ASP.NET MVC中Log4Net记录错误日志的使用

时间:2023-03-09 03:22:57
ASP.NET MVC中Log4Net记录错误日志的使用

第一、在管理NuGet程序包 =》下载 Log4Net

ASP.NET MVC中Log4Net记录错误日志的使用

第二、在web.config配置Log4Net

1:在<configuration>节点下 <configSections>节点中 配置log4Net节点引用。

<!--log4net日志记录-->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

ASP.NET MVC中Log4Net记录错误日志的使用

2:在<configSections>下后面 配置log4Net 日志记录组件

<!--log4net 日志记录组建配置-->
<log4net>
<!--定义输出到文件中-->
<appender name="RollingFileTracer" type="log4net.Appender.RollingFileAppender">
<!--定义文件存放位置-->
<file value="App_Data\\LogError\\"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/>
<staticLogFileName value="false"/>
<param name="MaxSizeRollBackups" value="100"/>
<layout type="log4net.Layout.PatternLayout">
<!--每条日志末尾的文字说明-->
<!--输出格式-->
<!--样例:2008-03-26 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info-->
<conversionPattern value="%n记录时间:%date %n线程ID:[%thread] %n日志级别: %-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%newline %n"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="FATAL" />
</filter>
</appender>

<root>
<level value="ALL"/>
<!--文件形式记录日志-->
<appender-ref ref="RollingLogFileAppender"/>
<appender-ref ref="RollingFileTracer"/>
</root>
</log4net>

ASP.NET MVC中Log4Net记录错误日志的使用

第三:在properties=>Assembyinfo.cs中添加以下代码,来读取配置文件

//为项目注册Log4Net.config配置文件
[assembly: log4net.Config.XmlConfigurator(ConfigFile = @"Web.config", Watch = true)]

ASP.NET MVC中Log4Net记录错误日志的使用

第四:自定义一个ExceptionControl类,继承 HandleErrorAttribute类 ,重写OnException方法

/// <summary>
/// 异常处理过滤器,使用log4net记录日志,并跳转至错误页面
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class ExceptionControl : HandleErrorAttribute
{
ILog log = LogManager.GetLogger(typeof(ExceptionControl));

public override void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)
{
string message = string.Format("消息类型:{0}\r\n消息内容:{1}\r\n引发异常的方法:{2}\r\n引发异常源:{3}"
, filterContext.Exception.GetType().Name
, filterContext.Exception.Message
, filterContext.Exception.TargetSite
, filterContext.Exception.Source + filterContext.Exception.StackTrace
);

//记录日志
log.Error(message);
//转向
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectResult("~/PageView/error/404.html");//跳转错误页,地址根据自己的改
}
base.OnException(filterContext);
}

}

ASP.NET MVC中Log4Net记录错误日志的使用

第五:在App_Start文件夹下的FilterConfig.cs修改代码。 Global.asax文件就不用修改了

ASP.NET MVC中Log4Net记录错误日志的使用

to:经过以上5步就实现了asp.net mvc中使用log4Net记录错误日志

ASP.NET MVC中Log4Net记录错误日志的使用

ASP.NET MVC中Log4Net记录错误日志的使用