0
votes

I have a logging use case where I want to log a specific API call at a different level than all of the other API services using Serilog, Log.Logger. My current logger configuration for the application is something like:

Log.Logger = new LoggerConfiguration()
                .MinimumLevel.ControlledBy(_loggingLevelSwitch)
                .WriteTo.MSSqlServer(connectionString, "LogTable")
                .CreateLogger();

So, when I call SetLoggingLevelSwitch to update the log level, it updates the level for the entire application, which is expected. What I'm wondering is, in an individual API call, can I override the log level just for the scope of that API call and not affect the log level in the rest of the application?

Thanks!

1

1 Answers

0
votes

I think you can use any Container for registration of common logger and then create ILogger from it

services.AddScoped<LoggerConfiguration>((_) => {
new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console();
});

Create logger with

public YourApiController(LoggerConfiguration loggerOrdinaryConfig)
{
    _strangeApiLogger = loggerOrdinaryConfig.
        MinimumLevel.Verbose()
        .CreateLogger();
}

But it could lead to difficulties with testing.

That's why you'd better look at LogContext (with filtering by property) or even FileConfiguration

upd: Always try to use interfaces because of easier unit testing reasons