框架:.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");
}
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一起注入类似单例的东西。