C# 添加日志的方式

1、使用小图标区分日志的信息、警告与报错,日志控件采用ListView;如果其他窗体需要调用添加日志使用委托进行绑定即可

 首先添加一个imageList用来绑定ListView的SmallImageList属性中

其次再设置ListView的Columns列属性,设置到Name与Width属性

对于日志信息可能显示不全的问题处理

 lstRcv.Columns[1].Width = lstRcv.ClientSize.Width - lstRcv.Columns[0].Width;

添加日志部分代码

        #region 添加日志
        private string CurrentTime
        {
            get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }
        }
        private void AddLog(int index, string infor)
        {
            if (!this.InvokeRequired)
            {
                ListViewItem lst = new ListViewItem("  " + CurrentTime, index);

                lst.SubItems.Add(infor);

                this.lstRcv.Items.Insert(0, lst);
            }
            else
            {
                this.Invoke(new Action(() =>
                {
                    ListViewItem lst = new ListViewItem("  " + CurrentTime, index);

                    lst.SubItems.Add(infor);

                    this.lstRcv.Items.Insert(0, lst);
                }));
            }
        }
        #endregion

实现效果

2、日志消息采用纯文本,能够节省内存消耗,采用日志类别,信息、警告、错误进行区分,使用控件Listbox显示日志

首先,添加Listbox到界面中,无需其他设置

其次,添加日志更新代码

        #region 添加日志
        private readonly object obj = new object();
        public void AddLogInfo(string message)
        {
            addLog(message, "消息");
        }
        public void AddLogWarning(string message)
        {
            addLog(message, "警告");
        }
        public void AddLogError(string message)
        {
            addLog(message, "错误");
        }
        private void addLog(string message, string type)
        {
            lock (obj)
            {
                Tools.Logs.Instance.Info(message);
                if (type == "消息")
                {
                    listLog?.Items.Insert(0, $"{DateTime.Now}  {type}  {message}");
                    if (listLog?.Items.Count > 1000)
                    {
                        listLog?.Items?.Clear();
                    }
                }
                else
                {
                    listErrorLog?.Items.Insert(0, $"{DateTime.Now}  {type}  {message}");
                    if (listErrorLog?.Items.Count > 1000)
                    {
                        listErrorLog?.Items.Clear();
                    }
                }
            }
        }
        #endregion

测试效果

3、日志写入到txt文档中,采用NLog库,使用Nuget将库安装到项目中即可,NLogConfig采用默认配置
        private Logger logger = NLog.LogManager.GetCurrentClassLogger(); //初始化日志类
        private static Logs _instance;

        private ManualResetEventSlim manualResetEventSlim = new ManualResetEventSlim(true);


        public static Logs Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new Logs();
                }
                return _instance;
            }
        }
        private Logs()
        {

        }

        #region info
        public void Info(string msg)
        {
            logger.Info(msg);

        }
        public DialogResult Info(string msg, MessageBoxButtons btns, MessageBoxDefaultButton defaultBtn = MessageBoxDefaultButton.Button1)
        {
            Info(msg);
            return MessageBox.Show(msg, "Info", btns, MessageBoxIcon.Information, defaultBtn);
        }
        public void Info(string message, Exception exception)
        {
            logger.Info(exception, message);
        }
        #endregion

        #region Warn
        /// <summary>
        /// 警告日志  --耗时日志操作
        public void Warn(DateTime start, string msg)
        {
            TimeSpan timeS = new TimeSpan();
            try
            {
                timeS = System.DateTime.Now - start;
                logger.Warn(string.Format("{0}共耗时:{1}ms", msg, timeS.Milliseconds));
            }
            catch { }
        }
        public void Warn(string msg)
        {
            logger.Warn(msg);
        }
        public DialogResult Warn(string msg, MessageBoxButtons btns, MessageBoxDefaultButton defaultBtn = MessageBoxDefaultButton.Button1)
        {

            Warn(msg);
            var res = MessageBox.Show(msg, "Warn", btns, MessageBoxIcon.Warning, defaultBtn);

            return res;
        }
        public void Warn(string message, Exception exception)
        {
            logger.Warn(exception, message);
        }
        #endregion

        #region Error
        public void Error(String msg)
        {
            logger.Error(msg);

        }
        public DialogResult Error(string msg, MessageBoxButtons btns, MessageBoxDefaultButton defaultBtn = MessageBoxDefaultButton.Button1)
        {
            manualResetEventSlim.Wait();
            manualResetEventSlim.Reset();
            Error(msg);

            var res = MessageBox.Show(msg, "Error", btns, MessageBoxIcon.Error, defaultBtn);
            manualResetEventSlim.Set();
            return res;

        }

        public DialogResult Error(string msg, string alarmType, MessageBoxButtons btns, MessageBoxDefaultButton defaultBtn = MessageBoxDefaultButton.Button1)
        {
            manualResetEventSlim.Wait();
            manualResetEventSlim.Reset();
            Error(msg);
            var res = MessageBox.Show(msg, "Error", btns, MessageBoxIcon.Error, defaultBtn);
            manualResetEventSlim.Set();
            return res;

        }
        public void Error(string message, Exception exception)
        {
            logger.Error(exception, message);
        }
        #endregion


        /// <summary>
        /// 调试日志
        /// </summary>
        /// <param name="msg">日志内容</param>
        public void Debug(String msg)
        {
            logger.Debug(msg);
        }

        /// <summary>
        /// 严重致命错误日志
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <remarks>
        ///     1.记录日志文件
        ///     2.控制台输出
        /// </remarks>
        public void Fatal(String msg)
        {
            logger.Fatal(msg);
        }
        public void Fatal(string message, Exception exception)
        {
            logger.Fatal(exception, message);
        }

        public void Trace(String msg)
        {
            logger.Trace(msg);
        }

        public void Trace(string message, Exception exception)
        {
            logger.Trace(exception, message);
        }

以上1、2两种方式需要记录日志到文件只需将NLog的添加日志添加到更新日志里即可

  • 13
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值