在ASP.NET MVC中使用Log4net記錄文件日誌

该文详细介绍了如何在.NETMVC项目中集成log4net进行日志管理,包括在NuGet安装log4net,配置Web.config以设置日志保存路径和格式,编写过滤器类ExceptionFilter来捕获并记录异常,以及在Global.asax中注册全局异常处理。这样,当程序出现错误时,会自动记录日志并重定向到错误页面。
摘要由CSDN通过智能技术生成

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);//註冊路由規則
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值