Log4Net 自定义级别,分别记录到不同的文件中

以下配置了二种写文件,第一种根据日期写文件yyyyMMdd.txt,第二种是写固定文件login.txt。


1, 下载Log4net组件:
http://logging.apache.org/log4net/download.html

2,将log4net.dll加到项目引用中;
 
3,在app.config中添加相关配置信息,文件内容如下:

   <?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="ChinaBank.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
    </sectionGroup>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net-net-1.0"/>
  </configSections>
  <log4net>
    <logger name="Daily.Logging">
      <level value="INFO"/>
      <appender-ref ref="DailyAppender" />
    </logger>
    <logger name="Login.Logging">
      <level value="INFO"/>
      <appender-ref ref="LoginAppender" />
    </logger>
    <appender name="DailyAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyyMMdd.'txt'" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%m%n" />
      </layout>
    </appender>
    <appender name="LoginAppender" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="Logs/login.txt" />
      <param name="AppendToFile" value="true" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d|%m|%n" />
      </layout>
    </appender>
  </log4net>
<!--这里为appSettings等其它节点信息-->
</configuration>
 
 
4,在AssemblyInfo.cs最下面添加(其中XXXXX.exe.config为app.config在bin\Debug中生成的文件名,以实际为准):
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "./XXXXX.exe.config", ConfigFileExtension = "config", Watch = true)]
 


5,在项目中使用Log4net:

//根据日期写文件yyyyMMdd.txt
log4net.ILog log = log4net.LogManager.GetLogger("Daily.Logging");  
log.Info("这是一条普通信息");    

//写固定文件login.txt
log4net.ILog log2 = log4net.LogManager.GetLogger("Login.Logging");
log2.Info("用户张三登录");

posted @ 2015-05-25 17:23  花道长  阅读(680)  评论(0编辑  收藏  举报