Centralized & Structured .NET Logging with Serilog & Seq Part 2

Contextual Logging

After Part1 and the introduction to the basics of Serilog and Seq, we are now going to examine how we can add some context to our logging events.

When we say Context, we mean information that is implicitly added to the log event without including it in the actual log event submission.

Let’s see how this works…

Create Contextual Logger

In order to enable our Logger to ‘carry’ this context, we have to include the .Enrich.FromLogContext() part when we create it:

Add a property

Let’s add a property to the context using the static PushProperty method of the LogContext class that returns an IDisposable. As you can see, the context is only added to the call which is done within the using statement:

Add a structured object

One of the biggest advantages of Serilog is also available for our context. Structured objects can also be included. We will use the Person class (like in Part 1) in order to create an object to be added to our context:

Add a dynamic object

Dynamic objects can also be included. Imagine packing a number of properties into a dynamic object and adding this to your log event context:

Include the class name

I think this is straightforward:

We will get the same event in both cases with the class name being assigned to the SourceContext property:

Add Context using Custom Enrichers

There is one more way to add context to your logs by using concrete classes in order to encapsulate the logic you would like to include. All you need to do is implement the ILogEventEnricher interface like in the following example:

You can then add your ILogEventEnricher to your context: