【问题标题】:Nlog rule for particular loggername do not work特定记录器名称的 Nlog 规则不起作用
【发布时间】:2018-11-29 23:45:59
【问题描述】:

我是 Nlog 的新手,所以我的问题可能很简单。但是我无法让它工作。 问题: 我的应用程序为几个客户做了一些事情。我想为每个客户提供单独的日志文件。所有配置都必须以编程方式完成。 目前我有:

private static Logger InitialiseLog(Target target, string customerName)
{
    var loggerName = customerName == null? "globalLog" : customerName;
    var config = LogManager.Configuration ?? new LoggingConfiguration();
    config.AddTarget("eventlog", target);
    var rule = new LoggingRule("*", LogLevel.Debug, target);
    config.LoggingRules.Add(rule);
    LogManager.Configuration = config;
    Logger _logger;
    _logger = LogManager.GetLogger(loggerName);

    return _logger;
}

调用者:

var target =
    new FileTarget
    {
        FileName = customerName + ".log",
        Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}${exception}"
    };

    return InitialiseLog(target, customerName);

它可以工作,但为每个客户日志文件写入相同的内容。 我想将单个信息写入特定文件,所以我将规则更改为:

var rule = new LoggingRule(loggerName, ...

但它没有用,什么都没有写。 我的目的是实现这样的目标: LogManager.GetLogger("Customer1"); -> 它只写入 Customer1.log 文件 LogManager.GetLogger("globalLog"); -> 它只写入 globalLog.log 文件

我做错了什么?

【问题讨论】:

  • 可能是customerName有一个空字符串?

标签: c# nlog


【解决方案1】:

我猜您希望同一个应用程序实例处理多个客户日志文件。

也许你可以这样做:

private static Logger InitialiseLog(Target target, string customerName)
{
    var loggerName = string.IsNullOrEmpty(customerName) ? "globalLog" : customerName;

    var config = LogManager.Configuration ?? new LoggingConfiguration();
    if (config.FindTargetByName("eventlog")==null)
    {
        config.AddTarget("eventlog", target);
        var rule = new LoggingRule("*", LogLevel.Debug, target);
        config.LoggingRules.Add(rule);
        LogManager.Configuration = config;
    }

    return LogManager.GetLogger(loggerName);
}

我不知道您如何配置(或分配)NLog Target,但由于您隐藏了该信息,所以我猜 NLog Target 仅取决于 ${logger}-name,您可以使用相同的 NLog Target所有记录器。

为每个记录器注册新目标的替代解决方案:

private static Logger InitialiseLog(Target target, string customerName)
{
    var loggerName = string.IsNullOrEmpty(customerName) ? "globalLog" : customerName;
    var targetAlias = "eventlog_" + loggerName;

    var config = LogManager.Configuration ?? new LoggingConfiguration();
    if (config.FindTargetByName(targetAlias)==null)
    {
        config.AddTarget(targetAlias, target);
        config.AddRule(LogLevel.Debug, LogLevel.Fatal, target, loggerName, true):
        if (LogManager.Configuration != null)
           LogManager.ReconfigExistingLoggers();
        else
           LogManager.Configuration = config;
    }

    return LogManager.GetLogger(loggerName);
}

【讨论】:

  • 这行不通。这个方法被调用了几次。所以如果我添加一个条件:config.FindTargetByName("eventlog")==null) 这只会在第一次运行时执行。
  • 如果你解释了为什么某些东西不起作用,事情就会容易得多。为什么同一目标不能被多个记录器使用?
猜你喜欢
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
相关资源
最近更新 更多