Dot-Net

如何在 app.config 中定義自定義 TraceListener

  • July 24, 2009

我已經實現了一個自定義跟踪偵聽器(派生自TextWriteTraceListener),現在我想將我的應用程序設置為使用它而不是標準的TextWriteTraceListener.

首先,我添加了預設值TextWriteTraceListener以確保它可以正常工作並且確實可以。這是我的 app.config:

<configuration>
   <system.diagnostics>
       <trace autoflush="true" indentsize="4">
           <listeners>
               <add name="TextListener"  type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log" />
           <remove name="Default" />
           </listeners>
       </trace>
   </system.diagnostics>
</configuration>

現在我的跟踪偵聽器在MyApp.Utils命名空間中定義,它被稱為FormattedTextWriterTraceListener. 所以我將上面配置中的類型更改為MyApp.Utils.FormattedTextWriterTraceListener,它目前看起來像這樣:

<configuration>
   <system.diagnostics>
       <trace autoflush="true" indentsize="4">
           <listeners>
               <add name="MyTextListener" type="MyApp.Utils.FormattedTextWriterTraceListener" initializeData="trace.log" />
           <remove name="Default" />
           </listeners>
       </trace>
   </system.diagnostics>
</configuration>

但是,現在當我嘗試記錄某些內容時,我收到了一條ConfigurationErrorsException消息:

找不到類 MyApp.Utils.FormattedTextWriterTraceListener 的類型。

有誰知道我如何在配置中設置這個自定義監聽器,如果它甚至可能?

也嘗試指定一個程序集,如下所示:

<configuration>
   <system.diagnostics>
       <trace autoflush="true" indentsize="4">
           <listeners>
               <add name="TextListener" 
                   type="MyApp.Utils.FormattedTextWriterTraceListener, MyApp"
                   initializeData="trace.log" />
           <remove name="Default" />
           </listeners>
       </trace>
   </system.diagnostics>
</configuration>

引用自:https://stackoverflow.com/questions/1176582