Serilog for ASP.NET Core 3.1 OR .NET 5

Prasad Patil
3 min readApr 12, 2020

--

Serilog
(https://github.com/serilog/serilog)
It is easy to set up, logging library, has a clean API, and runs on all recent .NET platforms. As per the documentation it supports structured logging and can provide diagnostic logging to files, consoles and many other outputs. Please check github url for more information

Create SerilogExample Project
If you need to know on howto create API project check the link below for more information
https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio

We will try to enable Serilog logging for our SerilogExample project, that will log information in the Logs folder. I have created API project for this example. When you run the project default endpoint is launched in the browser e.g. https://localhost:44324/weatherforecast

In your Visual Studio 2019 go to Project > Add Nuget Packages below packages

  1. Serilog.AspNetCore — Main package
  2. Serilog.Settings.Configuration — Microsoft.Extensions.Configuration (appsettings.json) support for Serilog
  3. Serilog.Sinks.Console — A Serilog sink that writes log events to the console/terminal.
  4. Serilog.Sinks.File — Write Serilog events to text files in plain or JSON format. Do not use “Serilog.Sinks.RollingFile”, rolling functionality in this sink has been improved and merged into the Serilog.Sinks.File
  5. Serilog.Sinks.Async — Asynchronous sink wrapper for Serilog

Finally we are ready to write configuration and code

Appsettings.json — Update the settings for the sinks. E.g. the Logs will be logged in the logs folder of your application. It will create the folder if needed.

{
"Serilog": {
"Using": [ "SeriLog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Async" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "File",
"Args": {
"path": "Logs/log.txt",
"rollingInterval": "Day"
}
}
]
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "SerilogExample"
}
},
"AllowedHosts": "*"
}

Program.cs

Let’s enable the logging for our application. Add Configuration property to the Program class

public static IConfiguration Configuration { get; } = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true).AddJsonFile($"appsettings.{Environment.MachineName}.json", optional: true).AddEnvironmentVariables().Build();

Then modify the Main method, to create logger using the settings read from Configuration defined in appsetting.json.

public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
try
{
Log.Information("Starting web host");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog() // Add this
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});

Controller

To use the logger in our WeatherForecastController we need the following

  1. using Microsoft.Extensions.Logging;
  2. Property for logger
    private readonly ILogger<WeatherForecastController> _logger;
  3. In the constructor pass the ILogger<WeatherForecastController> logger
  4. I have updated the Get method with try catch and log
public IEnumerable<WeatherForecast> Get()
{
try
{
var rng = new Random();
_logger.LogDebug("Debug message Called Get method WeatherForecastController");
_logger.LogInformation(
"Called Get method WeatherForecastController");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
}).ToArray();
}
catch(Exception ex)
{
_logger.LogError(ex.Message);
throw ex;
}
}

Finally, Run the project, since we have set the Logging Level to “Information” in appSettings.json, you should “ Starting web host” and “ Called Get method WeatherForecastController” message in the log file created in “Logs” folder.

To understand more about

  1. Serilog.Sinks.File — There are more options available for more info visit https://github.com/serilog/serilog-sinks-file
  2. Serilog.Settings.Configuration — There are more options available for more info visit https://github.com/serilog/serilog-Settings-configuration

You can also check the above code at
https://github.com/prasadpatil2015/serilogexample

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response