2013-09-28 57 views
-1

我是一名嘗試將日誌記錄添加到其應用程序的沒有經驗的VB.NET程序員。我使用的是Nlog,它運行良好,但我需要我的用戶能夠選擇他們希望看到的日誌級別(Debug,Info,Warn),並在運行時通過配置頁面將日誌記錄切換到文件。使用運行時修改記錄

Nlog與app.config中的靜態配置很好地協作,但在運行時以編程方式更改規則是我掙扎的地方。我已經閱讀了API文檔,並且有許多方法來「添加」目標或規則,但是我可以看到一種簡單的方法來「刪除」目標或修改規則。

我也看過像SLF一樣的門面,試圖讓我的生活變得更簡單,但我也沒有看到一種簡單的方法來添加新的日誌記錄目標或在運行時更改日誌級別。

任何意見,代碼片段(我很好用VB或C#)將不勝感激。

回答

0

您可以訪問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() 

我希望這有助於。