Select Page

ASP.NET Core Logging with Serilog

by | May 17, 2020 | Programming | 0 comments

ASP.NET Core has built-in logging API that supports a wide variety of logging providers. ASP.NET Core logging needs to be configured before using it in your application. It even supports non-built-in third party log providers. Logging with serilog provides structured logging which makes it easier to be read by programs.

Logging providers works by storing logs in some destination like file or database except console which can only display log entries. In-built logging API is available in Microsoft.Extensions.Logging namespace and works mostly all in-built and third-party logging providers.

Why logging?

Logging should be part of every application. There will always need to troubleshoot application issues for which logs will be required for analysis.

When something breaks in production then the first thing we do is try and get information about what went wrong and our primary source of information is logs during that point of time. So it becomes very important to at least log all error events by default and if needed there should be an option to selectively enable additional logs for debugging purposes.

Serilog

There are many third-party providers and one of these is Serilog. Serilog is a popular third party logging provider that is supported in ASP.NET Core Logging. It is very easy to set up and provides API for logging. Serilog provides a structured logging framework and supports a wide variety of sinks to log to console, files, azure, etc.

ASP.NET Core Logging

Serilog support structured logging that allows message string along with objects to be logged and these are logged in structured format which allows it easier to be queried.

Serilog uses Sinks to log to different destinations like database, console, file and many more without changing any code. We just need to configure a new sink in config file.

Default logging in ASP.NET Core

When you create ASP.NET Core web or API application in program.cs it will add an entry to CreateDefaultBuilder function which will be invoked on application start and this will register default logger along with other stuff. The logging level for this default logging will be configured in the appsettings.json file.

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

To use this default logger we can simply add a logger object to the constructor of the controller and start logging using this object.

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

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

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

On running application we will get following default Console Logs

ASP.NET Core Default Logs

Implement ASP.NET Core Logging with Serilog

Install appropriate NuGet Packages for Serilog & Sinks.

  • Serilog.Extensions.Logging
  • Serilog.Extensions.Hosting
  • Serilog.Sinks.RollingFile
  • Serilog.Sinks.Console

Serilog console & RollingFile Sinks are implemented by adding configuration to appsettings.json file. Log level can be specified by setting the log level in MinimumLevel.

  "Serilog": {
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "{Timestamp:HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
        }
      },
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "Serilogs\AppLogs-{Date}.log",
          "outputTemplate": "{Timestamp:HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "fileSizeLimitBytes": 10485760
        }
      }
    ]
  }

Following fields can be used in custom output Template

  • Exception
  • Level
  • Message
  • NewLine
  • Properties
  • Timestamp

Log Level values, their methods in Serilog & descriptions

Log LevelMethodDescription
VerboseVerbosetracing information and debugging; generally only switched on in unusual situations
DebugDebuginternal control flow and diagnostic state dumps to facilitate pinpointing of recognised problems
InformationInformationevents of interest or that have relevance to outside observers; the default enabled minimum logging level
WarningWarningindicators of possible issues or service/functionality degradation
ErrorErrorindicating a failure within the application or connected system
FatalFatalcritical errors causing complete failure of the application

Add UseSerilog() to CreateDefaultBuilder in Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

Load Serilog configuration from appsettings.json file in startup.cs

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();
        }
         //Remaining code was removed
}

Newsletter Subscription

Stay updated! Instantly get notified about my new articles in your mailbox by subscribing via email

On running Application we should see logs in Console and also in the file as per the path and name specified. Serilog sample logs to Console & RollingFile

Serilog Console Sink Sample
Serilog File Sink Sample

To log in controller we can use Log object from Serilog namespace.

public class HomeController : Controller
{
    public HomeController()
    {
    }

    public IActionResult Index()
    {
       try
        {
            return View();
        }
        catch(Exception ex)
        {
            Serilog.Log.Error(ex, ex.Message);
            //Redirect to Error Page instead of throw
            throw ex;
        }
    }

    public IActionResult Privacy()
    {
        Serilog.Log.Debug("Home Controller - Privacy Action - Entered");
        return View();
    }
}

Summary

Logging should be part of every application. ASP.NET Core logging needs to be configured before using it in your application. ASP.NET Core logging has inbuilt log providers and also many third-party log providers are supported.

Serilog is third party structured log provider that is supported in .NET Core logging. Serilog provides basic diagnostic logging that supports a wide variety of sinks.

References: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1 & https://serilog.net/

You can also check my other Article on ASP.NET Core Caching: https://procodeguide.com/programming/aspnet-core-caching/

Hope you found this article useful
Buy me a coffeeBuy me a coffee

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Credit card sized computer, Home Automation and much more with Raspberry Pi 4

Improve performance of your laptop by replacing hdd with ssd