Logger configuration

316 views
Skip to first unread message

Nicolas Tenoutasse

unread,
May 30, 2016, 10:25:43 AM5/30/16
to Serilog
Hi,

How do you do when you want to enrich your logging for a long time but not from the start?

Of course if you want to do it from the beginning, you can do it from the logger configuration
Log.Logger = new LoggerConfiguration()
                  .Enrich.WithProperty("App", APP_NAME)
                  .WriteTo.Seq("http://localhost:5341")
                  .CreateLogger();

And if you want to do it in a method, you have a few options lthat you have described for example in

But what if you want to do it for a certain period of time (that you don't know of course)
I found 2 ways, both a bit strange but for sure, the first one is really convoluted

You can recreate a Logger and make the new one points to the old one, something like:
Log.Logger = new LoggerConfiguration()
                  .Enrich.WithProperty("Shift", 2)
                  .WriteTo.Logger(Log.Logger)
                  .CreateLogger();

Or you can do something a bit less drastic by
Log.Logger = Log.Logger.ForContext("Shift", 2);

I noticed that serilog is clever enough to change the value of the property when there is already a property with the same name.
But still I wonder if there is a better way to do it?

Regards,
Nicolas

nblum...@nblumhardt.com

unread,
May 30, 2016, 6:17:16 PM5/30/16
to Serilog
Hi Nicolas,

This is a good scenario for a custom ILogEventEnricher. If you implement this interface, you can plug the resulting object into the logging pipeline using Enrich.With(enricher), and keep a reference to your enricher to turn enrichment on/off if necessary.

Let me know if you need more details.

Regards,
Nick
Reply all
Reply to author
Forward
0 new messages