C# 整合log4net

1 下载并导入log4net.dll

下载地址:
http://logging.apache.org/log4net/download_log4net.cgi

下载内容:log4net-2.0.8-bin-newkey.zip

解压后找到 log4net.dll,并引入到项目中

2 配置app.config

"1.0" encoding="utf-8" ?>

  
    
"log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> "RollingFileAppender_DateTime" type="log4net.Appender.RollingFileAppender"> "File" value="..\log\Test.log"/> "AppendToFile" value="true"/> "RollingStyle" value="Size"/> "DatePattern" value="yyyy-MM-dd-HH"/> "StaticLogFileName" value="true"/> "MaxSizeRollBackups" value="30"/> "MaximumFileSize" value="5MB"/> "CountDirection" value="1"/> "log4net.Layout.PatternLayout"> "ConversionPattern" value="%d [%t] %-5p %c - %m%n"/> "INFO"/> "RollingFileAppender_DateTime"/>

3 配置assembly

AssemblyInfo.cs 最后追加:
[assembly: log4net.Config.DOMConfigurator(Watch = true)]

4 .NET Framework4.X

项目右键属性 ⇒ 应用程序 ⇒ 目标框架 ⇒ .NET Framework4.X
※ 与所使用的log4net.dll 版本一致

5 测试

using System;
using System.Windows.Forms;

namespace AddLogTest
{
    public partial class Form1 : Form
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            logger.Info("INFO___________________________");

            logger.Error("Error++++++++++++++++++++++++++");

            logger.Debug("Debug==============================");
        }
    }
}

输出:

logger.Info(“INFO___________________________”);

logger.Error(“Error++++++++++++++++++++++++++”);

(由于配置文件只设置了【INFO】模式,Debug内容没被输出)

你可能感兴趣的:(C#)