如何配置Microsoft企业库日志记录应用程序块以处理任何日志记录类别?
我正在尝试使用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 & Warnings">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
我试过设置logWarningsWhenNoCategoriesMatch
为假,但只是沉默的警告 - 它没有记录工作。
我也试过摆脱<notProcessed switchValue="All" .../>
特殊来源,但这似乎也没有任何效果。
任何人都知道是否有办法让这个工作?谢谢!
当你调用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
方法,并让您的整个应用程序使用一个企业库类别。
'notProcessed'特殊来源将匹配与类别来源不匹配的任何条目 - 因此您可以使用它来捕获它们。这里有更多的信息:https://entlib.codeplex.com/discussions/215189
<notProcessed switchValue="All" name="Unprocessed Category"/>
<listeners>
<add name="Rolling Flat File Trace Listener Unprocessed"/>
</listeners>
</notProcessed>
这是适用于我的解决方案,因为我不必更改源代码。谢谢! – Calvin 2016-04-12 17:47:18
@Tuxo - 真棒!我没有意识到'GetLogger'会以这种方式工作 - 我的__assumption__(d'oh)是'GetLogger'会返回一个匹配给定类型的记录器,有点像ServiceLocator模式。现在命名对我来说更有意义。谢谢!!! – Pandincus 2011-03-21 17:19:32
@Pandincus - 有一个GetLogger负载需要一个Type,这可能是您想要的。 – 2011-03-21 17:49:04