Display Serilog log in the program's GUI using appsettings.json configuration

Viewed 156

Referencing Is it possible to display Serilog log in the program's GUI? I have this solution working well for me, however I cannot make it work using an appsettings.json configuration. I've variations along the lines of

  {
    "Name": "Sink",
    "Args": {
      "logEventSink": "$sink"
  }
  

with and without the $. The class for this is in my application and the application is in the using statement. I would be grateful for guidance on this.

1 Answers

First of all, you should create a configuration extension method that creates and configures sink. Because Serilog configuration reader looks for extension methods that accept LoggerSinkConfiguration as a first argument:

public static class InMemorySinkConfigurationExtensions
{
    public static LoggerConfiguration InMemory(
              this LoggerSinkConfiguration loggerConfiguration)
    {
        return loggerConfiguration.Sink(new InMemorySink());
    }
}

Next step - add assembly that has this method declared to the Using section of Serilog configuration:

{
  "Serilog": {
    "Using": [ "NameOfYourAssembly" ],
    // etc
}

And finally, you can add your sink configuration:

{
  "Serilog": {
    "Using": [ "NameOfYourAssembly" ],
    "MinimumLevel": {
      "Default": "Debug"
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "InMemory", // should match name of extension method
        "Args": {
           // put here arguments for confuguration extension method
        }
      }
    ]
  }
}

Also, keep in mind that mentioned implementation of InMemorySink will not work with the configuration file because you don't have reference to the instance of this sink. A dirty way to fix this would be making the Events queue static. Otherwise use sink arguments to specify communication settings.

Related