【问题标题】:NLog logger name missing from the log file, do you see why?日志文件中缺少 NLog 记录器名称,您知道原因吗?
【发布时间】:2013-10-06 01:05:21
【问题描述】:

我正在使用 NLog 从 ASP.NET 应用程序进行日志记录。除了 ${logger} 之外,一切都很好。我的日志文件缺少记录器名称。这是 NLog 配置文件中的目标行:

<target name="DebugToFile" xsi:type="File" fileName="${basedir}/Debug.log" layout="${logger} | ${longdate} | ${message}" />

这是我在日志文件中得到的:

| 2013-10-05 17:55:20.9852 | In Decrypt
| 2013-10-05 17:55:20.9852 | In Deserialize

下面是创建记录器实例的 C# 行:

new Log("Iamalogger").Debug("In Decrypt");

知道为什么 ${logger} 没有被接收吗?

编辑:2014 年 1 月 14 日 这是我正在使用的日志包装器:

public class Log 
{
    private Logger _log;

    public Log(string class)
    {
        _log = LogManager.GetLogger(class);
    }

    //methods for logging...
}

【问题讨论】:

  • 你能告诉我们你的 Log 类的代码吗?
  • 正如@wageoghe 所说,您似乎正在使用客户日志类,这是正确的吗?如果是,请提供该类的源代码
  • 对不起,这被我的优先级降低了。刚刚使用我正在使用的日志包装器中的代码进行了更新。

标签: asp.net nlog


【解决方案1】:

我知道这是一个老问题,但我最近偶然发现了这个问题,所以我想说明我的实现有什么问题,以防其他人发现自己处于这种情况。

由于问题中的日志包装器没有显示 Debug 方法的实现,我假设它类似于我在包装器中所做的实现:

public class Log
{
    private Logger _log;

    public Log (string className)
    {
        _log = LogManager.GetLogger(className);
    }

    public void Debug(string message)
    {
        _log.Log(new LogEventInfo
        {
            TimeStamp = DateTime.UtcNow,
            Level = LogLevel.Debug,
            Message = message,
        });
    }
}

...当然,如果我们像这样使用这个类:

new Log("Iamalogger").Debug("In Decrypt");

日志缺少记录器名称:

 | 2018-05-13 15:58:06.1805 | In Decrypt


解决方案是将值设置为LogEventInfo 中的LoggerName 属性:

public void Debug(string message)
{
    _log.Log(new LogEventInfo
    {
        TimeStamp = DateTime.UtcNow,
        Level = LogLevel.Debug,
        Message = message,
        LoggerName = _log.Name
    });
}

或使用接受记录器名称的构造函数:

public void Debug(string message)
{
    _log.Log(new LogEventInfo(LogLevel.Debug, _log.Name, message)
    {
        TimeStamp = DateTime.UtcNow
    });
}

导致写入以下日志:

Iamalogger | 2018-05-13 16:18:16.1201 | In Decrypt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多