Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / Azure

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

4.67/5 (2 votes)
11 Feb 2019CPOL1 min read 16.3K  
How to set up Serilog in a .NET Core 2.2 Web app deployed to Azure

This article is an entry in our Microsoft Azure IoT Contest. Articles in this section are not required to be full articles so care should be taken when voting.

Introduction

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”)

JavaScript
{
  "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”)

JavaScript
{
  "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

JavaScript
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

JavaScript
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)