.net 如何使用NLog记录CorrelationManager.ActivityId

.net 如何使用NLog记录CorrelationManager.ActivityId,.net,logging,nlog,trace,.net,Logging,Nlog,Trace,如何将CorrelationManager.ActivityId作为单独的字段记录 以下是我当前的NLog.config: <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <variable

如何将
CorrelationManager.ActivityId
作为单独的字段记录

以下是我当前的NLog.config:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <variable name="logDirectory" value="${basedir}/Logs" />

  <extensions>
    <add assembly="NLog.Mongo"/>
  </extensions>

  <targets>
    <target xsi:type="Mongo"
            name="mongoCustom"
            includeDefaults="false"
            connectionString="mongodb://localhost/FooLogging"
            collectionName="authLogs">

      <field name="Date" layout="${longdate:universalTime=true}" />
      <field name="Level" layout="${level}"/>
      <field name="Message" layout="${message}" />
      <field name="Logger" layout="${logger}"/>
      <field name="Exception" layout="${exception:format=tostring}" />
      <field name="ThreadID" layout="${threadid}" />
      <field name="ThreadName" layout="${threadname}" />
      <field name="ProcessID" layout="${processid}" />
      <field name="ProcessName" layout="${processname:fullName=true}" />
      <field name="UserName" layout="${windows-identity}" />
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="mongoCustom" />
  </rules>
</nlog>

目前没有对
CorrelationManager.ActivityId的内置支持

但是,您可以创建自己的布局渲染,并将其输出:

[LayoutRenderer(“活动ID”)]
公共类活动IDLayoutRenderer:LayoutRenderer
{
受保护的覆盖无效附加(StringBuilder生成器,LogEventInfo logEvent)
{
Append(Trace.CorrelationManager.ActivityId.ToString());
}
}
您还需要将其注册到:

 ConfigurationItemFactory.Default.LayoutRenderers
      .RegisterDefinition("activityid", typeof(ActivityIdLayoutRenderer));
然后,您可以在目标定义中使用它:

<target xsi:type="Mongo">
      <!-- ... -->
      <field name="ActivityId" layout="${activityid}" />
</target>


作为替代解决方案,您还可以输出任何自定义属性,如ActivityId,但在这种情况下,您必须在每次登录时都包含它。

${ActivityId}已添加到NLog v4.1中。

thx!我还提出了一个问题:github.com/NLog/NLog/issues/332