我正在使用Log4Net配置来记录所有未处理的异常。我需要将某些基于用户的属性添加到每个日志条目中。我已经在我的Application_Error事件中以如下方式成功设置了它。这是我的完整global.asaxLog4Net,ThreadContext和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
这似乎工作正常。但是,我有一些我无法回答的问题。
是我通过threadcontext添加用户特定属性的方式是否正确?即使在负载下,这是否会记录正确的信息?你什么时候会使用threadlogicalcontext?有一个更好的方法吗?
感谢
如果使用并行编码,请小心谨慎,因为如果将HttpContext.Current添加到日志中,HttpContext.Current可能需要复制到任何工作线程。 – 2011-10-25 00:01:55
在global.asax.cs中的哪个位置可以调用HttpContextUserProvider? – Rory 2012-08-19 17:31:56