【问题标题】:How can I add a named property that is not part of the message template?如何添加不属于消息模板的命名属性?
【发布时间】:2015-06-04 07:17:48
【问题描述】:

在某些情况下,我想将上下文信息添加到消息中(例如当前经过身份验证的用户),不必将其包含在消息模板中

我想完成这个:

logger.Information("Doing stuff {Foo} with the thing {Bar}. {User}", foo, bar, user)

但模板中没有{User}

我已经知道LogContext,但是在仅向一个事件中添加上下文信息时,这似乎有点过头了。

我也知道我可以使用低级 API logger.Write(LogEvent evnt) 来实际控制包含哪些属性,但这对于我想要完成的任务来说似乎有点太多了。

我很确定有一种简短而优雅的方式非常明显,但我还没有找到它:)

更新:

我后来才发现这个问题或多或少相似:Add custom properties to Serilog

【问题讨论】:

标签: serilog


【解决方案1】:

我可以自己解决!

您可以在一次调用.LogXXX() 方法之一时使用流畅的方法.ForContext(propertyName, propertyValue)

例如:

logger.ForContext("User", user)
      .Information("Doing stuff {Foo} with the thing {Bar}", foo, bar)

添加到事件的属性仅适用于事件,并且在下次调用logger.LogXXX() 方法时不再存在

更新

Nicholas Blumhardt 的文章很好地解释了这一点:Context and correlation – structured logging concepts in .NET (5)

【讨论】:

  • 我必须查看我的笔记,但是 IIRC,这个 Serilog 上下文会在 AsyncState 转换中丢失。
【解决方案2】:

如果您使用的是通用 Microsoft ILogger,则可以使用 BeginScope;

using (_logger.BeginScope(new Dictionary<string, object> { { "LogEventType", logEventType }, { "UserName",  userName } }))
{
    _logger.LogInformation(message, args);
}

这里讨论; https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/

【讨论】:

  • 不知道为什么没有更多的支持。我更喜欢使用 ILogger 接口而不是与 Serilog 紧密耦合(尽管 Serilog 很棒)。
  • 即使问题有#serilog 标签,这种方法可能更可取,因为正如@triple.vee 所提到的,它消除了将Serilog 依赖硬连接到日志代码中的需要。
  • 这样将属性添加到properties对象中,是否可以作为一个独立的属性?
猜你喜欢
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
  • 2022-11-14
相关资源
最近更新 更多