We have a huge C# codebase which does logging using .Net tracing and a custom trace listener. I am exploring option to dynamically change the tracing level (from Warning to Verbose etc..). I was hoping there was a way to change the trace level from the trace listener and I could modify the custom listener to change log level on the trace source. But that doesn't seem to be possible. Is there an easy way to get hold of tracesource object from trace listener (without reflection..)? I am trying to avoid deriving from TraceSource to implement dynamic tracing level as it will involve lot of code changes. Any suggestions?
Here is the typical way we do tracing is:
TraceSource ts = new TraceSource("TestLogSource");
ts.TraceEvent(TraceEventType.Warning, 0, "warning message");
ts.TraceEvent(TraceEventType.Error, 0, "error message");
<system.diagnostics>
<sources>
<source name="TestLogSource" switchName="GlobalSwitch">
<listeners>
<add name="TestLog"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="TestLog" initializeData="test.svclog" type="Library.RolloverXmlTraceListener, Library, Version=4.0.0.0, Culture=neutral, PublicKeyToken=1234.."/>
</sharedListeners>
<switches>
<add name="GlobalSwitch" value="Warning" />
</switches>
</system.diagnostics>
Nope, there is no way to do this without reflection and even with reflection it would be a hassle.
A TraceSource filters before it calls the listeners according to it's Switch property and you can not get the source TraceSource object from a TraceListener without reflection, so what you asked for is not doable (and not meant to be).
You could however implement the "dynamic filtering" in the listeners.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With