asp.net - Log4Net、ThreadContext 和 Global.asax

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

我正在开发一个 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

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

我通过线程上下文添加用户特定属性的方式正确吗?即使在负载下,这也会始终记录正确的信息吗?什么时候会使用threadlogiccontext?有更好的方法吗?

谢谢

最佳答案

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

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

据我所知,没有 HttpContext 特定的上下文存储,因此您可以做的是分配一个“值提供程序”实例作为您的线程上下文,并且在运行时它将调用此类上的 .ToString() 来获取值。

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

虽然不太理想,但确实有效。

关于asp.net - Log4Net、ThreadContext 和 Global.asax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1066062/

相关文章:

asp.net - javascript 中带有字母数字检查的文本框

vb.net - 如何检测何时意外通过引用传递了 ReadOnly 属性?

svn - 如何让 'git log' 显示像 'svn log -v' 这样的文件名

java - 在 Java 中反复打开和关闭 PrintWriter 对象是不好的做法吗?

java - 在 Eclipse 中配置 Logback

asp.net - 如何在 Controller 中获取路由 url?

javascript - onclick 事件在 Internet Explorer 中不起作用

asp.net - 此处不允许页面,因为它不扩展类 'System.Web.UI.MasterPage'

c# - 我怎么知道我是否在迭代集合的最后一项?

.net - 如何在 VB.NET 中自动处理另一个类/模块中的表单事件?