Win7 + VisualStudio2010 + .NetFramework 4.0 + MVC3.0
第一步,首先从官网下载dll
http://logging.apache.org/log4net/index.html ,在项目添加引用log4net.dll
第二步,log4net配置
配置单独写一个配置文件log4net.config
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
<!-- Set root logger level to ERROR and its appenders -->
<root>
<level value="ALL"/>
<appender-ref ref="SysAppender"/>
</root>
<!-- Print only messages of level DEBUG or above in the packages -->
<logger name="WebLogger">
<level value="DEBUG"/>
</logger>
<appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net" >
<param name="File" value="D:/log/shipin/" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value=""Logs_"yyyyMMdd".txt"" />
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
<param name="Header" value="
----------------------header--------------------------
" />
<param name="Footer" value="
----------------------footer--------------------------
" />
</layout>
</appender>
<appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
</log4net>
日志可以写入各种数据库也可以各种方式写入文件,详细配置看官网
第三步,修改AssemblyInfo.cs,在最后添加一行
// 日志组件配置
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
第四步,创建LogHelper使用logger
public class LogHelper
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static void AddInfo(string str)
{
log.Info(str);
}
public static void AddDebug(string str)
{
log.Debug(str);
}
public static void AddWarn(string str)
{
log.Warn(str);
}
public static void AddFatal(string str)
{
log.Fatal(str);
}
public static void AddError(string str)
{
log.Error(str);
}
}
第五步,调用LogHelper
LogManager.LogHelper.AddError("a test error");
知其然,不知其所以然,记录下来,相信下文更精彩