Member-only story
Comprehensive Guide to Logging in ASP.NET Core with Serilog

We will see logging into the console and then into a file.
Create Project
dotnet new webapi --use-controllers -o MediumLogging
Install packages
dotnet add package Serilog
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console
Program.cs
We start by registering the logger in Program.cs
. First, we create a Serilog logger instance where we define the minimum level of logging. In this example, the minimum level is set to Information
, meaning only logs with Information
level and higher will be logged.
Next, we clear the existing logging providers to ensure that no other loggers are active and then register Serilog as the primary logging provider.
var logger = new LoggerConfiguration()
.WriteTo.Console()
.MinimumLevel.Information()
.CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);
Controller
using Microsoft.AspNetCore.Mvc;
namespace MediumLogging.Controllers;
public class Todo
{
public Guid Id { get; set; }
public string Title { get; set; }
}
[ApiController]
[Route("[controller]")]
public class TodoController(ILogger logger) : ControllerBase
{
[HttpGet]
public IActionResult GetAll()
{
logger.LogInformation("Started fetching todos");
var todos = new List<Todo>
{
new()
{
Id = Guid.NewGuid(),
Title = "Walk a dog",
}
};
logger.LogInformation("Finished fetching todos");
return Ok(todos);
}
}
If we run the app and try to call this endpoint we should see logs in the console.

Logging to file
Now let's move to the second part, we will install a new package first. We installed Serilog.Sinks.Console for console logging, now we need Serilog.Sinks.File
dotnet add package…