ASP.NET Core has a completely new configuration subsystem that adds JSON, environment variables and other sources in addition to the classic XML format we’ve had since .NET 1.0. The appeal of Microsoft.Extensions.Configuration for me is that it’s easier to work with than the System.Configuration APIs.

Having the flexible JSON format is also a big plus, and it makes Serilog configuration on .NET Core quite a bit more natural than the XML <appSettings> support that shipped in Serilog 1.5.

Here’s the Serilog configuration for colored console logging:

Log.Logger = new LoggerConfiguration()
  .WriteTo.ColoredConsole()
  .CreateLogger();

With the new Serilog.Settings.Configuration package, ReadFrom.Configuration() lets us pull the same information from appsettings.json.

var configuration = new ConfigurationBuilder()
  .AddJsonFile("appsettings.json")
  .Build();

Log.Logger = new LoggerConfiguration()
  .ReadFrom.Configuration(configuration)
  .CreateLogger();

Log.Information("Hello, world!");

In the JSON file itself, the relevant section is called "Serilog":

{
  "Serilog": {
    "WriteTo": ["ColoredConsole"]
  }
}

Simple, hey? As long as the sink package, in this case Serilog.Sinks.ColoredConsole is installed, the right assemblies will be found. The names of sinks (and the arguments they might accept) are the same as the method names in the C# API, because behind the scenes the JSON configuration is translated into exactly the same method calls as you’d make directly in C#.

Let’s look at a more complete example:

{
  "Serilog": {
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "ColoredConsole" },
      { "Name": "Seq", "Args": { "serverUrl": "http://localhost:5341" } }
    ],
    "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"],
    "Properties": {
        "Application": "Sample",
        "Environment": "Test"
    }
  }
}

This one specifies a minimum level, and shows how "WriteTo" works to specify more complex sink configuration. Instead of just the name of the sink some arguments are included too. Seq is one of the network-based sinks for Serilog, and WriteTo.Seq() accepts a serverUrl argument in the C# API, so that’s passed under "Args" in the JSON version.

"Enrich" works the same way as "WriteTo": the options here are the same ones that you’ll see on the Enrich configuration API in C#, and arguments can be passed in the same way if they’re needed.

As a syntactic shortcut, Enrich.WithProperty("Application", "Sample") in C# is specified using the JSON "Properties" collection. (This has the side-effect of meshing nicely with environment variable configuration support, which we get “for free” by supporting the IConfiguration interface. More on that another day…)

What do you think? Let me know in the comments here, or join the Gitter chat we’ve just opened up for the Serilog project.