gpt4 book ai didi

asp.net - 如何在运行时更改注入(inject)实例的 Serilog LogLevel

转载 作者:行者123 更新时间:2023-12-02 22:18:39 25 4
gpt4 key购买 nike

框架:.NET Core 2.1

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

启动.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);

是否可以在运行时更改注入(inject)的 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");
}

最佳答案

除了在 Elasticsearch 选项中设置最小日志级别,您可以在 Logger 级别设置它吗?如果你能够做类似的事情

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 一起注入(inject)类似单例的东西。

关于asp.net - 如何在运行时更改注入(inject)实例的 Serilog LogLevel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56466317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com