c# - 在 App.config 中为所有 TraceSources 添加一个默认的 TraceListener

标签 c# .net app-config system.diagnostics tracelistener

如何在 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/

相关文章:

c# - 在 Visual Studio 的单元测试中出现错误 "Cannot start more than one local run"

c# - 访问路径...在 .net 中的文件上传期间被拒绝

c# - List Clear() 方法是否会破坏子级 [C#.NET]?

c# - C# 的 OPC 示例应用程序

c# - Xamarin.Forms 不编译 Android 项目

c# - DocumentDB 查询中的运算符之间

c# - 发布 .NET Web 应用程序时出现 "Index was outside the bounds of the array"错误

c# - 如何告诉 C# 使用哪个配置文件?

c# - TraceSource 名称是如何在 .NET 程序中解析的?

c# - 在 app.config 中使用 <rollForwardenabled ="true"/>