1,創建一個.NET MVC程序,然後在nuget程序包中安裝log4net.
2,在web.config中配置Log4Net
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!--log4net日誌記錄-->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<!--log4net日誌記錄組件配置-->
<log4net>
<appender name="RollingFileTracer" type="log4net.Appender.RollingFileAppender">
<file value="App_Data\\LogError\\"></file>
<appendToFile value="true"></appendToFile>
<rollingStyle value="Date"></rollingStyle>
<datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"></datePattern>
<staticLogFileName value="false"></staticLogFileName>
<param name="MaxSizeRollBackups" value="100"></param>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n記錄時間:%date%n線程ID:[%thread]%n日誌級別:%-5level%n出錯類:%logger property:[%property{NDC}]-%n錯誤描述:%message%newline%n"></conversionPattern>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR"></levelMin>
<levelMAX value="FATAL"></levelMAX>
</filter>
</appender>
<root>
<level value="ALL"></level>
<!--文件形式記錄日誌-->
<appender-ref ref="RollingLogFileAppender"></appender-ref>
<appender-ref ref="RollingFileTracer"></appender-ref>
</root>
</log4net>
3,然後就是在properties=》Assembyinfo.cs中添加以下代碼 ,來讀取配置文件。
//為項目配置Log4Net.config配置文件
[assembly:log4net.Config.XmlConfigurator(ConfigFile =@"Web.config",Watch =true)]
4,在.NET MVC項目中創建一個Filter文件夾,並在Filter文件夾里創建一個ExceptionFilter類。
/// <summary>
/// 異常處理過濾器 使用log4net記錄日誌 并跳轉至錯誤頁面
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,Inherited =true,AllowMultiple =true)]
public class ExceptionFilter:HandleErrorAttribute
{
ILog log = LogManager.GetLogger(typeof(ExceptionFilter));
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("~/Error.cshtml");
}
base.OnException(filterContext);
}
}
5,在App_Start下創建一個FilterConfig類,用來添加全局異常處理過濾器
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//添加全局異常處理過濾器
filters.Add(new ExceptionFilter());
}
6,最後在Global中進行註冊,這樣每次程序出現異常,都會進行異常的日誌記錄。
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();//自動註冊所有定義在當前應用程序中的區域
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);//創建全局過濾器
RouteConfig.RegisterRoutes(RouteTable.Routes);//註冊路由規則
}