5

我有一个配置文件,例如:

<configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</configSections>

<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="Tracing" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
        <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.SystemDiagnosticsTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" type="System.Diagnostics.ConsoleTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="System Diagnostics Trace Listener"/>
    </listeners>
    <formatters>
        <add template="{message}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Text Formatter"/>
    </formatters>
    <categorySources>
          <add switchValue="All" name="AppLog">
    <listeners>
          <add name="System Diagnostics Trace Listener"/>
    </listeners>
  </add>
</categorySources>
<specialSources>
  <allEvents switchValue="All" name="All Events"/>      
  <notProcessed switchValue="All" name="Unprocessed Category"/>
  <errors switchValue="Off" name="Logging Errors &amp; Warnings"/>
</specialSources>

除了我拥有的控制台侦听器之外,我还想以编程方式定义一个 RollingFlatFileTraceListenerData:

var listener = new RollingFlatFileTraceListenerData("AppLog", @"c:\log.log", "", "", 0, "yyyyMMdd-hhmm", Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollFileExistsBehavior.Increment, Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollInterval.Hour, TraceOptions.LogicalOperationStack, "Text Formatter");

如何以编程方式将新定义的侦听器添加到侦听器列表中?

4

1 回答 1

5

通常,在 asp.net 应用程序中,以编程方式添加 TraceListeners 的一种简单方法是使用诊断程序的 Trace.Listeners.Add() 方法。我喜欢在 Application_Start() 上的 global.asax.cs 中执行此操作:

using D = System.Diagnostics;

...

protected void Application_Start()
{
   if (D.Trace.Listeners["MyTraceListener"] == null)
   {
      D.Trace.Listeners.Add(new MyTraceListener("") { Name = "MyTraceListener" });
   }

   ...

}

我检查它是否已经到位的唯一原因是因为我已经看到 Application_Start() 触发了不止一次,尽管很少发生。

于 2012-10-10T06:42:19.990 回答