Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在插件中使用NLog_C#_.net_Logging_Nlog - Fatal编程技术网

C# 如何在插件中使用NLog

C# 如何在插件中使用NLog,c#,.net,logging,nlog,C#,.net,Logging,Nlog,我想在插件中使用NLog,并使用配置API对其进行配置。然而,由于LogManager是静态的,我如何在不干扰其他插件的情况下做到这一点呢 我看到的使用配置API的示例包括完全替换LogManager.configuration。我可以尝试修改现有的任何配置,但我不确定这是否是线程安全的。您是否尝试过类似的方法: // This could got into a static constructor somewhere in the plugin to make sure it happens

我想在插件中使用NLog,并使用配置API对其进行配置。然而,由于LogManager是静态的,我如何在不干扰其他插件的情况下做到这一点呢


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

您是否尝试过类似的方法:

// 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并行运行

// 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.");

是否要从插件配置日志记录?我认为这将取决于主应用程序。@Inuyasha在本例中,我希望每个插件分别配置其日志记录。您还可以想象一个您无法控制的主应用程序,它不提供日志记录服务,但您不想干扰其他使用NLog的插件。