第一步通过nuget添加log4net.dll的引用
第二步
<!--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配置节点结束-->
第3步 在Common类库中添加LogHelper.cs,添加日志写入函数:
private static ILog log = LogManager.GetLogger("LogHelper"); public static void WriteLog(string errorMsg) { log.Error(" ----------------出错开始------------------- "+errorMsg+" ----------------出错结束------------------- "); }
第4步添加一个类MyExceptionFilterAttribute.cs:
public class MyExceptionFilterAttribute:HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //处理错误消息。跳转到一个错误页面 LogHelper.WriteLog(filterContext.Exception.ToString()); //页面跳转到错误页面 filterContext.HttpContext.Response.Redirect("/Error.html");//在根目录添加错误页面 } }
第五步在Global.asax文件的Application_Start()方法中加入以下代码:
//让Log4Net配置节点起作用,并注册我们的过滤器 log4net.Config.XmlConfigurator.Configure(); GlobalFilters.Filters.Add(new MyExceptionFilterAttribute());