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

标签 asp.net properties log4net httpcontext

我一直在使用 log4net 来记录 ASP.NET 网站的日志消息,最近我想添加有关发生错误的页面/处理程序的信息。因此,我决定将以下行添加到 Global.asax:

void Application_BeginRequest(object sender, EventArgs e)
{
    log4net.ThreadContext.Properties["page"] = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
}

同样,我将 %property{page} 添加到我的转化模式中:

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

这对于单个请求效果很好。但后来我在日志中注意到页面属性可能会在 ASP.NET 请求期间发生更改。我登录了一个 ASHX 处理程序,在处理过程中,页面属性将更改为指向 ASPX 页面的不同值。我得出的结论是,有另一个请求传入 ASP.NET,并且它的 BeginRequest 被执行,并且 log4net.ThreadContext 中的静态页面属性被更改为另一个值。

现在,我想维护每个请求的页面属性,以便我可以将执行页面的路径一致地记录到日志中。我试图寻找答案,但一无所获。解决这个问题的推荐方法是什么?我确信这是 Web 服务器事件日志记录的非常基本的功能。

最佳答案

自 ASP.NET does not guarantee整个页面请求将在同一个线程上处理,我更喜欢从 HttpContext.Current as log4net processes 获得答案日志记录事件。

下面的GetCurrentPage类实现了log4net手册中所说的"Active Property Value"通过重写其 ToString 方法:

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
  }
}

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

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

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

关于asp.net - 如何设置特定于 ASP.NET 请求的 log4net 上下文属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9702066/

相关文章:

android - 将数据写入 assets 目录下的 .properties 文件

c# - 是否有必要使用 log4net 为 ASP.NET MVC 实现异步日志记录?

c# - 其中包含字符串操作的调试语句的最佳实践是什么?

log4net - 限制来自 smtpappender (log4Net) 的电子邮件

用于链接字符串中的 url 的 C# 代码

properties - C++/CLI 速记属性

c# - 有什么区别...? [C# 属性 GET/SET 方式]

asp.net - 处理 TextBox 中的 ENTER 按钮,ASP.NET

c# - 需要以编程方式为 BulletedList 创建点击事件

c# - OpenPop.net 获取实际消息文本