如何以编程方式添加RollingFlatFileTraceListenerData

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");

我该如何通过程序将新定义的监听器添加到监听器列表中?
1个回答

5

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

using D = System.Diagnostics;

...

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

   ...

}

我检查是否已经就位的唯一原因是因为我曾经看到过Application_Start()被触发了不止一次,尽管这种情况很少见。


Application_Start只有在应用程序池重启时才会触发多次。当一段时间内没有请求或根据回收规则时,IIS会自动执行此操作。不过这不应该成为问题,因为它将以全新的HttpApplication开始。 - Karl Cassar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接