加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

如何设置特定于ASP.NET请求的log4net上下文属性?

发布时间:2020-12-15 20:16:57 所属栏目:asp.Net 来源:网络整理
导读:我一直在使用log4net来记录我们的ASP.NET网站的日志消息,最近我想添加有关发生错误的页面/处理程序的信息.因此,我决定将以下行添加到Global.asax中: void Application_BeginRequest(object sender,EventArgs e){ log4net.ThreadContext.Properties["page"]
我一直在使用log4net来记录我们的ASP.NET网站的日志消息,最近我想添加有关发生错误的页面/处理程序的信息.因此,我决定将以下行添加到Global.asax中:
void Application_BeginRequest(object sender,EventArgs e)
{
    log4net.ThreadContext.Properties["page"] = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
}

并且如智慧我将%属性{page}添加到我的转换模式中:

<conversionPattern value="%newline%date %-5level %property{page} - %message%newline%newline%newline" />

这对单个请求工作正常.但是在我的日志中,我注意到在ASP.NET请求期间页面属性可能会发生更改.我已经登录一个ASHX处理程序,在处理过程中,页面属性将更改为指向ASPX页面的其他值.我得出结论,ASP.NET有另一个请求,它的BeginRequest被执行,并且log4net.ThreadContext中的静态页面属性被更改为另一个值.

现在,我想维护每个请求的page属性,以便我可以一直将执行页面的路径记录到日志中.我试图找到一个答案,但我没有出来.推荐的方法来解决这个问题?我相信这是Web服务器事件记录的基本功能.

解决方法

由于ASP.NET does not guarantee的整个页面请求将被处理在同一个线程上,所以我更喜欢从HttpContext.Current as log4net processes获取答案记录事件.

以下GetCurrentPage类通过覆盖其ToString方法来实现log4net手动调用“Active Property Value”:

public class GetCurrentPage
{
  public override string ToString()
  {
      if (null != HttpContext.Current)
      {
          return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
      }
      return string.Empty; // or "[No Page]" if you prefer
  }
}

在Global.asax的Application_Start中,在log4net的GlobalContext中注册此类.

protected void Application_Start(object sender,EventArgs e)
{
    XmlConfigurator.Configure();
    GlobalContext.Properties["page"] = new GetCurrentPage();
}

当log4net写入该行的%属性{page}部分时,它将调用GetCurrentPage类的ToString方法,该方法将查找当前请求中的值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读