Log4Net 在ASP.NET WebForm 和 MVC的全局配置

2023-02-16,,,,

使用log4net可以很方便地为应用添加日志功能。应用Log4net,开发者可以很精确地控制日志信息的输出,减少了多余信息,提高了日志记录性能。同时,通过外部配置文件,用户可以不用重新编译程序就能改变应用的日志行为,使得用户可以根据情况灵活地选择要记录的信息。

那么我们如何在Web项目中使用Log4Net呢?

配置方面请点击链接跳转上一笔记:

ASP.NET的错误处理机制之二(实例log4net)

这次主要针对上次的错误机制讲解如何进行Log4Net 在ASP.NET WebForm 和 MVC的全局配置

一、MVC中的全局配置

在项目中添加一个全局应用程序类Global.asax,如下图所示:

方法中添加如下代码:

      protected void Application_Start(object sender, EventArgs e)
      {
      #region 应用程序启动时,自动加载配置log4Net
        XmlConfigurator.Configure();
      #endregion
      }

      protected void Application_Error(object sender, EventArgs e)
      {
      #region 捕获全局异常

      Exception error = Server.GetLastError().GetBaseException();
      Exception ex = Server.GetLastError().GetBaseException();
      string ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") == null ?
      Request.ServerVariables.Get("Remote_Addr").ToString().Trim() :
      Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
      string logpath = Server.MapPath("~/Log/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
      StringBuilder builder = new StringBuilder();
      builder.AppendLine(string.Format("========== {0} Application_Error BEGIN ==========", DateTime.Now));
      builder.AppendLine("Ip:" + ip);
      builder.AppendLine("浏览器:" + Request.Browser.Browser.ToString());
      builder.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());
      builder.AppendLine("操作系统:" + Request.Browser.Platform.ToString());
      builder.AppendLine("页面:" + Request.Url.ToString());
      builder.AppendLine("错误信息:" + ex.Message);
      builder.AppendLine("错误源:" + ex.Source);
      builder.AppendLine("异常方法:" + ex.TargetSite);
      builder.AppendLine("堆栈信息:" + ex.StackTrace);
      builder.AppendLine("========== Application_Error END ===================");

      lock (logpath)
      {
      try
      {
      using (var writer = new StreamWriter(logpath, true))
      {
      ZX.B2C.GoodBaby.Common.LogHelper.WriteLog(typeof(RequestNotification), builder.ToString());
      }
      }
      catch
      {
      // 防止写文件时,文件被人为打开无法写入等
      // 记录日志报错不做处理,不应影响用户继续使用
      }
      }

      Server.ClearError();
      Response.Redirect("/Error/ErrorPath404");//跳出至404页面

      #endregion
      }

二、WebForm中的全局配置

在项目中添加一个全局应用程序类Global.asax,如下图所示:

方法中添加如下代码:

    protected void Application_Start(object sender, EventArgs e)
    {
    #region 应用程序启动时,自动加载配置log4Net

    XmlConfigurator.Configure();

    #endregion
    }
    /// <summary>
    /// 捕获全局异常
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    protected void Application_Error(object sender, EventArgs e)
    {
    #region 捕获全局异常

    Exception error = Server.GetLastError().GetBaseException();
    Exception ex = Server.GetLastError().GetBaseException();
    string ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") == null ?
    Request.ServerVariables.Get("Remote_Addr").ToString().Trim() :
    Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
    string logpath = Server.MapPath("~/Log/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
    StringBuilder builder = new StringBuilder();
    builder.AppendLine(string.Format("========== {0} Application_Error BEGIN ==========", DateTime.Now));
    builder.AppendLine("Ip:" + ip);
    builder.AppendLine("浏览器:" + Request.Browser.Browser.ToString());
    builder.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());
    builder.AppendLine("操作系统:" + Request.Browser.Platform.ToString());
    builder.AppendLine("页面:" + Request.Url.ToString());
    builder.AppendLine("错误信息:" + ex.Message);
    builder.AppendLine("错误源:" + ex.Source);
    builder.AppendLine("异常方法:" + ex.TargetSite);
    builder.AppendLine("堆栈信息:" + ex.StackTrace);
    builder.AppendLine("========== Application_Error END ===================");

    lock (logpath)
    {
    try
    {
    using (var writer = new StreamWriter(logpath, true))
    {
    ZX.B2C.GoodBaby.Common.LogHelper.WriteLog(typeof(RequestNotification), builder.ToString());
    }
    }
    catch
    {
    // 防止写文件时,文件被人为打开无法写入等
    // 记录日志报错不做处理,不应影响用户继续使用
    }
    }

    Server.ClearError();
    Response.Redirect("~/Error.htm");

    #endregion
    }

原文链接:

Log4Net 在ASP.NET WebForm 和 MVC的全局配置

Log4Net 在ASP.NET WebForm 和 MVC的全局配置的相关教程结束。

《Log4Net 在ASP.NET WebForm 和 MVC的全局配置.doc》

下载本文的Word格式文档,以方便收藏与打印。