Serilog is a popular logging library for .NET that provides a flexible and extensible way to log messages from applications.
One of the key features of Serilog is the ability to Enrich Log Events with additional contextual information that can help troubleshoot and debug.
In this blog post, we will explore how to create a Custom Enricher with Serilog to add custom properties to log events.
To create a custom enricher with Serilog, we should define a class that implements the
Let's start by creating a new class called
AspNetCoreEnvironmentEnricher that implements the
Enrich method is called for each log event, and we can use it to add custom properties to the
logEvent parameter. The
propertyFactory parameter can be used to create new properties that we can add to the log event.
Using the Serilog Enricher
Now that we have our custom enricher class, let's use it with Serilog. We can add it to the logger configuration like this:
In this example, we added our custom enricher to the logger configuration using the
Enrich.With method. We passed the current user's name "Alice" to the constructor of our enricher.
Now, when we log a message, the
UserName property will be added to the log event:
[Information Development] Hello, world!
Creating a custom enricher with Serilog is a simple and powerful way to add contextual information to log events.
By implementing the
ILogEventEnricher interface and using the
propertyFactory parameter, we can add any custom properties we need to help in troubleshooting and debugging our applications.