Search code examples
c#.net-coreserilog

Using Serilog for Logging with Azure Table Storage in .NET Core MVC


Despite hours spent on google, I am not getting there. We have a Core 3.1 MVC Web App project, and I've been asked to use SeriLog to write logs to Azure Table Storage. For the life of me, I can't find a working example or tutorial online. Here's what I've done so far:

  1. Added the following NuGet's:
  • Serilog
  • Serilog.Extensions.Logging
  • Serilog.Sinks.AzureTableStorage
  1. In appsettings.json,I replaced this:
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.Hosting.Lifetime": "Warning"
    }

With this:

  "Serilog": {
    "WriteTo": [
      {
        "Name": "AzureTableStorage",
        "Args": {
          "storageTableName": "Logs",
          "connectionString": "DefaultEndpointsProtocol=https;AccountName=***;AccountKey=***;EndpointSuffix=core.windows.net"
        }
      }
    ]
  },

And now I am stuck. This is currently in Program.cs in CreateHostBuilder :

.ConfigureLogging(logging =>
{
    logging.AddConsole();
})

I assume I should replace this? But, with what? I am not sure where to go from here. The serilog-sinks-azuretablestorage page on Github isn't much help. And I've been unable to find anything via Google that explains how to finish the implementation.


Solution

  • Well, I didn't get any bites on this. But after reading about 5 different articles, I managed to figure it out. In Program.cs, this was there by default:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
            {
                logging.AddConsole();
            })
    

    And I replaced it with this:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, logging) =>
            {
                var logger = new LoggerConfiguration()
                     .ReadFrom.Configuration(hostingContext.Configuration)
                     .CreateLogger();
    
                logging.AddSerilog(logger);
            })
    

    hostingContext is an instance of HostBuilderContext and it contains '.Configuration' which is an instance of IConfiguration. So hostingContext.Configuration contains all your settings in appsetting.json.

    In addition to the NuGet packages I mentioned in the OP, I also had to add this one:

    Serilog.Settings.Configuration

    (It's amazing how sometimes it can take 7 or 8 hours to write 4 lines of code.)