框架:.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");
}
答案 0 :(得分:1)
您可以在Logger级别上设置它,而不是在Elasticsearch选项中设置最低日志级别?如果您能够执行类似的操作
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Error()
.Enrich.FromLogContext()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(Configuration.GetSection("ElasticSearchURL").Value))
{
AutoRegisterTemplate = true
}).CreateLogger();
然后,您将可以使用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一起注入,您需要具有类似单例的东西。