DEV Community 👩‍💻👨‍💻

Carlos Mendible
Carlos Mendible

Posted on • Originally published at carlos.mendible.com on

Updated Step by step: Serilog with ASP.NET Core

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>();
}
Enter fullscreen mode Exit fullscreen mode

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 });
        }
    }
Enter fullscreen mode Exit fullscreen mode

Download the complete code here

Hope it helps!

Top comments (0)

🌚 Life is too short to browse without dark mode