Skip to content

NLog/NLog.DiagnosticSource

Repository files navigation

NLog.DiagnosticSource

NLog.DiagnosticSource extends NLog with support for System.Diagnostics.Activity and DiagnosticSource.

Version AppVeyor

How to install

  1. Install the package

    Install-Package NLog.DiagnosticSource or in your csproj:

    <PackageReference Include="NLog.DiagnosticSource" Version="6.*" />
  2. Add to your nlog.config:

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

    Alternative register from code using fluent configuration API:

    LogManager.Setup().SetupExtensions(ext => {
       ext.RegisterTarget<NLog.Targets.DiagnosticListenerTarget>();
       ext.RegisterLayoutRenderer<NLog.LayoutRenderers.ActivityTraceLayoutRenderer>();
    });

How to use ActivityTraceLayoutRenderer

The System.Diagnostics.Activity.Current is the .NET abstraction used by OpenTelemetry for distributed tracing.

Example of NLog.config file that outputs TraceId information together with each LogEvent by using ${activity}:

<nlog>
<extensions>
    <add assembly="NLog.DiagnosticSource"/>
</extensions>
<targets>
    <target name="console" xsi:type="console" layout="${message}|ActivityId=${activity:property=TraceId}" />
</targets>
<rules>
    <logger minLevel="Info" writeTo="console" />
</rules>
</nlog>

Property Enum Values

  • Id : Hierarchical structure identifier that is concatenation of ParentIds
  • SpanId : Identifier for the current activity (Ex. database activity within current request)
  • ParentId : Identifier for the parent activity
  • TraceId : Identifier for the root activity (Request Trace Identifier)
  • OperationName : Operation name of the current activity
  • DisplayName : Explicitly assigned activity display name (with fallback to OperationName)
  • StartTimeUtc : Time when the operation started
  • Duration : Duration of the operation (formatted as TimeSpan)
  • DurationMs : Duration of the operation (formatted as TimeSpan.TotalMilliseconds)
  • Baggage : Collection of key/value pairs that are passed to children of this Activity (Use Format="@" for json-dictionary)
  • Tags : Collection of key/value pairs that are NOT passed to children of this Activity (Use Format="@" for json-dictionary)
  • CustomProperty : Custom property assigned to this activity. Must be used together with Item-option
  • Events : Events attached to this activity (Use Format="@" for json-array)
  • TraceState : W3C tracestate header
  • TraceFlags : See System.Diagnostics.ActivityTraceFlags for activity (defined by the W3C ID specification). For int-value combine with format="d"
  • SourceName : Name of the activity source associated with this activity
  • SourceVersion : Version of the activity source associated with this activity
  • ActivityKind : Relationship kind between the activity, its parents, and its children. For int-value combine with format="d"
  • TraceStateString : W3C 'tracestate' header as a string
  • Status : Status code of the current activity (Ok or Error). For int-value combine with format="d"
  • StatusDescription : Status description of the current activity
  • IsAllDataRequested : Activity span has been marked to be sampled / recorded (0 or 1)

Formatting

  • Format: Format for rendering the property.
  • Culture: CultureInfo for rendering the property (Default Invariant Culture)
  • Item: Lookup a single item from property-collection (Baggage, Tags, CustomProperty)
    • ${activity:property=Baggage:item=BaggageKey}
    • ${activity:property=Tags:item=TagKey}
    • ${activity:property=CustomProperty:item=PropertyKey}

Extract property values from parent or root

You can also specify to extract the property from either the parent or the root activity.

${activity:property=OperationName:parent=true}
${activity:property=OperationName:root=true}

How to use DiagnosticListenerTarget

DiagnosticListenerTarget publishes NLog events as DiagnosticSource events, allowing subscribers such as diagnostics tools, telemetry libraries, or custom listeners to observe log events without coupling directly to NLog.

Example of NLog.config file that uses the diagnosticListener target:

<nlog>
<extensions>
    <add assembly="NLog.DiagnosticSource"/>
</extensions>
<targets>
    <target name="diagSource" xsi:type="diagnosticListener" layout="${message}" sourceName="nlog" eventName="${logger}" />
</targets>
<rules>
    <logger minLevel="Info" writeTo="diagSource" />
</rules>
</nlog>

HostBuilder and ActivityTrackingOptions

The ${activity} layout renderer reads directly from Activity.Current. Microsoft.Extensions.Logging uses ActivityTrackingOptions to control which activity details are included as logging scope properties:

builder.ConfigureLogging((hostingContext, loggingBuilder) =>
{
      loggingBuilder.Configure(options =>
      {
            options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId
                                            | ActivityTrackingOptions.TraceId
                                            | ActivityTrackingOptions.ParentId;
      });
}).

SpanId / TraceId in custom NLog Target

NLog v5.3.4 introduced support for Layout.FromMethod that returns typed NLog Layout<T>. This allows custom NLog Targets to resolve SpanId / TraceId with support for AsyncWrapper, without having to parse from string or depend on NLog.DiagnosticSource nuget-package:

public class MyCustomTarget : TargetWithContext
{
        private static readonly string EmptyTraceIdToHexString = default(System.Diagnostics.ActivityTraceId).ToHexString();
        private static readonly string EmptySpanIdToHexString = default(System.Diagnostics.ActivitySpanId).ToHexString();

        public Layout<System.Diagnostics.ActivityTraceId?> TraceId { get; set; } = Layout<System.Diagnostics.ActivityTraceId?>.FromMethod(static evt => System.Diagnostics.Activity.Current?.TraceId is System.Diagnostics.ActivityTraceId activityTraceId && !ReferenceEquals(EmptyTraceIdToHexString, activityTraceId.ToHexString()) ? activityTraceId : null);

        public Layout<System.Diagnostics.ActivitySpanId?> SpanId { get; set; } = Layout<System.Diagnostics.ActivitySpanId?>.FromMethod(static evt => System.Diagnostics.Activity.Current?.SpanId is System.Diagnostics.ActivitySpanId activitySpanId && !ReferenceEquals(EmptySpanIdToHexString, activitySpanId.ToHexString()) ? activitySpanId : null);

        protected override void Write(LogEventInfo logEvent)
        {
            var spanId = RenderLogEvent(SpanId, logEvent);
            if (spanId.HasValue)
                data.SpanId = spanId.Value;

            var traceId = RenderLogEvent(TraceId, logEvent);
            if (traceId.HasValue)
                data.TraceId = traceId.Value;
        }
}

W3C is the recommended format for distributed tracing and is the default on modern .NET versions. .NET Framework continues to default to hierarchical IDs unless configured otherwise.

  • System.Diagnostics.Activity.DefaultIdFormat = System.Diagnostics.ActivityIdFormat.W3C;
  • or by setting the environment variable DOTNET_SYSTEM_DIAGNOSTICS_ACTIVITY_DEFAULTIDFORMAT to W3C

About

NLog integration with Microsoft Activity TraceId and SpanId

Topics

Resources

License

Stars

16 stars

Watchers

2 watching

Forks

Contributors

Languages