今天试了下log4net的使用,总结了一下几个需要注意的地方,供大家少走弯路。
1.官方网站: http://logging.apache.org/log4net/
2.使用方法:下载上面的for .net的程序,然后引用log4net.dll
3.在程序中添加一个单独的配置文件,来存放log4net的配置。这里需要注意的是别忘了<log4net>节点,并且路径不要自以为是的加~\\ 切记!!!
下面是我的配置示例(我的配置名叫log4net.config),具体的各种配置请参考这里:http://www.joshua.org.cn/post/2007/04/Log4net.aspx
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="LogData\\" />
<appendToFile value="true" />
<datePattern value="yyyy-MM-dd.LOG" />
<maxSizeRollBackups value="10" />
<rollingStyle value="Date" />
<maximumFileSize value="10MB" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %u %c %l %m %n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
其实它的配置并不可怕,先学会其中的几个就ok了,以后的用着了再学。
4.在你的property目录下的AssemblyInfo.cs文件增加:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
5.在你的global中增加以下代码,初始化log4net
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));
}
6.调用代码:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
log4net.ILog log = log4net.LogManager.GetLogger("test");
log.Info("test 1");