Integrating Serilog with Asp.Net Core

The Asp.Net team has introduced WebHost.CreateDefaultBuilder method to simplify the verbose codes needed to start your web application (which includes configuration and logging in the Startup.cs). With the new changes, the Serilog team is currently evaluating on an elegant approach to initialize Serilog after environment and configuration have been built.

Take note that the steps listed below is a temporary solution (without changing much to existing default codes) which I will update it when the time comes. Alternatively, you can follow the Program.cs example in the github.

Below demonstrates how to integrate Serilog with Asp.Net Core 2.0 onward with rolling file features:

  • Install the following packages from Nuget:
    • Serilog.AspNetCore
    • Serilog.Settings.Configuration
    • Serilog.Sinks.Console
    • Serilog.Sinks.RollingFile
  • Edit Program.cs file.
    using Serilog;
    public class Program {
     public static void Main(string[] args) { 
      var configuration = new ConfigurationBuilder()
       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
       .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
      Log.Logger = new LoggerConfiguration()
     public static IWebHost BuildWebHost(string[] args) => 
  • Set your own Serilog configuration in appsettings.json and remove “Logging” section.
     "Serilog": {
      "MinimumLevel": {
       "Default": "Information",
       "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      "WriteTo": [
        "Name": "Console",
        "Args": {"outputTemplate": "[{Timestamp:HH:mm:ss.fff}] {Level:u3} - {Message}{NewLine}{Exception}"}
        "Name": "RollingFile",
        "Args": {
         "pathFormat": "logs\\log-{Date}.log",
         "outputTemplate": "[{Timestamp:dd/MM/yy HH:mm:ss.fff z}] {Level:u3} {Message}{NewLine}{Exception}"

Leave a Reply

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