简体   繁体   English

如何在插件中使用 NLog

[英]How to use NLog in a plugin

I would like to use NLog in a plugin and use the configuration API to configure it.我想在插件中使用 NLog 并使用配置 API 来配置它。 However, since the LogManager is static, how can I do this without interfering with other plugins that are doing the same thing?但是,由于 LogManager 是 static,我怎样才能在不干扰其他做同样事情的插件的情况下做到这一点?

The samples I see of using the configuration API involve replacing LogManager.Configuration entirely.我看到的使用配置 API 的示例涉及完全替换 LogManager.Configuration。 I could try modifying whatever existing configuration there is, but I'm not sure if that would be thread-safe.我可以尝试修改现有的任何配置,但我不确定这是否是线程安全的。

Have you tried something like this:你有没有尝试过这样的事情:

// 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 actually has a non-static mode, that is nice for plugins and running unit-tests in parallel. NLog 实际上有一个非静态模式,这对于插件和并行运行单元测试非常有用。

The LogManager is an interface around a global LogFactory. LogManager 是一个围绕全局 LogFactory 的接口。 But you can create your own local LogFactory for setting up your local configuration.但是您可以创建自己的本地 LogFactory 来设置本地配置。 It will run side-by-side with the global 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 https://github.com/NLog/NLog/wiki/Configure-component-logging

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

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