【问题标题】:Log4Net, ThreadContext, and Global.asaxLog4Net、ThreadContext 和 Global.asax
【发布时间】:2010-11-07 03:42:04
【问题描述】:

我正在处理一个 Log4Net 配置,它将记录所有未处理的异常。我需要根据用户将某些属性添加到每个日志条目中。我在 Application_Error 事件中以下列方式成功设置了它。这是我完整的 global.asax

Imports log4net
Imports log4net.Config

    Public Class Global_asax
        Inherits System.Web.HttpApplication

        'Define a static logger variable
        Private Shared log As ILog = LogManager.GetLogger(GetType(Global_asax))

        Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
            ' Fires when the application is started
            ConfigureLogging()
        End Sub

        Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs when an unhandled error occurs
            Dim ex As Exception = Server.GetLastError()
            ThreadContext.Properties("user") = User.Identity.Name
            ThreadContext.Properties("appbrowser") = String.Concat(Request.Browser.Browser, " ", Request.Browser.Version)
            If TypeOf ex Is HttpUnhandledException AndAlso ex.InnerException IsNot Nothing Then
                ex = ex.InnerException
            End If
            log.Error(ex)
            ThreadContext.Properties.Clear()
        End Sub

        Private Sub ConfigureLogging()
            Dim logFile As String = Server.MapPath("~/Log4Net.config")
            log4net.Config.XmlConfigurator.ConfigureAndWatch(New System.IO.FileInfo(logFile))
            log4net.GlobalContext.Properties("appname") = System.Reflection.Assembly.GetExecutingAssembly.GetName.Name
        End Sub
    End Class

这似乎工作正常。但是,我有一些问题我无法回答。

我通过线程上下文添加用户特定属性的方式是否正确?即使在负载下,这是否总是记录正确的信息?你什么时候使用threadlogicalcontext?有没有更好的方法来做到这一点?

谢谢

【问题讨论】:

    标签: asp.net vb.net logging error-handling log4net


    【解决方案1】:

    像这样将特定于请求的值加载到ThreadContext 是不安全的。原因是 ASP.NET 共享线程来服务请求。事实上,它经常这样做。

    您可以改用LogicalThreadContext,但这只是将值存储在用于远程处理的调用上下文中。

    AFAIK 没有 HttpContext 特定的上下文存储,所以你可以做的是分配一个“值提供者”实例作为你的线程上下文,并且在运行时它会在这个类上调用 .ToString() 来获取值。

    public class HttpContextUserProvider
    {
       public override string ToString()
       {
          return HttpContext.Current.User.Identity.Name;
       }
    }
    

    它不太理想,但它有效。

    【讨论】:

    • 如果你使用并行编码要小心,因为 HttpContext.Current 如果添加到日志中,可能需要复制到任何工作线程。
    • 您会在 global.asax.cs 中的哪个位置调用 HttpContextUserProvider?
    • ASP.Net 具有特定于上下文的存储。见这里:msdn.microsoft.com/en-us/library/…
    • 我确实将特定于请求的值放入 ThreadContext 中,并发现异常是使用来自其他请求的值记录的。 “但是,只是将值存储在调用上下文中”会给出什么样的限制?存储特定于请求的值是否有效?
    【解决方案2】:

    Ben 的回答是对的。

    但是,与其他一些用户一样,我仍然对如何进行操作有些迷茫。这个log4net Context problems with ASP.Net thread agility 帖子,尤其是这个Marek Stój's Blog - log4net Contextual Properties and ASP.NET,通过一些优秀的代码示例为问题提供了更多背景信息。

    我强烈推荐 Marek Stój 的实现,尽管在我的情况下需要将 ThreadContext.Properties["UserName"] 替换为 ThreadContext.Properties["User"]。

    我在我的 Logger 类中添加了一个 BeginRequest 方法,我从 Application_AuthenticateRequest 调用该方法,它加载了所有相关的 log4net 属性。

    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        Logger.BeginRequest(Request);
    }
    

    以及方法代码:

    public static void BeginRequest(System.Web.HttpRequest request)
    {
        if (request == null) return;
    
        ThreadContext.Properties["ip_address"] = AdaptivePropertyProvider.Create("ip_address", IPNetworking.GetMachineNameAndIP4Address());
        ThreadContext.Properties["rawUrl"] = AdaptivePropertyProvider.Create("rawUrl", request.RawUrl);
    
        if (request.Browser != null && request.Browser.Capabilities != null)
            ThreadContext.Properties["browser"] = AdaptivePropertyProvider.Create("browser", request.Browser.Capabilities[""].ToString());
    
        if (request.IsAuthenticated && HttpContext.Current.User != null)
            ThreadContext.Properties["User"] = AdaptivePropertyProvider.Create("user", HttpContext.Current.User.Identity.Name);
    }
    

    我发现我必须传入 Request 对象,而不是在方法中使用 HttpContext.Current.Request。否则我会丢失用户和身份验证信息。请注意,IPNetworking 类是我自己的,因此您需要提供自己的获取客户端 IP 的方法。 AdaptivePropertyProvider 类直接来自 Marek Stój。

    【讨论】:

    • 这会将自适应属性对象分配给TheadContext 属性集合,但最初的问题不是我们不能指望该集合正确持久吗?我认为自适应属性处理程序需要在全局上下文中分配为属性...
    • 鉴于我们正在尝试记录(在这种情况下)给定的 Web 会话,我不确定哪种全局对象适用,因此这些值将由各个线程进行上下文化,对吗?
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2012-01-30
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2018-03-07
    相关资源
    最近更新 更多