About a year ago, I wrote the post Structured logging with Serilog which covered the basics of using Serilog 2.0. I’ve just revisited this post and found Serilog 2.5 has changed things a little.
I’m not going to go over what Serilog does etc. but instead just list the same code from my original post, but working with the latest NuGet packages.
So install the following packages into your application using NuGet
- Serilog
- Serilog.Sinks.RollingFile
- Serilog.Sinks.Console
Serilog.Sinks.Console is used instead of Serilog.Sinks.Literate now, which has been deprecated.
Here’s the code. The only real change is around the JsonFormatter
Log.Logger = new LoggerConfiguration() .WriteTo.Console() .WriteTo.RollingFile( new JsonFormatter(renderMessage: true), "logs\\sample-{Date}.txt") .MinimumLevel.Verbose() .CreateLogger(); Log.Logger.Information("Application Started"); for (var i = 0; i < 10; i++) { Log.Logger.Information("Iteration {I}", i); } Log.Logger.Information("Exiting Application");
Now, let’s add something new to this post, add the following NuGet package
- Serilog.Settings.AppSettings
In my original post I pointed out that Serilog seemed to be aimed towards configuration through code, but the Serilog.Settings.AppSettings package allows us to use the App.config for our configuration.
Change you Log.Logger code to the following
Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger();
and now in your App.config, within the configuration section, put the following
<appSettings> <add key="serilog:minimum-level" value="Verbose" /> <add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" /> <add key="serilog:write-to:RollingFile.pathFormat" value="logs\\sample-{Date}.txt" /> <add key="serilog:write-to:RollingFile.formatter" value="Serilog.Formatting.Json.JsonFormatter" /> <add key="serilog:using:Console" value="Serilog.Sinks.Console" /> <add key="serilog:write-to:Console" /> </appSettings>
This recreates our original code by outputting to both a rolling file and console output, bad sadly does not allow us to set the renderMessage parameter of the JsonFormatter.
Note: At the time of writing it appears there’s no way to set this renderMessage, see How to set formatProvider property in Serilog from app.config file.