7

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>
Paramesh
  • 371
  • 1
  • 3
  • 8
  • http://stackoverflow.com/questions/4376699/how-to-use-tracesource-across-classes or http://stackoverflow.com/questions/4867947/when-do-i-need-more-then-one-tracesource-in-code and also found this but not sure if it works: "ts.Switch.Level = SourceLevels.Verbose;" – Davide Piras Sep 01 '11 at 22:07
  • 1
    Nope, that is not what I am looking for. I know how to set the tracel level when I have access to the traceSource object. I need a way to change the level across all instances of traceSource's (for a given trace source name). – Paramesh Sep 01 '11 at 22:22
  • which class are you referring to? public class MyTraceSource : TraceSource is valid.. – Paramesh Sep 02 '11 at 00:04

1 Answers1

3

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.

M.Stramm
  • 1,289
  • 15
  • 29