我正在使用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