我正在尝试将Common Infrastructure Libraries for .NET(Common.Logging)与Enterprise Library 4.1的Logging Application Block一起使用。根据{{3}},这是受支持的。
我遇到的问题是,当我尝试记录某些东西时,就像这样(在本例中我是在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以接受任何类别,即使它没有定义。< / p>
以下是我的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
设置为false,但这只会使警告静音 - 它不会使记录工作。
我也试过摆脱<notProcessed switchValue="All" .../>
特殊来源,但这似乎也没有任何影响。
任何人都知道是否有办法让这个工作?谢谢!
答案 0 :(得分:4)
&#39; notProcessed&#39;特殊来源将匹配任何与类别来源不匹配的条目 - 因此您可以使用它来捕获它们。这里有更多信息:https://entlib.codeplex.com/discussions/215189
<notProcessed switchValue="All" name="Unprocessed Category"/>
<listeners>
<add name="Rolling Flat File Trace Listener Unprocessed"/>
</listeners>
</notProcessed>
答案 1 :(得分: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
方法,并让整个应用程序使用一个企业库类别。