Log4Net配置笔记----
首先,添加对log4net.dll的引用。
在Web.config文件下的Configuration节点下添加Log4Net的配置信息:
<!--Log4Net配置节点-->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<!-- Define some output appenders -->
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt"/>
<appendToFile value="true"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="10240KB"/>
<rollingStyle value="Size"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
<!--Log4Net配置节点结束-->
添加一个类MyExceptionFilterAttribute.cs:
public class MyExceptionFilterAttribute:HandleErrorAttribute
{ public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext); //处理错误消息。跳转到一个错误页面
LogHelper.WriteLog(filterContext.Exception.ToString());
//页面跳转到错误页面
filterContext.HttpContext.Response.Redirect("/Shared/Error");
}
}
在Common类库中添加LogHelper.cs,添加日志写入函数:
private static ILog log = LogManager.GetLogger("LogHelper");
public static void WriteLog(string errorMsg)
{
log.Error("\n----------------出错开始-------------------\n"+errorMsg+"\n----------------出错结束-------------------\n");
}
在Global.asax文件的Application_Start()方法中加入以下代码:
//让Log4Net配置节点起作用,并注册我们的过滤器
log4net.Config.XmlConfigurator.Configure();
GlobalFilters.Filters.Add(new MyExceptionFilterAttribute());
一切大功告成!