LogUtil.cs 6.6 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.Reflection;
using System.Drawing;
using System.Runtime.ExceptionServices;
using System.Collections.Concurrent;
using System.Threading;

namespace OnlineStore.Common
{
    public class LogUtil
    {
        public static readonly ILog AIOLog = LogManager.GetLogger("AIOBOX");
        private static LogUtil instance = new LogUtil();
        public delegate void ShowLog(string msg, Color color);
        public static readonly ILog LOGGER = LogManager.GetLogger("RollingLogFileAppender");
        public static readonly ILog rfidLog = LogManager.GetLogger("RfidLog");
        public static ConcurrentDictionary<int, DateTime> lastErrorLogTime = new ConcurrentDictionary<int, DateTime>();

        public static System.Windows.Forms.RichTextBox logBox = null;

        public static int showCount = 15;

        public static bool debug_opened = false;


        public static void info(ILog log, string msg)
        {
            if (log == null)
            {
                return;
            }
            log.Info(msg);
            AddToBox(msg, Color.Black);
            //clear();
        }
        public static void info(ILog log, string msg, Color color)
        {
            log.Info(msg);
            AddToBox(msg, color);
        }
        public static void debug(ILog log, string msg, Color color)
        {
            log.Debug(msg);
            if (debug_opened)
            {
                AddToBox(msg, color);
            }
        }
        public static void debug(ILog log, string msg)
        {
            log.Debug(msg);
            if (debug_opened)
            {
                AddToBox(msg, Color.Gray);
            }
        }

        public static void RfidLog(string msg)
        {
            rfidLog.Debug(msg);
        }

        public static void error(string errorMsg, int type, int seconds = 10)
        {
            try
            {
                if (lastErrorLogTime.ContainsKey(type))
                {
                    TimeSpan span = DateTime.Now - lastErrorLogTime[type];
                    if (span.TotalSeconds > seconds)
                    {
                        lastErrorLogTime[type] = DateTime.Now;
                        error(LOGGER, errorMsg);
                    }
                }
                else
                {
                    lastErrorLogTime.TryAdd(type, DateTime.Now);
                    error(LOGGER, errorMsg);
                }
            }
            catch (Exception ex)
            {
                LOGGER.Error(" 打印日志【" + type + "-" + errorMsg + "】出错:" + ex.ToString());
            }
        }
        public static void error(ILog log, string errorMsg, Exception ex = null)
        {
            if (errorMsg.Trim().Equals("") && (ex == null))
            {
                return;
            }
            if (ex == null)
            {
                log.Error(errorMsg);
            }
            else
            {
                log.Error(errorMsg, ex);
            }
            AddToBox(errorMsg, Color.Red);
        }
        private static object lockObj = "";
        private static void AddToBox(string msg, Color color)
        {
            if (Monitor.TryEnter(lockObj, 2))
            {
                try
                {
                    ShowLogPro(msg, color);
                }
                catch (Exception ex)
                {
                    LOGGER.Error("出错:", ex);
                }
                finally
                {
                    Monitor.Exit(lockObj);
                }
            }
            else
            {
                LOGGER.Debug("ShowLogPro【" + msg + "】失败,未得到锁");
            }
        }
        private static List<string> logList = new List<string>();
        public static string LastText = "";
        [HandleProcessCorruptedStateExceptions]
        private static void ShowLogPro(string msg, Color color)
        {
            try
            {
                if (logList.Count >= showCount)
                {
                    logList.RemoveAt(0);
                }
                string text = "";
                foreach (string str in logList)
                {
                    text += str;
                }
                System.DateTime now = System.DateTime.Now;
                logList.Add(now.ToLongTimeString() + "  " + msg + Environment.NewLine);
                if (logBox == null)
                {
                    return;
                }
                LastText = text;
                if (logBox.Visible)
                {
                    logBox.Text = text;

                    //  logBox.Focus(); //使文本框获取焦点
                    logBox.AppendText(now.ToLongTimeString() + "  " + msg + Environment.NewLine); //增加文本

                    TimeSpan span = DateTime.Now - lastTime;
                    if (span.TotalSeconds > 3000000)
                    {
                        lastTime = DateTime.Now;
                        logBox.Select(logBox.Text.Length, 0);  //设置光标的位置到文本尾 
                        logBox.ScrollToCaret(); //滚动到控件光标处 
                    }
                }
            }
            catch (AccessViolationException e)
            {
                LOGGER.Error(" ShowLogPro 出错:" + e.ToString());
            }
            catch (Exception ex)
            {
                LOGGER.Error("出错:" + ex.ToString());
            }
        }
        private static DateTime lastTime = DateTime.Now;
        public static void UpdateLogbox()
        {
            if (logBox != null && logBox.Visible)
            {
                logBox.Text = LastText;

                TimeSpan span = DateTime.Now - lastTime;
                if (span.TotalSeconds > 3000000)
                {
                    lastTime = DateTime.Now;
                    logBox.Select(logBox.Text.Length, 0);  //设置光标的位置到文本尾 
                    logBox.ScrollToCaret(); //滚动到控件光标处 
                }
            }
        }
        public static void ClearLog()
        {

            if (logBox != null)
            {
                LastText = "";
                logList.Clear();
                logBox.Text = "";
            }
        }
        public static void debug(string msg)
        {
            debug(LOGGER, msg);
        }
        public static void error(string errorMsg, Exception ex = null)
        {
            error(LOGGER, errorMsg, ex);
        }
        public static void info(string msg)
        {
            info(LOGGER, msg);
        }

    }
}