MVC配置Log4Net
在Nuget中搜索Log4net ,在根目录中新建一个文件夹“error”,在根目录下新建一个错误页网页叫(error.html)
在“error”文件夹中创建MyExceptionAttribute.cs文件
/// <summary>
/// 这是异常过滤器
/// 要在FilterConfig中注册一下
/// </summary>
public class MyExceptionAttribute : HandleErrorAttribute
{
/// <summary>
/// 捕获异常
/// </summary>
/// <param name="filterContext"></param>
public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
Exception exception = filterContext.Exception;
//写入队列
ExcptionQueue.Enqueue(exception);
//跳到错误页
filterContext.HttpContext.Response.Redirect("/error.html");
}
/// <summary>
/// 创建队列
/// </summary>
public static Queue<Exception> ExcptionQueue = new Queue<Exception>();
}
- 打开App_Start文件夹中的FilterConfig.cs修改
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// filters.Add(new ErrorHandler.AiHandleErrorAttribute());
//自己的异常捕获上面是系统的
filters.Add(new WebApp.error.MyExceptionAttribute());
}
}
- 进入Web.config中添加配置信息
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<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="App_Data/" />
<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>
在根目录Global.asax的Application_Start()方法中配置
protected void Application_Start()
{
//log4net
log4net.Config.XmlConfigurator.Configure();
//开启线程,扫描异常信息队列
string filePath = Server.MapPath("/Log/");
ThreadPool.QueueUserWorkItem((a)=> {
while (true)
{
//队列是否有数据
if (WebApp.error.MyExceptionAttribute.ExcptionQueue.Count()>0)
{
//出队
Exception exception = WebApp.error.MyExceptionAttribute.ExcptionQueue.Dequeue();
if (exception != null)
{
写入日志文件
//string fileName = DateTime.Now.ToString("yyyy-MM-dd");
//File.AppendAllText(filePath + fileName + ".txt", exception.ToString(), System.Text.Encoding.UTF8);
ILog logger = LogManager.GetLogger("errorMsg");
logger.Error(exception.ToString());
}
else
{
Thread.Sleep(3000);
}
}
else
{
Thread.Sleep(3000);
}
}
},filePath);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
调试时使用开始执行不调试,程序异常时会在根目录的App_Data文件夹中生成错误信息的文本文件,记得网上找个好看的错误页
扩展
在根目录Global.asax文件中,新建一个Application_Error()方法
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
{
//跳转到错误页
Response.Redirect("/Error.html");
}
}