首页 > 代码库 > C#中使用Log4net日志输出到本地文件、Textbox或Listview

C#中使用Log4net日志输出到本地文件、Textbox或Listview

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

1、参考链接:http://blog.sina.com.cn/s/blog_642e41c201014pml.html

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

<configSections>  
    <!--在配置选项中加入log4net的引用-->  
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>  
  </configSections>  
  <log4net>  
    <appender  name="LogFile" type="log4net.Appender.RollingFileAppender,log4net" >  
      <param name="File" value="../../logs/log.txt" /> <!--定义用文件来保存日志,生成的文件log.txt放在logs目录中,logs文件夹和应用程序生成的bin文件夹在同一目录下。-->  
      <param name="AppendToFile" value="false" />  
      <param name="RollingStyle" value="Date" />  
      <param name="DatePattern" value="yyyy.MM.dd" />  
      <param name="StaticLogFileName" value="true" />  
      <layout type="log4net.Layout.PatternLayout,log4net">  
        <!--定义输出风格-->  
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />  
        <param name="Header" value="  ----------------------header--------------------------  " />  
        <param name="Footer" value="  ----------------------footer--------------------------  " />  
      </layout>  
    </appender>  
    <appender>  
      <!--一个配置文件可以有很多appender,一个appender节就相当于一个日志输出介质或方法。-->  
    </appender>  
    <logger name="logApp">  
      <!--定义logger对象的名字为logApp,以方便在代码中使用logger-->  
        <!--配置项可以不配置-->  
        <level value="ALL" />  
        <!--定义输出的信息等级为所有其中包括Fatal.Error.Warn.Info.Debug-->  
      </logger>  
      <root>  
        <!--定义日志输出的方式和等级-->  
        <level value="INFO" />  
        <appender-ref ref="LogFile" /><!--选择了文件输出,注意粗体部分对应的名称-->  
      </root>  
    </log4net>  

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

  参考链接:http://www.cnblogs.com/zfanlong1314/p/3662679.html

  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  
{  
    /// <summary>  
    /// 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);  
    /// </summary>  
    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标签下的   <appender-ref ref="LogFile" />  
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://download.csdn.NET/detail/sc6231565/9620527

 

原文链接: 

c# log4net 日志输出到 本地文件 textbox listview DEMO

C#中使用Log4net日志输出到本地文件、Textbox或Listview