2

In order to disable FirebirdSQL logging, I need to add the following code (See here) to app.config:

<system.diagnostics>
    <sources>
      <source name="FirebirdSql.Data.FirebirdClient" switchValue="Off">
        <listeners>
          <clear />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>

This succeeds, i.e. nothing is logged. Now I have do do this in C# code, but everything is logged despite my code:

TraceSource ts = new TraceSource("FirebirdSql.Data.FirebirdClient");
ts.Switch = new SourceSwitch("sourceSwitch", "Off");
var listeners = ts.Listeners;
listeners.Clear();
ts.Switch.Level = SourceLevels.Off;

which I added to the assemblies that execute SQL statements.

What am I missing?

4

1 回答 1

1

这将禁用所有跟踪源,无论它们是如何注册的(在代码中或在配置中)。

当您创建 TraceSource(在代码或配置中)时,它会被添加到静态列表中。没有公共 API 可以进入该列表。但是那个“私人”关键词是较小的开发人员要遵守的标志,而不是我们。所以我们只是把它踢下来,并引用我们理所当然的变量。然后我们可以添加/删除监听器,关闭跟踪标志——禁用跟踪的方法不止一种。

此示例将在单个方法中工作,但即使您没有像此示例那样对 TraceSource 的引用,该技术也将/应该工作。

TraceSource source = new TraceSource("foo");
SourceSwitch onOff = new SourceSwitch("onOff", "Verbose");

onOff.Level = SourceLevels.Verbose;

ConsoleTraceListener console = new ConsoleTraceListener();

source.Switch = onOff;
bool alreadyDone = false;
foreach (var listener in source.Listeners)
{
    if (typeof(ConsoleTraceListener) == listener.GetType())
    {
        alreadyDone = true;
    }
}
if (!alreadyDone)
{
    source.Listeners.Add(console);
}

source.TraceInformation("Hellow World! The trace is on!");

List<WeakReference>  traceSources = 
           (List<WeakReference>)typeof(TraceSource)
               .GetField("tracesources", BindingFlags.NonPublic | BindingFlags.Static)
               .GetValue(source);

foreach (WeakReference weakReference in traceSources)
{
    TraceSource target = (TraceSource)weakReference.Target;
    source.TraceInformation(
          "Somebody, in code or config, registered this trace source " + target.Name);
    target.Listeners.Clear();
}
source.TraceInformation(
       "Can you still see this? (No you can't, I cleared all the listeners)");
于 2013-06-07T17:45:21.917 回答