Log4net
直接上代码
1 nuget 下载 log4net。这个不多说了,大家都会
2 web.config (下面是两套配置,我的项目webapi和mvc网站记录的文件夹不同)
web和webapi一起写的:
<log4net>
<root>
<appender-ref ref="WebLog" />
</root>
<appender name="WebLog" type="log4net.Appender.RollingFileAppender,log4net">
<file value="Log/" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd_HH".txt"" />
<maxSizeToRollBackups value="10" />
<maximumFileSize value="5MB" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<conversionPattern value="%d - %-5level - %c - %m%n" />
</layout>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
</appender>
</log4net>
web和webapi分开写的:
<configuration>
<!-- 这句很重要 -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<log4net>
<root>
<appender-ref ref="ApiLog" />
<appender-ref ref="WebLog" />
</root>
<appender name="ApiLog" type="log4net.Appender.RollingFileAppender">
<file value="Log\Api\" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd".log"" />
<maxSizeToRollBackups value="10" />
<maximumFileSize value="5MB" />
<staticLogFileName value="false" />
<filter type="log4net.Filter.LoggerMatchFilter">
<loggerToMatch value="ApiLog" />
</filter>
<filter type="log4net.Filter.DenyAllFilter" />
<layout type="log4net.Layout.PatternLayout,log4net">
<conversionPattern value="%d - %-5level - %c - %m%n" />
</layout>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
</appender>
<appender name="WebLog" type="log4net.Appender.RollingFileAppender">
<file value="Log\Web\" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd".log"" />
<maxSizeToRollBackups value="10" />
<maximumFileSize value="5MB" />
<staticLogFileName value="false" />
<filter type="log4net.Filter.LoggerMatchFilter">
<loggerToMatch value="WebLog" />
</filter>
<filter type="log4net.Filter.DenyAllFilter" />
<layout type="log4net.Layout.PatternLayout,log4net">
<conversionPattern value="%d - %-5level - %c - %m%n" />
</layout>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
</appender>
</log4net>
</configuration>
3 记录日志 在 Global.asax
void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
//log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
}
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();
string msg = "\r\n" + "StackTrace:\r\n" + ex.StackTrace
+ "\r\n\r\n" + "Message:\r\n"
+ ex.Message + "\r\n\r\n\r\n\r\n";
//根据不同的Log对象,执行记录
//记录api的异常
log4net.ILog log = log4net.LogManager.GetLogger("APILog");
//记录web的异常
log4net.ILog log = log4net.LogManager.GetLogger("WebLog");
log4net.Config.XmlConfigurator.Configure();
log.Info(msg);
Server.ClearError();
Response.Redirect("~/ErrorManager/ErrorPage");
}
PS :发布的时候,一定要到 bin目录下 找到 log4net.xml这个文件一起拷贝到站点!