Logo

dev-resources.site

for different kinds of informations.

Serilog Integration in .NET

Published at
8/5/2024
Categories
dotnet
csharp
serillog
Author
Gaurav
Categories
3 categories in total
dotnet
open
csharp
open
serillog
open
Serilog Integration in .NET

Serilog is a newer logging framework for . NET. It was built with structured logging in mind. It makes it easy to record custom object properties and even output your logs to JSON.

How to install Serilog via Nuget and get started

Starting with Serilog is as easy as installing a Serilog Nuget package. You will also want to pick some logging sinks to direct where your log messages should go, including the console and a text file.

Install-Package Serilog
dotnet add package Serillog.ASPNetCore

If you want to store the logs in file

Install-Package Serilog.Sinks.File
dotnet add package Serillog.Sinks.File

Create a Service Class for Configuring the Serillog

public static class AppExtension
{
    public static void SerilLogConfiruation( this IHostBuilder host )
    {
        host.UseSerillog((context, loggerConfig)=> {
            loggerConfig.WriteTo.Console();

                        //store logs in json format
            loggerConfig.WriteTo.File(new JsonFormatter(),"logs/applogs.txt");

                        //store logs in text format
            //loggerConfig.WriteTo.File("logs/applogs.txt");

        }),
    }
}

Add Serillog in Program.cs

builder.Host.SerillogConfiguration();

[ApiController]
[Route("[controller]")]
public class DemoController : ControllerBase 
{
    private readonly ILogger<DemoController> _ilogger;

    public DemoController(ILogger<DemoController> logger)   
    {
        _ilogger = logger;
    }

    [Https]
    public IEnumerable<string> Get() 
    {
        _logger.LogInformation("Demo Controller Get is Called");
        return null;
    }
}

Featured ones: