写在前面的:
在网上找的,再加上自己的心得
AssemblyInfo.cs:(加载配置文件也可以写到app.config中)
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "systemconfig/log4net.xml", Watch = true)]
Test.cs:
ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
log4net.xml(注意:要将此文件的属性设置为 如有较新的则复制):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<root>
<level value="all" />
<appender-ref ref="RollingLogFileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net" >
<file value="./logs/log.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyy-MM-dd".log"" />
<!--设置无限备份=-1 ,最大备份数为50-->
<maxSizeRollBackups value="50"/>
<!--每个文件的最大20k-->
<maximumFileSize value="20"/>
<!--
<maximumFileSize value="50MB" />
-->
<!--名称是否可以更改:
false为可以更改-->
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-2p %c %method %L- %m%n"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%L] - %m%n" />
</layout>
</appender>
</log4net>
补充:
Log4net中ConversionPattern的解释说明:http://www.cnblogs.com/calaio/archive/2006/05/29/412024.html
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value=" -----------------------header-------------------------- " />
<param name="Footer" value="-----------------------footer-------------------------- " />
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] %X{auth} - Line:%L %m%n" />
</layout>
%m(message):输出的日志消息,如ILog.Debug(…)输出的一条消息
%n(new line):換行
%d(datetime):输出当前语句运行的时刻
%r(run time):输出程序从运行到执行到当前语句时消耗的毫秒数
%t(thread id):当前语句所在的线程ID
%p(priority): 日志的当前优先级别,即DEBUG、INFO、WARN…等
%c(class):当前日志对象的名称
%L:输出语句所在的行号
%F:输出语句所在的文件名
%-数字:表示该项的最小长度,如果不够,则用空格填充