Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Serilog LogLevel at runtime for injected instance

Framework: .NET Core 2.1

I'm using Elasticsearch configuration for Serilog as described in the code below:

Startup.cs

Log.Logger = new LoggerConfiguration().Enrich.FromLogContext()
                             .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(Configuration.GetSection("ElasticSearchURL").Value))
                             {
                                 AutoRegisterTemplate = true,
                                 MinimumLogEventLevel = Serilog.Events.LogEventLevel.Error
                             }).CreateLogger();
    services.AddSingleton(Log.Logger);

Is it possible to change the log level at runtime for injected instances of Logger?

private readonly ILogger<EmailService> _logger;
public EmailService(ILogger<EmailService> logger)
{
     _logger = logger;
}

public async Task<Result> Send(Email email)
{
    // CHANGE LOG LEVEL TO LOGINFORMATION HERE
    _logger.LogInformation("MESSAGE");
}
like image 208
Felipe Santana Avatar asked Jan 26 '23 05:01

Felipe Santana


1 Answers

Instead of setting the minimum log level in the Elasticsearch options, would you be able to set it at the Logger level? If you're able to instead do something like

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Error()
    .Enrich.FromLogContext()
    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(Configuration.GetSection("ElasticSearchURL").Value))
    {
        AutoRegisterTemplate = true
    }).CreateLogger();

then you'd be able to use a LoggingLevelSwitch to control the minimum level, like this:

var levelSwitch = new LoggingLevelSwitch();
levelSwitch.MinimumLevel = Serilog.Events.LogLevelEvent.Error;

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.ControlledBy(levelSwitch)
    .Enrich.FromLogContext()
    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(Configuration.GetSection("ElasticSearchURL").Value))
    {
        AutoRegisterTemplate = true
    }).CreateLogger();

You'd need to have something like a singleton for your instance of the LoggingLevelSwitch to inject along with your ILogger.

like image 89
Blake Avatar answered Jan 29 '23 07:01

Blake