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

问题描述 投票:0回答:2

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

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

我们稍后如何根据需要更改最低水平?

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

myLogger.ChangeMinimumLevelTo(newLevel)
c# .net logging f# microsoft.extensions.logging
2个回答
6
投票

对于需要此解决方案的其他人,但在 C# 中,这是@Franco Tiveron 的解决方案翻译:

void changeMinimumLevel(ILogger logger, LogLevel level)
        {
            var _logger = logger
                    .GetType()
                    .GetField("_logger", BindingFlags.NonPublic | BindingFlags.Instance)
                    .GetValue(logger);
            var loggersArray =
                (Array)_logger
                    .GetType()
                    .GetProperty("MessageLoggers")
                    .GetValue(_logger);


            var enu = loggersArray.GetEnumerator();
            var i = 0;
            while (enu.MoveNext())
            {
                var x = enu.Current;
                var piMinLevel = x.GetType().GetProperty("MinLevel");
                var fiMinLevel = piMinLevel.GetBackingField();
                fiMinLevel.SetValue(x, level);
                loggersArray.SetValue(x, i);
                i++;
            }
        }

5
投票

有点脏,但它有效(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)
    )
© www.soinside.com 2019 - 2024. All rights reserved.