To be clear, ASP.NET Core has a logging right under the hood. The framework has acces to structured logging API’s. Serilog is easy to set up, you can overwrite all levels of logging and create custom sinks to log to any DB or file.
Install Serilog
Install the Serilog.AspNetCore
package in your solution or project, this package contains about everything needed to get started. You can use the Nuget Package Manager or use the following command in the terminal.
dotnet add package Serilog.AspNetCore
Create and configure Serilog in the Main()
method of the Program.cs
file. This is example contains the basics to activate Serilog in your ASP.NET Core
application to write logs tot the console.
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
We need to let all logging events pass through Serilog, and just Serilog. For now, logging is still done by 2 providers. We need to let the application know that we will use Serilog only. To do that we update the CreateHostBuilder
method, also located in the Program.cs
file. Add .UseSerilog
to the method as following:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}
Now all logging happens though Serilog. We just need to clean up appsettings.json
as Serilog does not use these settings by default.
// BEFORE
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
// AFTER
{
"AllowedHosts": "*"
}
Use Serilog in your application
Just inject the ILogger
where you need it, using Dependency Injection. ILogger is registered in the IServiceCollection
this this can be resolved by just injecting it in the construtor.
public class ActionCommandHandler
{
private readonly ILogger<ActionCommandHandler> _logger;
public ActionCommandHandler(ILogger<ActionCommandHandler> logger)
{
_logger = logger;
}
public async Task<int> HandleCommand()
{
int result = 1 + 1;
_logger.LogInformation("One plus one is {result}", result);
return result;
}
}
This is a quick walkthrough, showing you how to implement Serilog in a ASP.NET Core 3 application. In part 2 I will address how you can overwrite multiple levels of logging, and how to add custom Serilog Sinks.