【问题标题】:How to include additional properties when using structured logging with NLog?使用带有 NLog 的结构化日志记录时如何包含其他属性?
【发布时间】:2021-08-23 18:50:29
【问题描述】:

我知道你可以这样做:

_Logger.Info("This is my message: {MessageId}.  And here's an explanation: {expl}", messageId, expl)

这将根据它们在字符串中的顺序将 messageId 和 expl 的值插入到消息中,如 String.Format。

不幸的是,我想在结构化消息日志记录之外添加额外的属性,所以我使用了 LogEventInfo:

Dim ev as New LogEventInfo(LogLevel.Info, "", "This is my message: {MessageId}")
ev.Properties{"EventId"}=eventId
_Logger.Log(ev)

还有其他方式可以优雅地添加其他属性吗?

【问题讨论】:

  • 我不明白这个问题。您是否有兴趣构建 LogEvent 可用于格式化输出消息的复杂消息模板?或者您是否有兴趣向 LogEvent 添加许多属性?也许阅读github.com/NLog/NLog/wiki/How-to-use-structured-logging
  • 朱利安,很抱歉,当它出现时我没有注意到这条评论。我的问题是将添加几个属性的需求与结构化的日志消息简明扼要地结合起来。我自己想通了,做的事情与您在下面的答案略有不同,但我会在那里回复。
  • 现已更新您的问题以匹配已接受的答案。

标签: vb.net nlog


【解决方案1】:

我认为您正在寻找 WithProperty 来添加消息中没有的属性。

例子:

_Logger.WithProperty("EventId", eventId)
       .Info("This is my message: {MessageId}.  And here's an explanation: {expl}", messageId, expl)

另请参阅:https://github.com/NLog/NLog/wiki/Context#logevent-properties

【讨论】:

  • 这看起来和我需要的完全一样。对于遇到此答案的其他人,您可以链接 WithProperty 以添加其他属性:_Logger.WithProperty("EventId", eventId).WithProperty("AddtlInfo", moreInfo).Info("This is my message: {MessageId}. And here's an explanation: {expl}", messageId, expl) 实际上,我使用流利的方式解决了这个问题:_Logger.Info().Message("This is my message: {MessageId}. And here's an explanation: {expl}", messageId, expl).Property("EventId", eventId).Property("AddtlInfo", moreInfo).Write() 不过,我更喜欢您的方法。
猜你喜欢
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多