C# – Where should I put a project- or application-wide TraceSwitch in the design


I'm trying to enhance my program with some logging functionality provided by System.Diagnostics. As my Solution consists of several projects, I wanted to create a switch for the whole application and one for every project.

Now the question is, how can I achieve this and where should I put the switch definition?

Starting with the application wide switch, since there is no such thing as global variables in C# as I understood it, how could I achieve this?

Will putting

static TraceSwitch ApplicationSwitch = new TraceSwitch("Application", "Enables logging in the whole application.");

once in every class solve this or would this rather create as much switches as there are classes, each with the same name? (my guess is the latter)

Or should I put the initialization once in a separate class

static class GlobalSwitch
    static TraceSwitch Application = new TraceSwitch("Application", "Enables logging in the whole application.");

and reference to it from every other class like this

public OtherClass
    static TraceSwitch Application = GlobalSwitch.Application;

This would solve having 1 switch for a whole project, but is this a good practice?

Concerning the application wide switch, I would have to reference the project containing the GlobalSwitch class in every other project, which I would like to avoid if possible.

Some clues as to how this can be done the smart way would be very appreciated.

Best Solution

I usually wrap trace switches (and log functions) into a central logging assembly, exposing a static interface to the switch(es) and also static log methods that will call the underlying log functionality in use (usually Trace.Write-functions).

Related Question