2012-05-02 128 views
1

我正在转换某些代码以使用Microsoft跟踪。我想要的是在一个项目中定义所有侦听器,然后从其他程序集中使用它们,而不必在那里显式加载它们。自动加载所有新跟踪源的跟踪侦听器

为了澄清,这是我现在在做什么:

<?xml version="1.0" encoding="utf-8" ?> 
    <configuration> 
    <system.diagnostics> 
     <trace autoflush="true"> 
     <listeners> 
      <add name="myListener" type="ConsoleApplication4.LogListener, ConsoleApplication4"/> 
      <remove name="Default" /> 
     </listeners> 
     </trace> 
    </system.diagnostics> 
    </configuration> 

和C#代码:

var b = Trace.Listeners; 
TraceSource tr = new TraceSource("Blah", SourceLevels.All); 
tr.Listeners.Add(b["myListener"]); 
tr.TraceEvent(TraceEventType.Warning, 5, "Hello"); 

我想是myListener被自动添加到任何新跟踪源我创建时无需像现在这样查看它。这可能吗?

回答

1

定义跟踪源,其听众一起在配置:

<system.diagnostics> 
    <sources> 
    <source name="Blah" switchValue="Warning"> 
     <listeners> 
     <add name="myListener" /> 
     </listeners> 
    </source> 
    </sources> 
    <!-- Note these are in sharedListeners rather than trace --> 
    <sharedListeners> 
    <add name="myListener" ... /> 
    </sharedListeners> 
    <!-- Autoflush still works as expected --> 
    <trace autoflush="true" /> 
</system.diagnostics> 

然后构建代码的TraceSource你已经被(它的踪影水平将在配置的switchValue覆盖)的方式,不要” t添加任何侦听器并正常登录。