以编程方式更改 .NET 最低日志级别

Changing .NET Minimum Log Level programmatically

使用Microsoft.Extensions.Logging,设日志初始化(F#):

let myLogger = 
    LoggerFactory
        .Create(fun builder -> 
            builder
                .AddSimpleConsole()
                .SetMinimumLevel(myLevel) 
                |> ignore)
        .CreateLogger()

我们以后如何根据需要更改最低级别?

我正在寻找像这样简单的东西:

myLogger.ChangeMinimumLevelTo(newLevel)

有点脏,但可以用(Mono.Reflection 用于 GetBackingField)

let changeMinimumLevel (logger: ILogger) (level: LogLevel) = 
    let logger = logger :?> Microsoft.Extensions.Logging.Logger<obj>
    let _logger = 
        logger
            .GetType()
            .GetField("_logger", BindingFlags.NonPublic ||| BindingFlags.Instance)
            .GetValue(logger)
    let loggersArray = 
        _logger
            .GetType()
            .GetProperty("MessageLoggers")
            .GetValue(_logger) :?> Array

    let loggers = seq { 
        let enu = loggersArray.GetEnumerator()
        while enu.MoveNext() do enu.Current 
    }

    loggers |> Seq.iteri (fun i info ->            
        let piMinLevel = info.GetType().GetProperty("MinLevel")
        let fiMinLevel = piMinLevel.GetBackingField()
        fiMinLevel.SetValue(info, Nullable(level))
        loggersArray.SetValue(info, i)
    )