Using Serilog with ILogger in CSharp

Serilog is a powerful logging library for .NET applications. It supports structured logging and integrates easily with ILogger from Microsoft.Extensions.Logging. Installation Install the necessary NuGet packages: dotnet add package Serilog.AspNetCore dotnet add package Serilog.Sinks.Console Basic Setup in Program.cs (.NET 8+) using Microsoft.Extensions.Hosting; using Serilog; Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); var builder = WebApplication.CreateBuilder(args); // Replace default logging with Serilog builder.Host.UseSerilog(); // --- Some code here app.Run(); Using ILogger in a Controller or Service using Microsoft.Extensions.Logging; public class MyService { private readonly ILogger<MyService> _logger; public MyService(ILogger<MyService> logger) { _logger = logger; } public void DoWork() { _logger.LogInformation("Doing work at {Time}", DateTime.UtcNow); try { // some code } catch (Exception ex) { _logger.LogError(ex, "An error occurred while doing work"); } } } Benefits Structured logging with properties Multiple sinks (e.g., console, file, Seq) Easy integration with ASP.NET Core Resources Serilog Documentation GitHub Repo

May 6, 2025 · 1 min · 142 words · Wei Wang

Customizing Log Output with Seilog's IDestructuring Policy

Serilog is a powerful logging library for .NET that allows deep customization of how objects are represented in structured logs. One such customization point is IDestructuringPolicy. What is IDestructuringPolicy? IDestructuringPolicy is an interface in Serilog that lets you control how specific objects are transformed into structured log data. This is especially useful when you want to: Omit sensitive fields (e.g., passwords, tokens) Rename properties Format output differently Use Case Example Say you have a User class: ...

August 6, 2024 · 2 min · 232 words · Wei Wang