.Net Core Logging with MongoDB and Serilog

Logging is essential in any software.  Logged messages can aid in troubleshooting sporadic errors that may only occur in production. Logging can also include identity tracking so we are able to keep an electronic trail of user activity.

I have also used logging to determine hot code paths and their associated runtime benchmarks. Nowadays, I just use Application Insights for that!

In the next section, I will be covering how to setup .Net Core logging with Serilog and its MongoDB Sink.

Logging in .Net Core

.Net Core offers a very modular logging mechanism that gives us the ability to register one or more providers that can “listen in” and act on messages of interest. One provider, Serilog, is well regarded as a high performance structured logging package.

MongoDB Community Edition

MongoDB is a document based, distributed database.  It supports a very flexible document model that allows developers to store objects as documents in the database. It does not require a schema upfront and does not confine data to the traditional table columns and rows found in a relational database model. MongoDB is supported on Linux, Windows, Mac OS and Solaris. The Community Edition of MongoDB is free and open source. A paid Enterprise Edition providing additional features is also available.

Connecting .Net Core, Serilog and MongoDB

To get started, we need to install the necessary packages via NUGET. These packages are applicable to any .Net Core application using GenericHost. (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.1)

Serilog package summary:

Nuget Package Description
Serilog.Extensions.Logging   Serilog Logging Provider
Serilog.Extensions.Hosting Route framework log messages through Serilog
Serilog.Settings.Configuration Read Serilog configuration from json configuration file
Serilog.Sinks.MongoDB Write message routed through Serilog to MongoDB

Register and configure Serilog in Program.cs.In the code below, I am registering a Service Worker setup to run as a Windows Service:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseWindowsService()
                .UseSerilog((context, config) =>
                {
                    config.ReadFrom.Configuration(context.Configuration);
                });

Configure Logging settings and levels for .Net Core, Serilog and MongoDB:

"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "MongoDB",
        "Args": {
          "databaseUrl": "mongodb://my-db:27017",
          "collectionName": "myCollection",
          "cappedMaxSizeMb": "1024",
          "cappedMaxDocuments": "50000"
        }
      }
    ]
  }

At this point, messages will be logged into the configured MongoDB database collection specified in the Json configuration file.