如何使用 ServiceStack.Logging ILog 记录消息关联 ID?

How to log a message correlation Id with ServiceStack.Logging ILog?

我对我目前使用的当前日志记录解决方案非常满意,它是由 NLOG 实现的 ServiceStack 接口。我使用的 NLOG 目标如下:

xsi:type="Console"

xsi:type="Debugger"

xsi:type="File"

xsi:type="Seq"

特别重要的是 Seq which is a log receiver on steroids and my lifeline to whats happening real-time with my services. The ability to query the structured logs is absolutely fantastic, so much so that now I'd like to query the Seq logs looking for all the messages with the same correlation Id, which, according to this post 可以使用浓缩剂:

using (LogContext.PushProperty("MessageId", GetCurrentMessageId()))
{
  Log.Information("Processing {OrderId}", message.Order.Id); 

  // Later
  Log.Information("Order processing complete");
} 

<target name="seq" xsi:type="Seq" serverUrl="http://localhost:5341">
  <property name="CallSite" value="${callsite}" />
  <property name="Logger" value="${logger}" />
  <property name="MachineName" value="${machinename}" />
  <property name="ThreadId" value="${threadid}" as="number" />

  <!-- would like to add the correlationId to the nlog properties here -->

</target>

使用 ServiceStack 接口,我看不到这样做的方法,而是必须通过使每个日志语句在消息中包含 correlationId 来伪复制它。即 _log.Warn("CorrelationId:{0} Campaign => no trackingId found".Fmt(request.CorrelationId));

有没有办法让 correlationId 成为第一个 class citizen/property 以便 Seq 让我通过它查询?

根据@paaschpas 的回答更新

鉴于如果您在记录器接口上使用 xxxxFormat 方法(非常重要),您现在可以使用它并在序号位置(有点脆弱)提供参数,例如

if (_log.IsDebugEnabled)
    _log.DebugFormat("CorrelationId:{0} CallReceived request:{1}", msgId, request.Dump());

最终会给你这个 ,我的朋友足以满足我的需要。

有没有办法让 correlationId 成为第一个 class citizen/property 以便 Seq 让我通过它查询?

根据 this 它指出 "you can't used named properties in your NLog messages for querying in Seq, the @0 and @1 placeholders can be used in queries to identify the parameters to {0} and {1} in format strings." 因此,如果您使用 _log.Warn("CorrelationId:{0} Campaign => no trackingId found".Fmt(request.CorrelationId)); 或 ServiceStack 的 log.WarnFormat("correlationid {0}", "correlationid"); 的伪副本,您可以 query/filter 使用 @0 == "correlationid"

使用 ServiceStack 接口,我看不到这样做的方法...

因为 ServiceStack 只是调用 NLog.LogManager.GetLogger(typeName) 而 NLog 似乎没有提供任何接口到 LogContext.PushProperty 我认为唯一的选择是通过参数查询 {0}, {1}, { 2}...等等

ServiceStack 现在支持 NLog (MDLC) + Log4net + Serilog 的 PushProperty:

using (log.PushProperty("Hello", "World"))
{
    log.InfoFormat("Message");
}

https://docs.servicestack.net/logging#logging-with-context

此功能从 ServiceStack v5.1.0 开始可用

NLog 4.5 还引入了 structured logging that works together with the new NLog.Targets.Seq