【问题标题】:How to use NLog in a plugin如何在插件中使用 NLog
【发布时间】:2011-04-28 15:34:02
【问题描述】:

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

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

【问题讨论】:

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

标签: c# .net logging nlog


【解决方案1】:

你有没有尝试过这样的事情:

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

【讨论】:

    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多