Updated Step by step: Serilog with ASP.NET Core

by Carlos Mendible on 14 Jan 2019 » dotNetCore

Many of you come to my site to read the post Step by step: Serilog with ASP.NET Core which I wrote in 2016 and is completely out of date, so with this post I will show you how to setup Serilog to work with your ASP.NET Core 2.2 applications.

1. Create an ASP.NET Core project


    md aspnet.serilog.sample
    cd aspnet.serilog.sample
    dotnet new mvc

2. Add the following dependencies to your project


    dotnet add package Microsoft.AspNetCore.App
    dotnet add package Microsoft.AspNetCore.Razor.Design
    dotnet add package Serilog.AspNetCore
    dotnet add package Serilog.Extensions.Logging
    dotnet add package Serilog.Sinks.ColoredConsole

3. Change your Program.cs file to look like the following


public class Program
{
    public static void Main(string[] args)
    {
        // Create the logger
        Log.Logger = new LoggerConfiguration()
            .Enrich.FromLogContext()
            .MinimumLevel.Debug()
            .WriteTo.ColoredConsole(
                LogEventLevel.Verbose,
                "{NewLine}{Timestamp:HH:mm:ss} [{Level}] ({CorrelationToken}) {Message}{NewLine}{Exception}")
                .CreateLogger();

        try
        {
            CreateWebHostBuilder(args).Build().Run();
        }
        finally
        {
            // Close and flush the log.
            Log.CloseAndFlush();
        }
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseSerilog() // Set serilog as the loggin provider.
            .UseStartup<Startup>();
}

4. Inject the logger to your services or controllers


Change the home controller and log some actions:

    public class HomeController : Controller
    {
        // Logger instance
        ILogger<HomeController> logger;

        // Logger is injected into the controller
        public HomeController(ILogger<HomeController> logger)
        {
            this.logger = logger;
        }

        public IActionResult Index()
        {
            // Log something
            this.logger.LogDebug("Index was called");
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }

Download the complete code here

Hope it helps!