【问题标题】:Show log object in console from ILogger<Class> log critical在 ILogger<Class> 日志关键的控制台中显示日志对象
【发布时间】:2020-07-24 07:44:01
【问题描述】:

我使用ILogger 接口将有关我的应用程序的信息记录到控制台中。

我正在记录对我的应用程序的未经授权的访问:

private readonly RequestDelegate _next;
private readonly ILogger<SomeClass> _logger;

public SomeClass(RequestDelegate next, ILogger<SomeClass> logger)
{
      _next = next;
      _logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

// some methods there

_logger.LogCritical(
      $"{DateTime.UtcNow} - Unauthorized Access",
      new 
      { 
          token = jwt, 
          // other stuff
      });

但在控制台中,我只收到消息;

crit: namespace.to.my.app.SomeClass[0]
      24.07.2020 07:36:37 - Unauthorized Access

如何在控制台中显示我创建的匿名对象?

【问题讨论】:

    标签: c# asp.net-core logging


    【解决方案1】:

    ILogger 是一个语义记录器,因此您需要在日志字符串中使用一个标记来表示您正在记录的内容。试试这个:

    _logger.LogCritical
    (
      "{Time} - Unauthorized Access. Details {Details}",
      DateTime.UtcNow,
      new 
      { 
        token = jwt, 
        // other stuff
    });
    

    请注意,字符串插值不适用于语义日志记录,因此我将 DateTime.UtcNow 表达式移出并在日志字符串中为其指定了一个标记。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多