1. 程式人生 > 其它 >C#中使用 Log4net 日誌輸出到本地檔案、Textbox或Listview

C#中使用 Log4net 日誌輸出到本地檔案、Textbox或Listview

方法一: 直接將配置檔案配置在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)] 輸出到自定義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中使用的時候的程式碼為

        //讀取配置檔案的資訊
        private ILog log  = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private void frmText_Load(object sender, EventArgs e)
        {
            //設定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);
 
        }

輸出到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();    
        }  
    }  
}  

在Form中使用的時候的程式碼為:

        //讀取配置檔案的資訊
        private ILog log  = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private void frmText_Load(object sender, EventArgs e)
        {

            //設定 ListView 列印日誌------------------------------------------------------
            var listview_logAppender = new ListViewBaseAppender()
            {
                listView = this.listView1,//註釋後 就只有檔案log  
                Layout = new PatternLayout(logPattern)
            };
            //相當於root標籤下的   <appender-ref ref="LogFile" />  
            log4net.Config.BasicConfigurator.Configure(listview_logAppender);

        }

十分感謝:

rainbow70626

https://www.cnblogs.com/rainbow70626/p/6168338.html