Setting Up Serilog in a .NET Core 2.2 Web App Deployed to Azure

The standard .NET Core logging is all well and good, but it doesn’t give you logging to a file out of the box. My requirements were to display the application log messages in the Visual Studio Debug window and also log them to a physical file whilst in development on my local PC, but then when deployed to production, log the messages in a physical file on the Azure server but also allow them to be streamed using the Azure “Log stream” functionality when required. I also wanted to be able to change configuration options in the appsettings.*.json files so I didn’t have to touch the code once deployed.

Step 1: Install the following nuget packages.

  • Serilog.AspNetCore
  • Serilog.Settings.Configuration
  • Serilog.Sinks.Debug
  • Serilog.Sinks.File

Step 2: Make changes to the appsettings.Development.json file (configure to write to debug window and a file in “c:\temp”):

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Fatal",
        "System": "Fatal"
      }
    },
    "WriteTo": [
      {
        "Name": "Debug"
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:\\Temp\\log.txt",
          "fileSizeLimitBytes": "10000",
          "rollingInterval": "Day",
          "retainedFileCountLimit": "2",
          "rollOnFileSizeLimit": "true",
          "shared": "true",
          "flushToDiskInterval": "00:00:01"
        }
      }
    ]
  }
}


Step 3: Create a new or make changes to the existing appsettings.Production.json (configure to write to a file in “d:\home\LogFiles\http\RawLogs”):

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Error",
        "System": "Error"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "D:\\home\\LogFiles\\http\\RawLogs\\log.txt",
          "fileSizeLimitBytes": "1000000",
          "rollingInterval": "Day",
          "retainedFileCountLimit": "2",
          "rollOnFileSizeLimit": "true",
          "shared": "true",
          "flushToDiskInterval": "00:00:01"
        }
      }
    ]
  }
}

Step 4: Update the CreateWebHostBuilder method in Program.cs to use Serilog with our configuration:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseSerilog((context, config) =>
        {
            config.ReadFrom.Configuration(context.Configuration);
        })
        .UseStartup<Startup>();

Step 5: Setup some test messages in a Razor page to confirm it is working as intended

public class IndexModel : PageModel
{
    private readonly ILogger _logger;
    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }
    public void OnGet()
    {
        // Log level hierarchy: 
        // Trace, Debug, Information, Warning, Error, Critical
        _logger.LogTrace("IndexModel.OnGet entered (trace)");
        _logger.LogDebug("IndexModel.OnGet entered (debug)");
        _logger.LogInformation("IndexModel.OnGet entered (info)");
        _logger.LogWarning("IndexModel.OnGet entered (warn)");
        _logger.LogError("IndexModel.OnGet entered (error)");
        _logger.LogCritical("IndexModel.OnGet entered (crit)");
    }
}

The Azure detail for those that care

On Azure we need to have shared “true”, a short flush to disk interval (I chose every 1 second), and write to the “d:\home\LogFiles\http\RawLogs” folder for the “Log stream” to pick up the log entries. Then to see them you can turn on “Application Logging (Filesystem)” in the “Diagnostics logs” tab of the App in the Azure portal and view them in “Log stream”. The log files will also be stored on the Azure server if you want to download them.


Posted

in

, ,

by

Tags: