0

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.

snappymcsnap
  • 2,050
  • 2
  • 29
  • 53
  • If you just want it boiled down to the basics, then I suggest this link: http://blog.stephencleary.com/2010/12/simple-and-easy-tracing-in-net.html – Bent Tranberg Mar 08 '17 at 21:30
  • @BentTranberg - good one, thank you for that. Looks like you would do it per-class for the most part, maybe per-module if you want to be able to turn on/off larger swaths of logging – snappymcsnap Mar 08 '17 at 22:06

1 Answers1

0

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>
BozoJoe
  • 6,117
  • 4
  • 44
  • 66