HDLogUtil.cs 2.6 KB
using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CodeLibrary
{
    public class HDLogUtil
    {
        private static string logName = "";
        public static string LogName
        {
            get { return logName; }
            set
            {
                logName = value;
                LOGGER = LogManager.GetLogger(LogName);
            }
        }
        private static ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static Dictionary<int, DateTime> lastErrorLogTime = new Dictionary<int, DateTime>();
        public static System.Windows.Forms.RichTextBox logBox = null;
        public static int showCount = 50;
        public static bool debug_opened = false;
        static HDLogUtil()
        {
            XmlConfigurator.Configure();
        }

        public static void info(string msg)
        {
            LOGGER.Info(LOGGER.Logger.Name + " - " + msg);
            AddToBox(msg);
        }
        public static void debug(string msg)
        {
            LOGGER.Debug(LOGGER.Logger.Name + " - " + msg);
            if (debug_opened)
            {
                AddToBox(msg);
            }
        }

        public static void error(string errorMsg)
        {
            LOGGER.Error(LOGGER.Logger.Name + " - " + errorMsg);
            AddToBox(errorMsg);
        }
        private static void AddToBox(string msg)
        {
            try
            {
                if (logBox == null)
                {
                    return;
                }
                ShowLogPro(msg);
            }
            catch (Exception ex)
            {
                LOGGER.Error("出错:" + ex.StackTrace);
            }
        }
        private static int count = 0;
        private static void ShowLogPro(string msg)
        {
            try
            {
                if (count > showCount)
                {
                    count = 0;
                    logBox.Clear();
                }
                System.DateTime now = System.DateTime.Now;
                logBox.AppendText(now.ToLongTimeString() + "  " + msg + Environment.NewLine);
                count++;
            }
            catch (Exception ex)
            {
                LOGGER.Error("出错:" + ex.ToString());
            }
        }

        public static void ClearLog()
        {
            if (logBox != null)
            {
                logBox.Text = "";
                count = 0;
            }
        }
    }
}