処理されていないすべての例外を記録するLog4Net構成で作業しています。私は、ユーザーに基づいて特定のプロパティを各ログエントリに追加する必要があります。これを私のApplication_Errorイベントで以下のようにして正常に設定しました。完全なglobal.asaxですLog4Net、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を使いますか?これを行うより良い方法はありますか?そのようなThreadContext
に要求固有の値をロードすることは安全ではありません
おかげ
HttpContext.Currentがログに追加されたワーカースレッドにコピーする必要があるため、並列コードを使用する場合は注意が必要です。 –
global.asax.csではHttpContextUserProviderを呼び出しますか? – Rory
ASP.Netにはコンテキスト固有のストレージがあります。ここをクリックしてください:http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx – MatteoSp