Click here to Skip to main content
13,863,412 members
Click here to Skip to main content
Add your own
alternative version

Stats

1.2K views
Posted 11 Feb 2019
Licenced CPOL

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

, 11 Feb 2019
Rate this:
Please Sign up or sign in to vote.
How to set up Serilog in a .NET Core 2.2 Web app deployed to Azure

Editorial Note

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

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

License

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

Share

About the Author

frez
CEO Frez Systems Limited
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190214.1 | Last Updated 11 Feb 2019
Article Copyright 2019 by frez
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid