首页 > 解决方案 > 特定记录器名称的 Nlog 规则不起作用

问题描述

我是 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 文件

我做错了什么?

标签: c#nlog

解决方案


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

也许你可以这样做:

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);
}

推荐阅读