7

如何在 net 4.0 c# 项目中定义一个默认的 TraceListener,它会自动添加到所有 TraceSources 中?

目前我必须列出我在 App.config 文件中使用的每个命名 TraceSource,如下所示:

  <system.diagnostics>
  <sharedListeners>
      <add name="MyListener" type="MyListenerType,MyAssemblyName" />
  </sharedListeners>
    <sources>
      <source name="Class1" switchValue="All">
        <listeners><add name="MyListener"></add></listeners>
      </source>
      <source name="Class2" switchValue="All">
        <listeners><add name="MyListener"></add></listeners>
      </source>
      <source name="Class3" switchValue="All">
        <listeners><add name="MyListener"></add></listeners>
      </source>
      ... repeat for a gazillion classes ...
    </sources>
  <system.diagnostics>

除非另有说明,否则我正在使用应接收来自所有 TraceSource 的所有输出的 SharedListener。使用上述语法,这需要为每个 TraceSource 手动输入。

每当我引入一个带有新 TraceSource 的新类时,我都必须更新 App.Config。如果多个程序使用该程序集,我必须更新多个 App.Config。更新这些条目时的拼写错误不会产生任何错误,它只会默默地忽略来自正确源的所有跟踪输出。

有没有办法可以通过 App.config 设置默认的 TraceListener,这样如果我想偏离默认值,我只需要命名特定的 TraceSources?

4

2 回答 2

4

我没有找到很好的解决方案,所以我所做的至少是集中创建 TraceSources。然后我可以将 app.config 中的任何“跟踪”侦听器添加到这些新创建的源中:

TraceSource toReturn = new TraceSource(name, filterLevel);

//remove the default trace listener; don't 'clear' the listeners entirely, because that would undo changes made in app.config; this is a decent compromise
toReturn.Listeners.Remove("Default");

//add all global trace listeners from the app.config
toReturn.Listeners.AddRange(Trace.Listeners);

return toReturn;

现在,我添加的任何侦听器<system.diagnostics> \ <trace> \ <listeners>都将添加到我使用此代码创建的所有跟踪源中。

于 2015-09-24T21:55:15.780 回答
1

您可以在机器配置中添加一个默认侦听器,但这会影响比您想要影响的应用程序更多的应用程序。

于 2014-07-01T12:52:06.423 回答