Configuring Serilog in ASP.NET Core 2.2 web API
For this post, we will be using .NET Core version 2.2’s web api.
Click here to learn how to create a new web API
Why use Serilog?
Serilog provides basic diagnostic logging for many sinks including, but not limited to, the console, files, Amazon, Azure, etc. This article will demonstrate the console and file sinks. It is easy as 1, 2, 3 to set up with appsetting configurations.
1. Install Serilog Packages
To install packages either run:
dotnet add package
Or in Visual Studio go to Project > Add Nuget Packages…
Serilog.AspNetCore — the main driver
Serilog.Settings.Configuration — the provider that reads the appsetting configurations
Serilog.Sinks.Async — an async wrapper for other sinks, especially the file sink, that reduces the overhead of logging calls by delegating work to a background thread
Serilog.Sinks.Console — the default sink and most suitable for development
Serilog.Sinks.File — a suitable sink for production
2. Configuration Files
Replace “Logging” with “Serilog” in appsettings.json as shown below:
The “Default” minimum level limits the logging of specify project code. This is different from the “Override” key that limits the ASP.NET Core framework’s log events.
The “Name” key specifies the sink desired. To write to multiple sinks, add another object to the “WriteTo” array.
Note that the async sink wraps subsequent sinks. Even though the async sink will not offer much performance gain to the console, it will allow you to brag to all your friends of your elite async coding skills.
When you are ready for the production settings, add the following appsetting.Production.json to the root directory of your project next to the other appsettings.
The “MinimumLevel” is being overwritten here since debug is not too useful in production.
How can I roll my logs you may ask?
Well since the Serilog.Sinks.RollingFile package has been deprecated, it is now handled by the Serilog.Sinks.File package, which we downloaded earlier.
This example shows a rolling interval of a day and keeping logs for the last 7 days.
The “retainedFileCountLimit” deletes old files older the interval count specified. The default is 31 intervals if left null.
Buffered set to true improves write performance by permitting the underlying stream to buffer writes.
3. Hook Serilog into the Web API
Add the lines 2, 10, and 11 to Program.cs:
And that is it! You can now log anywhere in your application by importing Serilog and using the available Log class functions just as the examples below show: