如何在 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>
我正在使用一个 SharedListener,它应该接收来自所有 TraceSources 的所有输出,除非另有说明。使用上述语法,这需要为每个 TraceSource 手动输入。
每当我引入一个带有新 TraceSource 的新类时,我都必须更新 App.Config。如果多个程序使用该程序集,我必须更新多个 App.Config。更新这些条目时的拼写错误不会产生任何错误,它只会默默地忽略来自正确源的所有跟踪输出。
有没有一种方法可以通过 App.config 设置默认的 TraceListener,这样如果我想偏离默认值,我只需要命名特定的 TraceSources?
最佳答案
我没有找到很好的解决方案,所以我所做的至少是集中创建 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>
的所有听众将添加到我使用此代码创建的所有跟踪源。
关于c# - 在 App.config 中为所有 TraceSources 添加一个默认的 TraceListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24509595/