I am using Serilog for logging in my .net 6 web API and would like to expose an endpoint to enable me to change the global logging level. This will enable me to switch the level via a front end toggle switch. This is what I have implemented so far but it does not seem to have any effect at all. Even just setting the logging level in the startup is not moving the default level off of "Information". I am using the .net DI to configure everything.
This is what I have so far:
Program.cs
var levelSwitcher = new LoggingLevelSwitch(LogEventLevel.Verbose);
builder.Services.AddSingleton<LoggingLevelSwitch>(levelSwitcher);
var seriLogger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitcher)
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();
Then in my endpoint controller
private readonly LoggingLevelSwitch _levelSwitch;
private readonly ILogger<DiagnosticsController> _logger;
public DiagnosticsController(ILogger<DiagnosticsController> logger, LoggingLevelSwitch levelSwitch)
{
_logger = logger;
_levelSwitch = levelSwitch;
}
[HttpGet(Name = "SwitchLoggingLevel")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult SwitchLoggingLevel(string level)
{
if (Enum.TryParse(level, out Serilog.Events.LogEventLevel newLoggingLevel))
{
_levelSwitch.MinimumLevel = newLoggingLevel;
return Ok();
}
return BadRequest();
}
From what I can see in the debugger is that the logger is still on "Information" minimum level and even when call the endpoint and passing in a more or less verbose level nothing is having an effect.
My initial thoughts are that the way I am initializing the switcher in the DI environment is incorrect, but I am not sure on how to do it correctly (ie creating a service and then immediately using it in the subsequent config of the logger), but even if that is incorrect, the actual minimum level is not even being set to "Error" as configured.
Check that you have configured Serilog correctly because the code works as expected.
Assign your variable seriLogger
to Log.Logger
or
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitcher)
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
builder.Host.UseSerilog();
Note that you need to add WriteTo.Console()
or any other sink.