Dot-Net

我可以以程式方式控制 WCF 跟踪嗎?

  • March 12, 2013

我最近閱讀了Chris Love 關於使用 WCF 跟踪來幫助進行故障排除的建議

他通過將新的 XML 部分添加到文件中來開啟跟踪功能,app.config此後我在這裡看到了針對相同技術的類似建議

但是,我們真的不想發送多個app.config文件。

而且我們絕對不希望我們的客戶在生產系統上修改它們!

有沒有辦法可以在 app.config 中設置 WCF 跟踪的各種設置,但跟踪是從程式碼中打開/關閉的?

理想情況下,我希望我的應用程序檢查系統資料庫並僅在存在某個值時才啟動跟踪。

我的建議是使用一個自定義TraceFilter,將其應用於附加到 WCF TraceSources 的所有偵聽器(即“System.ServiceModel”、“System.ServiceModel.MessageLogging”)。在 TraceFilter 的ShouldTrace()方法中,您可以根據應用程序可用的任何資訊有條件地抑制跟踪。

這是一些範常式式碼,您可以將其用作起點。有一個靜態幫助器類,它在應用程序的生命週期內全域確定一次是否應該啟用或禁用跟踪:

namespace WCF.Diagnostics
{
   using System.Diagnostics;

   public static class WcfDiagnosticsHelper
   {
       private readonly static bool _shouldTraceWcf;

       static WcfDiagnosticsHelper()
       {
           // here, determine if WCF Tracing should be enabled or not
           // i.e., read some custom settings from App.config or the registry etc...

           _shouldTraceWcf = true;
       }

       internal static bool ShouldTraceWcf
       {
           get { return _shouldTraceWcf; }
       }
   }

   public class WcfTraceFilter : TraceFilter
   {
       public override bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data)
       {
           // In here, check the static 'ShouldTraceWcf' property as well as the name of the originating TraceSource
           if (source != null && source.StartsWith("System.ServiceModel") && !WcfDiagnosticsHelper.ShouldTraceWcf)
               return false;
           return true;
       }
   }
}

在 App.config 中,您將像這樣配置 TraceFilter:

<system.diagnostics>
 <sources>
   <source name="System.ServiceModel" propagateActivity="true" switchValue="Warning">
     <listeners>
       <add name="LocalXmlFile" initializeData="WcfTracing.svclog" type="System.Diagnostics.XmlWriterTraceListener">
         <filter type="WCF.Diagnostics.WcfTraceFilter, WCF_Custom_TraceFilter"/>
       </add>
     </listeners>
   </source>
 </sources>
</system.diagnostics>

**

請注意,可以通過編寫自定義Trace Switch來實現類似的行為。主要區別在於 TraceSwitch 應用於 TraceSource,而 TraceFilter 應用於 TraceListener。不過,它會稍微多一些。

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