【问题标题】:Serilog Level switcher via api endpoint通过 api 端点的 Serilog 级别切换器
【发布时间】:2023-01-15 05:53:30
【问题描述】:

我正在使用 Serilog 登录我的 .net 6 web api,并想公开一个端点以使我能够更改全局日志记录级别。这将使我能够通过前端拨动开关切换电平。这是我到目前为止所实施的,但它似乎根本没有任何效果。即使只是在启动时设置日志记录级别也不会改变“信息”的默认级别。我正在使用 .net DI 来配置所有内容,如有任何建议,我们将不胜感激。这是我到目前为止所拥有的:

程序.cs

var levelSwitcher = new LoggingLevelSwitch(LogEventLevel.Verbose);

builder.Services.AddSingleton<LoggingLevelSwitch>(levelSwitcher);

var seriLogger = new LoggerConfiguration()
            .MinimumLevel.ControlledBy(levelSwitcher)
            .ReadFrom.Configuration(builder.Configuration)
            .Enrich.FromLogContext()
            .CreateLogger();

然后在我的端点控制器中

    private readonly LoggingLevelSwitch _levelSwitch;
    private readonly ILogger<DiagnosticsController> _logger;

    public DiagnosticsController(ILogger<DiagnosticsController> logger, LoggingLevelSwitch levelSwitch)
    {
        _logger = logger;
        _levelSwitch = levelSwitch;
    }

    [HttpGet(Name = "SwitchLoggingLevel")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public IActionResult SwitchLoggingLevel(string level)
    {
        if (Enum.TryParse(level, out Serilog.Events.LogEventLevel newLoggingLevel))
        {
            _levelSwitch.MinimumLevel = newLoggingLevel;
            return Ok();
        }

        return BadRequest();
    }

从我在调试器中看到的情况来看,记录器仍处于“信息”最低级别,即使调用端点并传入或多或少的详细级别,也没有任何效果。

我最初的想法是我在 DI 环境中初始化切换器的方式不正确,但我不确定如何正确地进行(即创建服务然后立即在记录器的后续配置中使用它)。但即使那是不正确的,实际的最低级别甚至没有按照配置设置为“错误”。

任何建议将不胜感激。

【问题讨论】:

  • 您使用的是哪个 Serilog 版本?
  • Serilog.AspNetCore 6.1.0 Serilog.Sinks.Console 4.1.0
  • 更新:似乎我可以成功让 levelSwitch 连接到记录器的唯一方法是通过 json 配置文件来实现。问题是我无法获得对它的引用,因此我可以将它作为单例注入到 DI 上下文中

标签: c# api .net-6.0 serilog


【解决方案1】:

检查您是否已正确配置 Serilog,因为代码按预期工作

Log.Logger = new LoggerConfiguration()
   .MinimumLevel.ControlledBy(levelSwitcher)
   .ReadFrom.Configuration(builder.Configuration)
   .Enrich.FromLogContext()
   .CreateLogger();

builder.Host.UseSerilog();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多