Closed dev-vinicius-andrade closed 1 year ago
Your IDinamicallyLogSwitcherService.Switch()
method is incorrect. It should take a LogEventLevel
instead of a LoggingLevelSwitch
and the implementation should read like this:
public void Switch(string switchName, LogEventLevel level)
{
if (_switches.TryGetValue(switchName, out var levelSwitch))
levelSwitch.MinimumLevel = level;
}
Then, in your LogLevelController
, all calls must be updated like this:
[HttpPost("{switchName}/{logLevel}")]
public IActionResult Post(string switchName, LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Trace:
_dinamicallyLogSwitcherService.Switch(switchName, LogEventLevel.Verbose);
return Ok($"Switched {switchName} to {logLevel}");
case LogLevel.Debug:
_dinamicallyLogSwitcherService.Switch(switchName, LogEventLevel.Debug);
return Ok($"Switched {switchName} to {logLevel}");
case LogLevel.Information:
_dinamicallyLogSwitcherService.Switch(switchName, LogEventLevel.Information);
return Ok($"Switched {switchName} to {logLevel}");
case LogLevel.Warning:
_dinamicallyLogSwitcherService.Switch(switchName, LogEventLevel.Warning);
return Ok($"Switched {switchName} to {logLevel}");
case LogLevel.Error:
_dinamicallyLogSwitcherService.Switch(switchName, LogEventLevel.Error);
return Ok($"Switched {switchName} to {logLevel}");
case LogLevel.Critical:
_dinamicallyLogSwitcherService.Switch(switchName, LogEventLevel.Fatal);
return Ok($"Switched {switchName} to {logLevel}");
case LogLevel.None:
_dinamicallyLogSwitcherService.Switch(switchName, LogEventLevel.Fatal);
return Ok($"Switched {switchName} to {logLevel}");
default:
return BadRequest($"Log level {logLevel} is not valid");
}
}
You may want to have a look at my WebSample branch where I have fully functional sample project very similar to yours but with a few improvements. For example, the log level switches (and log filter switches) are exposed as IReadOnlyDictionary
instead of IDictionary
in the ILogSwitchesAccessor
interface, making it impossible to use incorrectly. Also, passing a non existing switch name produces an error. And finally, you can test logs directly in swagger with the logs/test
route.
Closing since the question has been answered.
Hello,
Currently I'm trying to control the level switch from the app dynamically. Here is my serilog section from appsettings.json
Together with it I've made the changes in my program startup to use the level switch.
And Also created an interface to provide the contract to switch the log level.
And A Service that implements this interface.
Then I've created a controller responsible to change the log level
The controller shows me the log level changed, but It not reflects the changes. Am I missing something?