Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

Member-only story

Comprehensive Guide to Logging in ASP.NET Core with Serilog

Tomas Svojanovsky
Dev Genius
Published in
3 min readAug 27, 2024

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.

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by Tomas Svojanovsky

I'm a full-stack developer. Programming isn't just my job but also my hobby. I like developing seamless user experiences and working on server-side complexities

No responses yet

Write a response