All Articles

Logging for .NET Core with Serilog

Serilog

Serilog is a diagnostic logging library for .NET applications. It is easy to set up, has a clean API, and runs on all recent .NET platforms. While it’s useful even in the simplest applications, Serilog’s support for structured logging shines when instrumenting complex, distributed, and asynchronous applications and systems.

Serilog provides diagnostic logging to files, console, and more.

Steps to configure Serilog for a .NET Core solution

  1. Install the Serilog.AspNetCore NuGet package.

    With the command:

    dotnet add package Serilog.AspNetCore

    Or with the NuGet Package Manager window:

    serilog-nuget-listing

  2. Install the Serilog.Sinks.Console and Serilog.Sinks.File and NuGet packages.

    With the command:

    dotnet add package Serilog.Sinks.Console
    dotnet add package Serilog.Sinks.File

    Or with the NuGet Package Manager window:

    serilog-sinks-listing

  3. Go to Program.cs and add UseSerilog() in the CreateHostBuilder method as shown below.

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
       return Host.CreateDefaultBuilder(args)
           .UseLamar()
           .UseSerilog() // Add this line
           .ConfigureWebHostDefaults(webBuilder =>
           {
               webBuilder.UseStartup<Startup>();
           });
    }
  4. To add request logging for an ASP.NET Core application, Go to Startup.cs and add the below line in the Configure method.

    Ensure to add the line before UseStaticFiles() is called.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
       if (env.IsDevelopment())
       {
           app.UseDeveloperExceptionPage();
       }
       else
       {
           app.UseExceptionHandler("/Home/Error");
       }
    
       app.UseSerilogRequestLogging(); //Add this line
    
       app.UseStaticFiles();
    
       app.UseRouting();
    
       app.UseAuthorization();
    
       app.UseEndpoints(endpoints =>
       {
           endpoints.MapControllerRoute(
               name: "default",
               pattern: "{controller=Home}/{action=Index}/{id?}");
       });
    }
  5. Create the below section in appsettings.json.

    Ensure to remove the Logging section in the file, which is there by default.

    The below configuration logs everything to the Console.

    "Serilog": {
       "MinimumLevel": {
         "Default": "Information",
         "Override": {
           "Microsoft": "Warning",
           "System": "Warning"
         }
       },
       "WriteTo": [
         {
           "Name": "Console"
         }
       ]
     }

    The below configuration is for logging into a file:

    Ensure to create the App_Data and the Logs folders.

    "Serilog": {
       "MinimumLevel": {
         "Default": "Information",
         "Override": {
           "Microsoft": "Warning",
           "System": "Warning"
         }
       },
       "WriteTo": [
         {
           "Name": "File",
           "Args": {
             "path": "App_Data\\Logs\\log-.txt",
             "shared": true,
             "rollingInterval": "Day",
             "rollOnFileSizeLimit": true,
             "fileSizeLimitBytes": 5000000,
             "buffered": false,
             "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}) {Message}{NewLine}{Exception}"
           }
         }
       ]
     }
  6. Create an installer file for Serilog configuration. (or you can also add the below code in the ConfigureServices method in Startup.cs)

    For information on how to use Installer files, refer to my post on Lamar.

    using Lamar;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Serilog;
    
    namespace Project.Web.Installers
    {
       public class LoggerInstaller : IInstaller
       {
           public void InstallServices(ServiceRegistry services, IConfiguration configuration)
           {
               services.AddLogging();
               // Add serilog configuration - reads from "Serilog" section on appsettings.json
    
               LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
                   .ReadFrom.Configuration(configuration);
               Log.Logger = loggerConfiguration.CreateLogger();
           }
       }
    }
  7. Now, you can inject ILogger in any class where you want to use logging.

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using System.Diagnostics;
    
    namespace Project.Web.Controllers
    {
       public class HomeController : Controller
       {
           private readonly ILogger<HomeController> _logger;
    
           public HomeController(ILogger<HomeController> logger)
           {
               _logger = logger;
           }
    
           public IActionResult Index()
           {
               _logger.LogInformation("Homepage opened.");
               return View();
           }
       }
    }

Please drop a comment below if you have any queries.