简体   繁体   English

NLog - 在运行时设置记录器级别?

[英]NLog - set the logger level in runtime?

I'm using the latest NLog v3.1 and have a question on how to set logging level at runtime.我正在使用最新的 NLog v3.1,并且对如何在运行时设置日志记录级别有疑问。 I have just one target and logger in my NLog.config file.我的 NLog.config 文件中只有一个目标和记录器。 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.我在一个模块中有以下代码来声明记录器以及 function GetLoggingLevel,我可以传入记录器名称以检索它的级别。 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.目前我必须打开 NLog.config XML 并修改 XML 中的最小级别。因为我有 autoReload = "true",它会生效 - 但希望有一种方法可以使用 NLog 方法/属性来设置它。

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.有了这个,我可以轻松地在我的项目中调用 Log.Info("some text") 或 Log.Error("some error") 等。 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.我可以获得当前级别并将其显示给用户,但我希望用户能够将日志记录级别更改为调试、信息、错误等,但我不知道如何在配置文件中设置最小级别在运行时无需直接加载和修改配置 XML。

You can access the LogManager.Configuration.LoggingRules and enable or disable logging for a certain level.您可以访问 LogManager.Configuration.LoggingRules 并启用或禁用某个级别的日志记录。 For instance, using a small project with a NLog config as :例如,使用一个带有 NLog 配置的小项目:

<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

C# C#

  using NLog;

  LogManager.GlobalThreshold = LogLevel.Debug;

You need to implement ILoggerProvider to return your own custom logger.您需要实现ILoggerProvider以返回您自己的自定义记录器。 The logger you create can implement ILogger .您创建的记录器可以实现ILogger You will need to duplicate your nlog configuration file and change the min and max level to allow all log levels.您将需要复制您的 nlog 配置文件并更改最小和最大级别以允许所有日志级别。 This will be overriden in a class that you will use only for these special requests that need different logging.这将在您将仅用于需要不同日志记录的这些特殊请求的类中被覆盖。

VB: VB:

Public NotInheritable Class CustomLevelNLogProvider
    Inherits ILoggerProvider

    Private ReadOnly factory As NLog.LogFactory

    ' pass a separate nlog config path that has logging enabled all the way to trace level, you will override it down below in the LogWrapper class
    Public Sub New(ByVal customNlogConfigPath As String)
        factory = NLog.Web.NLogBuilder.ConfigureNLog(customNlogConfigPath)
    End Sub

    Public Function CreateLogger(ByVal categoryName As String) As ILogger
        Dim logger = factory.GetLogger(categoryName)
        Return New CustomLevelLogger(logger)
    End Function
End Class

Public NotInheritable Class CustomLevelLogger
    Inherits ILogger

    Private ReadOnly innerLogger As ILogger
    Private ReadOnly minLevel As LogLevel
    Private ReadOnly maxLevel As LogLevel

    Public Sub New(ByVal innerLogger As ILogger)
        Me.innerLogger = innerLogger
    End Sub

    ' call this method on each request that needs a temporary log level
    Public Sub SetLogLevels(ByVal minLevel As LogLevel, ByVal maxLevel As LogLevel)
        Me.minLevel = minLevel
        Me.maxLevel = maxLevel
    End Sub

    ' implement the ILogger interface, making sure to use minLevel and maxLevel properly, forward calls on to innerLogger if level matches
}
End Class

C#: C#:

public sealed class CustomLevelNLogProvider : ILoggerProvider
{
    private readonly NLog.LogFactory factory;

    // pass a separate nlog config path that has logging enabled all the way to trace level, you will override it down below in the LogWrapper class
    public CustomLevelNLogProvider(string customNlogConfigPath)
    {
        factory = NLog.Web.NLogBuilder.ConfigureNLog(customNlogConfigPath);
    }

    ' call this method on each request that needs a temporary log level
    public ILogger CreateLogger(string categoryName)
    {
        var logger = factory.GetLogger(categoryName);
        return new CustomLevelLogger(logger);
    }
}

public sealed class CustomLevelLogger : ILogger
{
    private readonly ILogger innerLogger;
    private readonly LogLevel minLevel;
    private readonly LogLevel maxLevel;

    public CustomLevelLogger(ILogger innerLogger)
    {
        this.innerLogger = innerLogger;
    }

    // call this method on each request that needs a temporary log level
    public void SetLogLevels(LogLevel minLevel, LogLevel maxLevel)
    {
        this.minLevel = minLevel;
        this.maxLevel = maxLevel;
    }

    // implement the ILogger interface, making sure to use minLevel and maxLevel properly, forward calls on to innerLogger if level matches
}

NLog ver. NLog 版本4.6.7 enables you to do this: 4.6.7 使您能够做到这一点:

<nlog>
   <variable name="myLevel" value="Warn" />
    <rules>
      <logger minLevel="${var:myLevel}" />
    </rules>
</nlog>

Then you can execute this code, and it will dynamically update the logging rule:然后你可以执行这段代码,它会动态更新日志规则:

LogManager.Configuration.Variables["myLevel"] = "Debug";
LogManager.ReconfigExistingLoggers();

See also: https://github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules另见: https : //github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM