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