如何在运行时更改注入实例的Serilog LogLevel

问题描述 投票:1回答:1

框架:.NET Core 2.1

我正在使用Serilog的Elasticsearch配置,如下面的代码所述:

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);

是否有可能在运行时更改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");
}
asp.net elasticsearch asp.net-core serilog
1个回答
1
投票
您可以在Logger级别上设置它,而不是在Elasticsearch选项中设置最低日志级别?如果您可以执行类似的操作

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

then您将能够使用LoggingLevelSwitch来控制最低级别,如下所示:

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();
您需要使LoggingLevelSwitch实例与ILogger一起注入类似单例的东西。
© www.soinside.com 2019 - 2024. All rights reserved.