如何設置特定於 ASP.NET 請求的 log4net 上下文屬性?
我一直在使用 log4net 來記錄我們的 ASP.NET 網站的日誌消息,最近我想添加有關發生錯誤的頁面/處理程序的資訊。因此,我決定在 Global.asax 中添加以下行:
void Application_BeginRequest(object sender, EventArgs e) { log4net.ThreadContext.Properties["page"] = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath; }同樣明智地我添加
%property{page}到我的轉換模式:<conversionPattern value="%newline%date %-5level %property{page} - %message%newline%newline%newline" />這適用於單個請求。但後來我注意到在我的日誌中頁面屬性可能會在 ASP.NET 請求期間發生變化。我登錄了一個 ASHX 處理程序,在其處理過程中,頁面屬性將更改為指向 ASPX 頁面的不同值。我的結論是有另一個請求來到 ASP.NET 並且它
BeginRequest被執行並且靜態頁面屬性log4net.ThreadContext被更改為另一個值。現在,我想維護每個請求的頁面屬性,以便我可以將執行頁面的路徑一致地記錄到日誌中。我試圖找到答案,但我一無所獲。解決此問題的推薦方法是什麼?我確信這是 Web 伺服器事件記錄的非常基本的功能。
由於 ASP.NET不保證整個頁面請求將在同一個執行緒上處理,我更喜歡從 HttpContext.Current 獲取答案,因為 log4net 處理 日誌事件。
以下類通過覆蓋其方法
GetCurrentPage實現了 log4net 手冊所稱的“活動屬性值” :ToStringpublic class GetCurrentPage { public override string ToString() { if (null != HttpContext.Current) { return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath; } return string.Empty; // or "[No Page]" if you prefer } }
Application_Start在 log4net 的 GlobalContext中的 Global.asax 中註冊這個類。protected void Application_Start(object sender, EventArgs e) { XmlConfigurator.Configure(); GlobalContext.Properties["page"] = new GetCurrentPage(); }當 log4net 寫入該
%property{page}行的一部分時,它將呼叫ToString我們GetCurrentPage類的方法,該方法將在目前請求中查找值。
在 ASP.NET 上下文中儲存屬性值
HttpContext.Current.Items.Add("yourProperty", value)它將可從 log4net 佈局中獲得:<layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%aspnet-context{yourProperty}" /> </layout>在這裡找到更多細節。