Search code examples
c#jsonlogging.net-coreserilog

Reload Serilog JSON Configuration on changes in .NET Core 2.1


I'm currently working on a ASP.NET Core 2.1 application and I use Serilog for logging. I want to reload the application settings file for my Serilog implementation during runtime.

My goal is to change the log level at runtime e.g. I write into minimumLevel Debug instead of Information and I save the file. I want to trigger a live reload of the settings. My appsettings.json looks like this:

{
  "serilog": {
    "using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
    "minimumLevel": "Information",
    "writeTo": [
      {
        "name": "File",
        "args": {
          "fileSizeLimitBytes": 256000000,
          "retainedFileCountLimit": 62,
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": true,
      },
      {
        "name": "Console",
      }
    ]
  }
}

In my Program.cs I load the settings with the flag reloadOnChange: true.

public class Program
{
    public static readonly ServiceSettings Settings = new ServiceSettings();
        public static void Main(string[] args)
    {
        //...
    }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(Path.GetFullPath(CoreServiceBase.Instance.ConfigFilePath), optional: false, reloadOnChange: true)
            .AddCommandLine(args)
            .Build();

        config.Bind(Settings);

        return WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseSerilog((hostingContext, loggerConfiguration) =>
                    loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration))
            .UseConfiguration(config);
    }
}

My Startup looks like this:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // ...
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // Custom application logging
        ApplicationLogging.LoggerFactory = loggerFactory;

        // ...
    }
}

Do you know how to reload the Serilog configuration during runtime, if I somehow the appsettings.json gets changed. => Live reload for the appsettings.json.

Thank you!!


Solution

  • You can change the loglevel using LoggingLevelSwitch. You can read about it here

    You can use the IOptionsSnapshot<> interface to reload the configuration. You can read more about that here