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");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With