Vb.net – NLog – set the logger level in runtime

loggingnlogvb.net

I'm using the latest NLog v3.1 and have a question on how to set logging level at runtime. I have just one target and logger in my NLog.config file. The logger name = "*" and the minlevel = "Info". I have the following code in a module to declare the logger along with a function GetLoggingLevel which I can pass in the logger name to retrieve it's level. However, how may I set the logging level? Currently I'm having to open the NLog.config XML and modify the minlevel in the XML. Since I have autoReload = "true", it takes affect – but was hoping there was a way to set this using an NLog method/property.

Imports System.Xml
Imports NLog

Module modLogging

Private m_Log As Logger

Public ReadOnly Property Log As Logger
    Get
        If (m_Log Is Nothing) Then
            m_Log = LogManager.GetCurrentClassLogger
        End If
        Return m_Log
    End Get
End Property

Public Sub LogShutdown()
    LogManager.Shutdown()
End Sub

Public Function GetLoggingLevel(ByVal loggerName) As String
    Dim level As String = String.Empty

    If (LogManager.GetLogger(loggerName).IsInfoEnabled) Then
        level = "Info"
    ElseIf (LogManager.GetLogger(loggerName).IsErrorEnabled) Then
        level = "Error"
    ElseIf (LogManager.GetLogger(loggerName).IsDebugEnabled) Then
        level = "Debug"
    End If

    Return (level)
End Function

With this I can easily call Log.Info("some text") or Log.Error("some error"), etc. in my project. I can obtain the current level and show this to the user, but I want the user to be able to change the logging level to either Debug, Info, Error, etc. but I cannot figure out how to set the minlevel in the config file at runtime without loading & modifying the config XML directly. Any help would be appreciated.

Kindest Regards

Best Answer

You can access the LogManager.Configuration.LoggingRules and enable or disable logging for a certain level. For instance, using a small project with a NLog config as :

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

and a console app like

Sub Main()

    Dim log As Logger = LogManager.GetCurrentClassLogger

    log.Debug("debug message")
    log.Info("info message")

    For Each rule As LoggingRule In LogManager.Configuration.LoggingRules
        rule.DisableLoggingForLevel(LogLevel.Debug)
    Next

    LogManager.ReconfigExistingLoggers()

    log.Debug("debug message") REM This line will not be logged
    log.Info("info message")

    Console.ReadLine()

End Sub
Related Topic