【问题标题】:Logging with runtime modifications记录运行时修改
【发布时间】:2013-10-04 12:59:12
【问题描述】:

我是一个缺乏经验的 VB.NET 程序员,我试图将日志记录添加到他的应用程序中。我正在使用 Nlog,它运行良好,但我需要我的用户能够选择他们希望查看的日志级别(调试、信息、警告),并在运行时通过配置页面将日志记录切换到文件。

Nlog 与 app.config 中的静态配置配合得很好,但在运行时以编程方式更改规则是我苦苦挣扎的地方。我已阅读 API 文档,并且有一些方法可以“添加”目标或规则,但我可以看到“删除”目标或修改规则的简单方法。

我还研究了像 SLF 这样的 Facade,试图让我的生活变得更简单,但我也没有看到一种简单的方法来添加新的日志记录目标或在运行时更改日志级别。

任何建议,代码 sn-ps(我擅长 VB 或 C#)将不胜感激。

【问题讨论】:

    标签: vb.net logging nlog


    【解决方案1】:

    您可以访问 LogManager.Configuration.LoggingRules 并启用或禁用特定级别的日志记录。例如,使用带有 NLog 配置的小项目:

    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <targets>    
        <target name="console" xsi:type="Console" layout="${message}"/>
      </targets>
      <rules>
        <logger name="*" minlevel="Debug" writeTo="console" />
      </rules>
    </nlog>  
    

    还有一个像

    这样的控制台应用程序
    Sub Main()
    
        Dim log As Logger = LogManager.GetCurrentClassLogger
    
        REM Both lines will be logged as defined in the NLog.config 
        log.Debug("debug message")
        log.Info("info message")
    
        For Each rule As LoggingRule In LogManager.Configuration.LoggingRules
            rule.DisableLoggingForLevel(LogLevel.Debug)
            REM rule.EnableLoggingForLevel(LogLevel.Debug)
        Next
    
        LogManager.ReconfigExistingLoggers()
    
        REM This line will not be logged as we just disabled it
        log.Debug("debug message")
        REM This line will still be logged
        log.Info("info message")
    
        Console.ReadLine()
    
    End Sub
    

    将禁用所有级别调试及以下的日志记录。这条线非常关键:

    LogManager.ReconfigExistingLoggers()   
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多