What is the correct usage of TraceSource across a solution?

559 Views Asked by At

I've not worked with the System.Diagnostics.TraceSource package before so I want to make sure I implement it correctly. In the past I've used NLog (before that log4net) where you configure the settings in a config file (or programmatically) and in each class you declare this:

private static Logger Logger = LogManager.GetCurrentClassLogger();

then statements like this as required:

Logger.Error("some message", exc);

But with TraceSource you create a new TraceSource, set its properties and assign your listener(s) and then write your messages to it.

Do I create a TraceSource instance for every class like NLog? Or do I have one per application that all classes use? And if the former, it seems like at least I should centralize the creation of the TraceSource into a factory or something so the code is simplified and I'm not having to setup the settings, listeners etc every time I need use it. What's the proper usage here?

Note: due to the nature of how this code will be deployed, I cannot have a config file, I have to do it all programmatically.

1

There are 1 best solutions below

0
BozoJoe On

just use

class DracBlahBlah
{
  private static readonly TraceSource = new TraceSource("deathtoexecutives", SourceLevel.Error);
}

and in the other classes

class werewolf
{
  private static readonly TraceSource = new TraceSource("deathtoexecutives", SourceLevel.Error);
}

then assign the listeners using config

<system.diagnostics>
  <sharedListeners>
    <add name="p0rn" type="p0rn.Tracelistener, super.bad.crazytown" />
  </sharedListeners>

  <sources>
    <source name="deathtoexecutives" switchValue="Verbose">
      <listeners>
        <add name="p0rn" />
      </listeners>
    </source>