【问题标题】:Using NLog LogLevel value from AppSettings configuration file使用 AppSettings 配置文件中的 NLog LogLevel 值
【发布时间】:2019-08-28 06:25:29
【问题描述】:

我需要从另一个应用程序配置 NLog 设置,本质上我有一个主应用程序和一个配置应用程序,并且需要从配置应用程序设置一些日志设置。

我在下面尝试过,但 minlevelenum 并且无效.. :(

<logger name="*" minlevel="${appsetting:MinimumLogLevel}" writeTo="File" />

这将是完美的工作,有什么建议吗?

谢谢

【问题讨论】:

    标签: nlog


    【解决方案1】:

    ** 更新答案**

    NLog 版本。 4.6 添加了对在 minLevel 中使用 NLog-Config-Variables 的支持。见https://github.com/NLog/NLog/pull/2709

    NLog 版本。 4.6.7 添加了对运行时调整 minLevel 的支持,方法是修改 NLog-Config-Variables 并调用 ReconfigExistingLoggers()。见https://github.com/NLog/NLog/pull/3184

    ** 原始答案**

    minlevel 属性确实不是Layout,所以你不能使用像`${appsetting} 这样的布局渲染器。

    您可以通过编程方式完成:

    var configuration = LogManager.Configuration;
    
    //TODO find correct rule
    var rule = configuration.LoggingRules[0];
    
    //disable all
    rule.DisableLoggingForLevel(LogLevel.Trace);
    rule.DisableLoggingForLevel(LogLevel.Debug);
    rule.DisableLoggingForLevel(LogLevel.Trace);
    rule.DisableLoggingForLevel(LogLevel.Info);
    rule.DisableLoggingForLevel(LogLevel.Warn);
    rule.DisableLoggingForLevel(LogLevel.Error);
    rule.DisableLoggingForLevel(LogLevel.Fatal);
    
    
    var minLevelRaw = System.Configuration.ConfigurationManager.AppSettings["minLevel"];
    var minLevel = LogLevel.FromString(minLevelRaw);
    
    //enable correct one
    rule.EnableLoggingForLevels(minLevel, LogLevel.Fatal); //enable from minLevel to fatal
    
    LogManager.Configuration = configuration;
    

    或者如果它适用于所有规则,您可以使用GlobalThreshold:

    var minLevelRaw = System.Configuration.ConfigurationManager.AppSettings["minLevel"];
    var minLevel = LogLevel.FromString(minLevelRaw);
    
    LogManager.GlobalThreshold = minLevel;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多