.net 以编程方式重新配置 NLog
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10302561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reconfiguring NLog programmatically
提问by snappymcsnap
This is my first time using the NLog package for logging but so far its been great to work with.
这是我第一次使用 NLog 包进行日志记录,但到目前为止它非常适合使用。
In my scenario I need to initialize my NLog LoggingConfiguration settings programmatically rather than thru the more typical config file scenario. I've tested this and got it all working the way I want it by default. But how would I go about modifying my settings programmatically at run-time? Probably the most common scenario here is one where the application's logging level is set to ERROR by default but a bug arises in a particular module that I want to switch the logging level to be much more verbose to track down the error. I'd like to write a little web interface so I can easily tweak these settings at runtime but I want to make sure I am taking the right approach with this.
在我的场景中,我需要以编程方式初始化我的 NLog LoggingConfiguration 设置,而不是通过更典型的配置文件场景。我已经对此进行了测试,并默认按照我想要的方式工作。但是我将如何在运行时以编程方式修改我的设置?可能这里最常见的情况是应用程序的日志记录级别默认设置为 ERROR 但在特定模块中出现错误,我想将日志记录级别切换为更详细的以跟踪错误。我想编写一个小的 Web 界面,以便我可以在运行时轻松调整这些设置,但我想确保我对此采取了正确的方法。
回答by Lee Hiles
I know I'm a year late but I just ran into similar scenario where I needed to provide dynamic control of the logger to users. Fortunately, this is relatively easy with nlog. Here I'm just enabling Trace level logging to an already created Logger but obviously you could do anything you wanted including adding new Targets/Rules or just completely replace the LoggerConfiguration with your programmatically generated one.
我知道我迟到了一年,但我遇到了类似的情况,我需要向用户提供记录器的动态控制。幸运的是,这对于 nlog 来说相对容易。在这里,我只是为已经创建的 Logger 启用跟踪级别日志记录,但显然您可以做任何您想做的事情,包括添加新的目标/规则,或者只是用您以编程方式生成的完全替换 LoggerConfiguration。
Basic ColoredConsole nlog.config:
基本 ColoredConsole nlog.config:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target xsi:type="ColoredConsole" name="c"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Error" writeTo="c" />
</rules>
</nlog>
Simple console application:
简单的控制台应用程序:
public class Program
{
//Initialize default Logger from config file
private static readonly Logger m_log = LogManager.GetCurrentClassLogger();
public static Logger Log
{
get { return m_log; }
}
public static void Main(string[] args)
{
Log.Trace("You won't see me because config is at LogLevel.Error");
EnabledTraceForAllRules();
Log.Trace("You will see me now though!");
//Pause console window
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
/* Prints:
2013-05-07 16:04:22.7050 TRACE You will see me now though!
Press any key to continue...
*/
}
public static void EnabledTraceForAllRules()
{
foreach(var rule in LogManager.Configuration.LoggingRules)
{
rule.EnableLoggingForLevel(LogLevel.Trace);
}
//Call to update existing Loggers created with GetLogger() or
//GetCurrentClassLogger()
LogManager.ReconfigExistingLoggers();
}
}
If you need to alter the Logging configuration from outside the process and it has to be done programmatically, I would suggest going with WCF. You could expose a small WCF service from either your application or website that provides methods for reconfiguring nlog.
如果您需要从进程外部更改日志记录配置并且必须以编程方式完成,我建议使用 WCF。您可以从您的应用程序或网站公开一个小型 WCF 服务,该服务提供重新配置 nlog 的方法。
回答by Micha? Zalewski
I found "Configuration API" in NLog documentation (https://github.com/NLog/NLog/wiki/Configure-from-code), may be this help you. Look at NLog.Config namespace in NLog assembly too.
我在 NLog 文档(https://github.com/NLog/NLog/wiki/Configure-from-code)中找到了“配置 API” ,可能对你有帮助。也看看 NLog 程序集中的 NLog.Config 命名空间。
See also: https://github.com/NLog/NLog/wiki/Reinitialize-NLog-configuration
另见:https: //github.com/NLog/NLog/wiki/Reinitialize-NLog-configuration
回答by Rolf Kristensen
NLog 4.6.7 introduces the ability to use Layout-logic in the LoggingRules. So you can have a NLog.config with logging-rules that are easily adjusted at runtime:
NLog 4.6.7 引入了在 LoggingRules 中使用布局逻辑的能力。所以你可以有一个 NLog.config 带有在运行时很容易调整的日志规则:
<nlog>
<variable name='myLevel' value='Warn'/>
<rules>
<logger minLevel='${var:myLevel}' writeTo="your-target-name" />
</rules>
</nlog>
Then one can update myLevelat runtime:
然后可以myLevel在运行时更新:
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
回答by 4myle
A programmatic initial setup example is given on the NLog tutorial page herewhich I've included below. (There's a slightly more extensive version here.)
一个纲领性初始设置的例子是NLOG教程页面上给出这里,我在下面列出。(有一个稍微更广泛的版本在这里。)
public static void Startup()
{
var config = new NLog.Config.LoggingConfiguration();
// Targets where to log to: File and Console
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
// Rules for mapping loggers to targets
config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
// Apply config
NLog.LogManager.Configuration = config;
LogManager.ReconfigExistingLoggers();
}
Then, to change the log level, where logconsoleis the target you want to change:
然后,要更改日志级别,logconsole您要更改的目标在哪里:
public static void SetConsoleLogLevel(LogLevel level)
{
foreach (var rule in LogManager.Configuration.LoggingRules)
{
foreach (var ruleTarget in rule.Targets)
{
if (ruleTarget != logconsole) continue;
DisableLoggingForLevels(rule, LogLevel.Trace, level);
rule.EnableLoggingForLevels(level, LogLevel.Fatal);
LogManager.GetCurrentClassLogger().Log(level, "Changed logger level to {0}", level);
}
}
LogManager.ReconfigExistingLoggers();
}
where DisableLoggingForLevelsis a private method exactly like NLog.Config.LoggingRule.EnableLoggingForLevelsexcept that it disables:
哪里DisableLoggingForLevels是一个完全一样的私有方法,NLog.Config.LoggingRule.EnableLoggingForLevels除了它禁用:
private static void DisableLoggingForLevels(LoggingRule rule, LogLevel minLevel, LogLevel maxLevel)
{
for (var ordinal = minLevel.Ordinal; ordinal <= maxLevel.Ordinal; ++ordinal)
rule.DisableLoggingForLevel(LogLevel.FromOrdinal(ordinal));
}
回答by Eternal21
I see answers enabling one level at a time, but if you want to mirror the behavior of NLog.config file, where setting a single level also enables all higher priority levels (and disables lower priority ones), you need to enable a range of levels using SetLoggingLevelslike this:
我看到了一次启用一个级别的答案,但是如果您想镜像 NLog.config 文件的行为,其中设置单个级别也启用所有更高优先级的级别(并禁用较低优先级的级别),您需要启用一系列使用SetLoggingLevels这样的级别:
NLog.config:
NLog.config:
<rules>
<logger name="*" minlevel="Trace" writeTo="your-target-name" />
</rules>
Code:
代码:
public static void SetLogLevel(LogLevel newLogLevel)
{
foreach (var rule in LogManager.Configuration.LoggingRules)
{
foreach (var target in rule.Targets)
{
if (target.Name == "your-target-name")
{
rule.SetLoggingLevels(newLogLevel, LogLevel.Fatal);
}
}
}
LogManager.ReconfigExistingLoggers();
}
From NLog documentation:
从 NLog 文档:
public void SetLoggingLevels(LogLevel minLevel, LogLevel maxLevel);Enables logging the levels between (included)
minLevelandmaxLevel. All the other levels will be disabled.
public void SetLoggingLevels(LogLevel minLevel, LogLevel maxLevel);启用记录 (included)
minLevel和 之间的级别maxLevel。所有其他级别将被禁用。

