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)");