如何在插件中使用NLog

本文关键字:NLog 插件 | 更新日期: 2023-09-27 17:53:49

我想在插件中使用NLog并使用配置API来配置它。但是,由于LogManager是静态的,我如何在不干扰其他正在做同样事情的插件的情况下做到这一点?

我看到的使用配置API的示例涉及替换LogManager。完全配置。我可以尝试修改任何现有的配置,但我不确定这是否会是线程安全的。

如何在插件中使用NLog

你试过这样做吗?

// This could got into a static constructor somewhere in the plugin to make sure it happens early
LoggingConfiguration config = LogManager.Configuration;
ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
config.AddTarget("myplugin", consoleTarget);
LoggingRule rule = new LoggingRule("myplugin", LogLevel.Debug, consoleTarget);
config.LoggingRules.Add(rule);
// Whenever my plugin creates a logger it'll obtain it like this
var log = LogManager.GetLogger("myplugin");
log.Error("Some message.");

NLog实际上有一个非静态模式,这对于并行运行插件和单元测试是很好的。

LogManager是一个围绕全局LogFactory的接口。但是您可以创建自己的本地LogFactory来设置本地配置。它将与全局LogFactory并行运行。

// This could got into a static constructor somewhere in the plugin to make sure it happens early
LogFactory logFactory = new LogFactory();
LoggingConfiguration config = new LoggingConfiguration();
ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
config.AddTarget("mypluginconsole", consoleTarget);
config.AddRuleForAllLevels(consoleTarget, "myplugin")
logFactory.Configuration = config;
// Whenever my plugin creates a logger it'll obtain it like this
var log = logFactory.GetLogger("myplugin");
log.Error("Some message.");
https://github.com/NLog/NLog/wiki/Configure-component-logging