Search code examples
c#.netloggingtrace

How to use the same name to initialize many TraceSource in multiple classes


I am in the process of adding logging to my c# application with the aid of the

System.Diagnostics.TraceSource

On the top of many classes now (UI, Processing, Data...) I have this :

private static TraceSource logger = new TraceSource("SourceName");

I want every class to be logging to a common source name, but without hardcoding it, like it is currently.

The source name would be provided by the top level application, that name corresponding to the one in the config file.

What is the best way to achieve this, except for adding a new string sourceName parameter into each and every class that has logging activated and pass it down from the program host class to the lowest data layer class?


Solution

  • Create a Static singleton which will have an empty property string called name. That property will be initialized by the originating process which will read it from settings, and then place it in the singleton's name property. Then when all the worker classes need the name, they will get it from the singleton's static property which was setup during initialization..