C#log4net配置

项目使用log4net,配置过程比较简单,想要实现各种需求,可以深入研究一下配置文件。

1、引用log4net.dll

2、使用命名空间 using log4net;

3、定义logger

public static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

4、定义配置文件,log4net.dll(或直接使用App.config)

5、调用配置文件

在Properties下面的AssemblyInfo中添加

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

或在Program.cs的Main方法中添加

log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo("log4net.config"));     

附使用的配置文件内容:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>  
  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> 
      <param name= "File" value= "logs\"/>
      <param name= "AppendToFile" value= "true"/>
      <param name= "MaxSizeRollBackups" value= "10"/>
      <param name= "StaticLogFileName" value= "false"/>
      <param name= "DatePattern" value= "yyyy-MM-dd&quot;.log&quot;"/>
      <param name= "RollingStyle" value= "Date"/>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="Debug" />
        <param name="LevelMax" value="Fatal" />
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="[%d] [%-5p] [%c] - %m%n" />
      </layout>
    </appender>
    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="Error" />
        <foreColor value="Red, HighIntensity" />
      </mapping>
      <mapping>
        <level value="Warn" />
        <foreColor value="Yellow" />
      </mapping>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="Warn" />
        <param name="LevelMax" value="Fatal" />
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />
      </layout>     
    </appender>

    <root>
      <level value="all" />
      <appender-ref ref="ColoredConsoleAppender"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
  </log4net>
</configuration>

其中

<lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> 

可以让多个exe共用一个log文件。

 

posted @ 2017-12-08 15:37  大江东去奔流到海  阅读(2869)  评论(0编辑  收藏  举报