2011-03-20 296 views
4

我正在嘗試使用Common Infrastructure Libraries for .NET(Common.Logging)和Enterprise Library 4.1的日誌記錄應用程序塊。根據docs,這是支持的。如何配置Microsoft企業庫日誌記錄應用程序塊以處理任何日誌記錄類別?

我遇到的問題是,當我嘗試登錄的東西,像這樣(在這個例子中,我在ASP.NET MVC應用程序):

public ActionResult Index() 
{ 
    ViewBag.Message = "Welcome to ASP.NET MVC!"; 

    ILog log = LogManager.GetCurrentClassLogger(); 
    log.Info("Hello world!"); 

    return View(); 
} 

而不只是簡單的日誌消息,我在事件日誌中收到錯誤:

消息:沒有類別'TestApp.Controllers.HomeController'的顯式映射。

那麼,Common.Logging中似乎沒有任何選項來設置默認類別,並且我無法弄清楚如何配置LoggingConfiguration以接受任何類別,即使它不是定義。

這裏是我的LoggingConfiguration的一個片段:

<loggingConfiguration name="Logging Application Block" tracingEnabled="true" 
    defaultCategory="General" logWarningsWhenNoCategoriesMatch="true"> 
... 
    <categorySources> 
    <add switchValue="All" name="General"> 
     <listeners> 
     <add name="Formatted EventLog TraceListener" /> 
     <add name="Email TraceListener" /> 
     </listeners> 
    </add> 
    </categorySources> 
    <specialSources> 
    <allEvents switchValue="All" name="All Events" /> 
    <notProcessed switchValue="All" name="Unprocessed Category" /> 
    <errors switchValue="All" name="Logging Errors &amp; Warnings"> 
     <listeners> 
     <add name="Formatted EventLog TraceListener" /> 
     </listeners> 
    </errors> 
    </specialSources> 
</loggingConfiguration> 

我試過設置logWarningsWhenNoCategoriesMatch爲假,但只是沉默的警告 - 它沒有記錄工作。

我也試過擺脫<notProcessed switchValue="All" .../>特殊來源,但這似乎也沒有任何效果。

任何人都知道是否有辦法讓這個工作?謝謝!

回答

3

當你調用LogManager.GetCurrentClassLogger() Common.Logging將使用您的調用類的類型,類別:

public static ILog GetCurrentClassLogger() 
{ 
    StackFrame frame = new StackFrame(1, false); 
    return Adapter.GetLogger(frame.GetMethod().DeclaringType); 
} 

如果你想用這種方法(雖然建議是不要過分使用這種方法因爲它檢查StackFrame)然後,是的,你需要爲每個你正在登錄的類創建一個類別。這將重新創建Log4Net中使用的一種分層記錄器。但是這種方法並不理想,因爲它不可維護。

你應該能夠通過使用LogManager.GetLogger(string name)超載而不是GetCurrentClassLogger來解決這個問題。它看起來像傳入的名稱將用作登錄到Enterprise Library中的類別。因此,您可以將類別名稱定義爲常量並將其傳遞給GetLogger方法,並讓您的整個應用程序使用一個企業庫類別。

+0

@Tuxo - 真棒!我沒有意識到'GetLogger'會以這種方式工作 - 我的__assumption__(d'oh)是'GetLogger'會返回一個匹配給定類型的記錄器,有點像ServiceLocator模式。現在命名對我來說更有意義。謝謝!!! – Pandincus 2011-03-21 17:19:32

+0

@Pandincus - 有一個GetLogger負載需要一個Type,這可能是您想要的。 – 2011-03-21 17:49:04

4

'notProcessed'特殊來源將匹配與類別來源不匹配的任何條目 - 因此您可以使用它來捕獲它們。這裏有更多的信息:https://entlib.codeplex.com/discussions/215189

<notProcessed switchValue="All" name="Unprocessed Category"/> 
    <listeners> 
     <add name="Rolling Flat File Trace Listener Unprocessed"/> 
    </listeners> 
</notProcessed> 
+1

這是適用於我的解決方案,因爲我不必更改源代碼。謝謝! – Calvin 2016-04-12 17:47:18

相關問題