How to dynamically change Serilog's minimum log level for a tenant in a Multi-Tenant Asp.Net Core application

1.1k Views Asked by At

In our asp.net 6 application, we are writing file logs for each tenant (customer) in a separate folder using Serilog File sink. We get TenantId from Request URL and Enrich the property in Serilog to generate the folder path with tenantId.

In appsettings.json, minimum level is Error but would like to switch Serilog to Debug level for a given tenant in production temporarily.

Keeping performance in mind, How do we make that switch for a given tenant/request assuming that the required minimum level can be read from Context like HttpContext or similar.

Currently the minimal log level can be set only application-wide and there is no way to override it for particular execution pipeline (web request or queue message handler).

1

There are 1 best solutions below

2
On

You could try to switch the loglevel with LoggingLevelSwitch

Log.Logger = new LoggerConfiguration().MinimumLevel.ControlledBy(switcher).WriteTo.File("").CreateLogger();

A similar case here: https://social.msdn.microsoft.com/Forums/en-US/8344afa6-109b-43c5-8ba7-2e01fa52c4ce/using-serilog-logginglevelswitch?forum=aspdotnetcore

Update:

I would share all codes I tried :

Log.Logger = new LoggerConfiguration().MinimumLevel.ControlledBy(LoggingLevelSwitcher.Switcher).WriteTo.File(@"path").CreateLogger();
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();

public class LoggingLevelSwitcher
    {
        public static readonly LoggingLevelSwitch Switcher
       = new LoggingLevelSwitch(LogEventLevel.Information);



   }

In controller:

public IActionResult Privacy()
        {
            LoggingLevelSwitcher.Switcher.MinimumLevel = LogEventLevel.Warning;
           
            return View();
        }

You would find that after you visit the Privacy Page,the logger won't log info