Search code examples
c#.netloggingdependency-injectionserilog

Setting Serilog log file location at run time in C#


I am writing a small console application , and using Serilog for logging. I have a logging service registered as shown

logFilelocation = "C:/Applications"
services.AddSingleton<IMyLogger>(x => new MyLogger(new LoggerConfiguration().WriteTo.File(logFileLocation, rollingInterval:RollingInterval.Month).CreateLogger()));

where logFileLocation is a default value;

When the program starts, it does:

  IMyLogger _logger = host.Services.GetRequiredService<IMyLogger>();

But I want to update the logFileLocation when user gives input at run time. How can I set this logFileLocation at run time in this case???


Solution

  • Thanks to the comment by @ThomasArdal; I could do a Hot-reload by modifying

    services.AddSingleton<IMyLogger>(x => new MyLogger(new LoggerConfiguration()
                    .WriteTo.Map(
                     _ => GetLogFileLocation(),
                        (url, wt) => wt.File($@"{url}\Log.txt", rollingInterval: RollingInterval.Month),
            sinkMapCountLimit: 1)
        .CreateLogger()));
    

    Where GetLogFileLocation() returns a property that represents the path.