One logger for a multi-project solution

Heres my solution to multi-assembly logging:

I set up the Mainlogger with the configuration as usual in the master assembly, i.e. the assembly responsible for creating and configuring the log. In my case the logging-master is a GUI application which interacts with a dll, which acutally does the work.

Then I installed Serilog in the slave-assembly and exposed a subscribe function to the master assembly like this:

void SubscribeLogging(ILogger masterlogger)
{
    Log.Logger = new LoggerConfiguration()
          .MinimumLevel.Debug()
          .WriteTo.Logger(masterlogger)
          .CreateLogger();
}

which i than call from the master assembly if necessary

myDll.SubscribeLogging(Log.ForContext("SourceContext", "myDll"));

As far as I can tell, one could manipulate the logging configuration to a certain degree, but I did not try using a completely different output template in the slave assemply.


Serilog lets you use a logger configuration per program; though it's possible to adjust logging class-by-class this is usually done after the fact with filtering and so-on.

The recommended approach is:

Set up Serilog as the first thing in Program.Main() or wherever your app's entry point is:

Log.Logger = new LoggerConfiguration()
  .WriteTo.Sink1()
  .WriteTo.Sink2()
  .CreateLogger();

Notice this sets up the static Log class. Elsewhere in your app you can now write:

Log.Information("This is a message");

and the message will be passed to both sinks. You can avoid the static Log and instead pass ILogger around, but unless you have strong preferences here, the static option is less hassle.

XML/appSettings configuration doesn't change any of this. It just moves some details to the config file, so changing the first block of code to:

Log.Logger = new LoggerConfiguration()
  .ReadFrom.AppSettings()
  .CreateLogger();

And adding:

<add key="serilog:write-to:Sink1" />
<add key="serilog:write-to:Sink2" />

to App.config will have the same effect. Configuration in code is often less hassle (fewer moving parts) if you can avoid the XML.

Tags:

Serilog