Skip to content

Logging using Serilog

Install Serilog

Serilog provides structured logging with sinks to write logs into various formats such as console, DataDog, DynaTrace, ElasticSearch, email etc.

In Rider, go to Tools > NuGet > Manage NuGet Packages for Dotnet. alt text

Search for Serilog and install Serilog.AspNetCore 8.0.3. alt text

Alternatively, in Terminal, use
cd Library
dotnet add package Serilog.AspNetCore --version 8.0.3

If you're using a dark theme in Rider, logs might be written in black and impossible to read. Go to Settings > Editor > Color Scheme > Console Colors > Bright White and change Foreground to something like #FFFFF. alt text

Configure Serilog

csharp
var builder = WebApplication.CreateBuilder(args);

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateLogger();

builder.Host.UseSerilog();

Log.Information("Starting Library {env}", builder.Environment.EnvironmentName);

builder.Services.AddControllers();
//...


Run the project. Open Run at bottom left or using Cmd + 4alt text

Write logs using ILogger

Back in BookController, inject ILogger and write some logs using logger.LogInformation().

csharp
[ApiController]
[Route("[controller]")]
public class BookController(ILogger<BookController> logger) : Controller
{
    [HttpGet]
    public IActionResult Index()
    {
        logger.LogInformation("BookController.Index - Request");
    
        var book = new { Id = 1, Title = "Dotnet" };

        logger.LogInformation("BookController.Index - Response {@response}", book);
        return Ok(book);
    }
}



Run the project, call the API and view what is logged. alt text

If you don't want the Microsoft logs, add .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)

csharp
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning) // add this
    .WriteTo.Console()
    .CreateLogger();


alt text

Released under the MIT License.