博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#中使用Log4net日志输出到本地文件、Textbox或Listview
阅读量:7093 次
发布时间:2019-06-28

本文共 6519 字,大约阅读时间需要 21 分钟。

网上很多配置log4net的方法,但是排行靠前的 根本就没有说明清除,导致浪费了两个小时来搞清楚如何配置,真是无语,特写此文,给那些刚接触log4net的朋友

1、参考链接:

此方法是直接将配置文件配置在app.config

  第二种方式就是单独将配置文件配置在log4net.config中,网上大多数都是这种方法,但是却没有说明关键的一步

  参考链接:

  1. 新建一个配置文件,log4net.config配置方法同成web.config或app.config一致;
  2.如果windows应用程序请把配置文件设为:复制到输出目录 修改方法:在log4net.config上右击-->属性--->把
"复制到输出目录" 
值改为
true
;
  3.在要用到log4的地方命名空间上边加上:[assembly: log4net.Config.XmlConfigurator(ConfigFile = 
"log4net.config"
, Watch = 
true
)]

 

2、输出到自定义Textbox日志输出

using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using log4net.Appender;  using System.Windows.Forms;  using log4net.Core;  using log4net.Layout;    namespace log4myself  {      ///       /// Usage:      ///     log4net.Config.BasicConfigurator.Configure();      ///     var logPattern = "%date [%thread] %-5level %logger !%M - %message%newline";      ///     var logAppender = new TextBoxBaseAppender()      ///     {      ///         TextBox = this.textBox2,      ///         Layout = new PatternLayout(logPattern)      ///     };      ///           ///     ((log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetLoggerRepository()).Root.AddAppender(logAppender);      ///       public class TextBoxBaseAppender : AppenderSkeleton      {          public TextBoxBase TextBox { get; set; }            public TextBoxBaseAppender()          {          }            protected override void Append(LoggingEvent loggingEvent)          {              if (this.TextBox == null)              {                  return;              }                if (!this.TextBox.IsHandleCreated)              {                  return;              }                if (this.TextBox.IsDisposed)              {                  return;              }                var patternLayout = this.Layout as PatternLayout;                var str = string.Empty;              if (patternLayout != null)              {                  str = patternLayout.Format(loggingEvent);                    if (loggingEvent.ExceptionObject != null)                  {                      str += loggingEvent.ExceptionObject.ToString() + Environment.NewLine;                  }              }              else              {                  str = loggingEvent.LoggerName + "-" + loggingEvent.RenderedMessage + Environment.NewLine;              }                if (!this.TextBox.InvokeRequired)              {                  printf(str);              }              else              {                  this.TextBox.BeginInvoke((MethodInvoker)delegate                  {                      if (!this.TextBox.IsHandleCreated)                      {                          return;                      }                        if (this.TextBox.IsDisposed)                      {                          return;                      }                      printf(str);                  });              }          }            private void printf(string str)          {              //若是超过10行 则清楚              if (TextBox.Lines.Length > 50)              {                  TextBox.Clear();              }              this.TextBox.AppendText(str);          }      }  }

  在Form中使用的时候的代码为:

//读取配置文件的信息  log1 = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);    //设置textbox打印日志  var logPattern = "%d{yyyy-MM-dd HH:mm:ss} --%-5p-- %m%n";  var textBox_logAppender = new TextBoxBaseAppender()  {      TextBox = this.textBox1,//注释后 就只有文件log      Layout = new PatternLayout(logPattern)  };  //相当于root标签下的   
log4net.Config.BasicConfigurator.Configure(textBox_logAppender);

3、输出到Listview代码为:

using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using log4net.Appender;  using System.Windows.Forms;  using log4net.Core;  using log4net.Layout;    namespace log4myself  {      public class ListViewBaseAppender : AppenderSkeleton      {          public ListView listView { get; set; }            public ListViewBaseAppender()          {          }            protected override void Append(LoggingEvent loggingEvent)          {              if (this.listView == null)              {                  return;              }                if (!this.listView.IsHandleCreated)              {                  return;              }                if (this.listView.IsDisposed)              {                  return;              }                var patternLayout = this.Layout as PatternLayout;                var str = string.Empty;              if (patternLayout != null)              {                  str = patternLayout.Format(loggingEvent);                    if (loggingEvent.ExceptionObject != null)                  {                      str += loggingEvent.ExceptionObject.ToString() + Environment.NewLine;                  }              }              else              {                  str = loggingEvent.LoggerName + "-" + loggingEvent.RenderedMessage + Environment.NewLine;              }                if (!this.listView.InvokeRequired)              {                  printf(str);              }              else              {                  this.listView.BeginInvoke((MethodInvoker)delegate                  {                      if (!this.listView.IsHandleCreated)                      {                          return;                      }                        if (this.listView.IsDisposed)                      {                          return;                      }                        printf(str);                  });              }          }            private void printf(string str)          {              if (listView.Items.Count>50)              {                  listView.Items.Clear();              }                ListViewItem item = new ListViewItem();              item.Text = str.ToString();                 listView.BeginUpdate();              listView.Items.Add(item);              listView.Items[listView.Items.Count - 1].EnsureVisible();//滚动到最后                listView.EndUpdate();            }      }  }

Demo 下载:

 

原文链接: 

转载地址:http://mjiql.baihongyu.com/

你可能感兴趣的文章
Android小知识-Retrofit框架的介绍以及使用方式
查看>>
设计模式(八)——策略模式
查看>>
Java多线程 -- 锁降级
查看>>
vux之x-input使用以及源码解读
查看>>
vue指令
查看>>
打死也不敢说自己火的面试题更新第二弹
查看>>
Android应用内悬浮窗,无需一切权限,适配所有ROM和厂商FloatWindow
查看>>
iOS逆向之旅(基础篇) — 汇编(三) — 汇编下的 Switch语句
查看>>
通俗易懂--决策树算法、随机森林算法讲解(算法+案例)
查看>>
1024程序员节最新福利之2018最全java资料集合
查看>>
《图解http》笔记
查看>>
ReactNative集成到原生项目
查看>>
为什么大部分编程语言的数组的下标都从0开始?
查看>>
react16.7.0-alpha hooks的api介绍
查看>>
『中级篇』 Linux网络命名空间(25)
查看>>
JS计算精度小记
查看>>
js的各种距离计算(较全)
查看>>
微信小程序异步API为Promise简化异步编程
查看>>
关于java泛型大大小小的那些事
查看>>
此面试题版本落后-请勿观看
查看>>