Pergunta

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?

Foi útil?

Solução

This disables all trace sources regardless to how they were registered (in code or in config.)

When you create a TraceSource (in code or config), it is added to a static list. There isn't a public API to get at that list. But that "private" key word is a sign for lesser developers to obey, not us. So we just kicked it down and take the reference to the variable which is rightfully ours. And then we can add/remove listeners, turn off the trace flags-- there is more than one way to disable trace.

This example will work in a single method, but the technique will/should work even if you don't have a reference to the TraceSource like this example has.

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)");
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top