log4net使用教程

1、引入log4net组件

在Visual Studio中选中所需添加log4net的项目,点击鼠标右键,选择【管理NuGet程序包】

log4net使用教程_第1张图片

输入关键字log4,查找对应程序包,并点击安装

log4net使用教程_第2张图片

完成完成之后,你可以在引用中看到已经成功引用log4net

log4net使用教程_第3张图片

2:App.config中添加section节点

  <configSections>
    <section 其他setion节点信息等/>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

3:添加log4net点(基本完整)

  <log4net>
    <root>
      <level value="all" />
      <appender-ref ref="INFOAppender" />
      <appender-ref ref="DEBUGAppender" />
      <appender-ref ref="WARNAppender" />
      <appender-ref ref="ERRORAppender" />
      <appender-ref ref="FATALAppender" />
      <appender-ref ref="ColoredConsole" />
      <appender-ref ref="TraceAppender" />
    </root>
    <appender name="INFOAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\\INFO\\" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.log'" />
      <staticLogFileName value="false"/>
      <maxSizeRollBackups value="100" />
      <maximumFileSize value="10MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="INFO"/>
      </filter>
    </appender>
    <appender name="DEBUGAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\\DEBUG\\" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.log'" />
      <staticLogFileName value="false"/>
      <maxSizeRollBackups value="100" />
      <maximumFileSize value="10MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="DEBUG"/>
        <param name="LevelMax" value="DEBUG"/>
      </filter>
    </appender>
    <appender name="WARNAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\\WARN\\" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.log'" />
      <staticLogFileName value="false"/>
      <maxSizeRollBackups value="100" />
      <maximumFileSize value="10MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="WARN"/>
        <param name="LevelMax" value="WARN"/>
      </filter>
    </appender>
    <appender name="ERRORAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\\ERROR\\" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.log'" />
      <staticLogFileName value="false"/>
      <maxSizeRollBackups value="100" />
      <maximumFileSize value="10MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="ERROR"/>
        <param name="LevelMax" value="ERROR"/>
      </filter>
    </appender>
    <appender name="FATALAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\\FATAL\\" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.log'" />
      <staticLogFileName value="false"/>
      <maxSizeRollBackups value="100" />
      <maximumFileSize value="10MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="FATAL"/>
        <param name="LevelMax" value="FATAL"/>
      </filter>
    </appender>
    <!--调试模式,输出日志到控制台-->
    <appender name="ColoredConsole" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR"/>
        <foreColor value="Red, HighIntensity"/>
        <!--<backColor value="Green" />-->
      </mapping>
      <mapping>
        <level value="DEBUG"/>
        <foreColor value="Yellow, HighIntensity"/>
        <backColor value="Green"/>
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
      <layout type="log4net.Layout.PatternLayout">
        <param name="conversionPattern" value="%newline*******************************************%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline*******************************************%newline" />
      </layout>
    </appender>
  </log4net>

4:在使用log4net的程序的顶部添加 [assembly: log4net.Config.DOMConfigurator(Watch = true)]

using System.Reflection;
......

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace TestConsole
{

    class Program
    {
       //......
    }
}

5:添加log4net.Config.DOMConfigurator.Configure(); 否则可能log4net不能正常写入文件,如果不添加该条语句,log对象的 isDebugEnabled IsErrorEnabled IsInfoEnabled IsFatalEnabled等属性全部是flase

其次Program.cs中的Main初始化:log4net.Config.DOMConfigurator.Configure();
注意此初始化加到顶部,以为初始化窗口的时候就需要初始化它:
        static void Main()
        {
            log4net.Config.DOMConfigurator.Configure();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

6:log4net的封装类

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Helper
{
    /// <summary>
    /// 对log4net的封装
    /// </summary>
    public class LogHelper
    {
        private ILog logger;

        public LogHelper( ILog log )
        {
            this.logger = log;
        }

        public void Info( object message )
        {
            this.logger.Info(message);
        }

        public void Info( object message, Exception e )
        {
            this.logger.Info(message, e);
        }

        public void Debug( object message )
        {
            this.logger.Debug(message);
        }

        public void Debug( object message, Exception e )
        {
            this.logger.Debug(message, e);
        }

        public void Warming( object message )
        {
            this.logger.Warn(message);
        }

        public void Warming( object message, Exception e )
        {
            this.logger.Warn(message, e);
        }

        public void Error( object message )
        {
            this.logger.Error(message);
        }

        public void Error( object message, Exception e )
        {
            this.logger.Error(message, e);
        }

        public void Fatal( object message )
        {
            this.logger.Fatal(message);
        }

        public void Fatal( object message, Exception e )
        {
            this.logger.Fatal(message, e);
        }
    }

    public class LogFactory
    {
        static LogFactory( )
        {
        }

        public static LogHelper GetLogger( Type type )
        {
            return new LogHelper(LogManager.GetLogger(type));
        }

        public static LogHelper GetLogger( string str )
        {
            return new LogHelper(LogManager.GetLogger(str));
        }
    }
}


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