Skip to main content

.NET TraceId and SpanId injection into logs configuration

This page describes how to configure traceId and spanId data injection into user logs from ASP.NET and .Net core. The goal is to correlate the relevant logs with your corresponding traces and spans.

The injection allows you to click a link from the Trace View tab and launch a search tab that displays the logs with the linked traceid/spanid. These logs should be stored in the Continuous data tier as the links in Sumo Logic default to searching there instead of other data tiers. It's worth noting that to search actual traces and not the logs, those can be found in _index=_trace_spans.

.NET Core

  1. Get the current traceId and spanId, which can be obtained by:

    var traceId = Tracer.CurrentSpan.Context.TraceId;
    var spanId = Tracer.CurrentSpan.Context.SpanId;
  2. It is a matter of logging this information like this:

    _logger.LogInformation("Hello World! - trace_id=" + traceId + " - span_id=" + spanId);

    _logger is standard .net ILogger instance. The Sumo Logic demo system performs this using the Coffee Bar code example, which you can find here: CalculatorController.cs | SumoLogic GitHub.

  3. [Optional] If using Activity in the code, then there is one more option: you can configure the ActivityTrackingOptions for logging in Program.cs and it will automatically add traceId and spanId into logs.

private static IHostBuilder CreateHostBuilder(string[] args) =>
.ConfigureLogging(loggingBuilder =>
loggingBuilder.Configure(options =>
options.ActivityTrackingOptions =
| ActivityTrackingOptions.SpanId))
.ConfigureWebHostDefaults(webBuilder =>

ASP.NET Logs4net

  1. Get the current traceId and spanId, which can be obtained by:
log4net.ThreadContext.Properties["trace_id"] = Tracer.CurrentSpan.Context.TraceId;
log4net.ThreadContext.Properties["span_id"] = Tracer.CurrentSpan.Context.SpanId;
  1. Extend log pattern layout in log4net.config file, like in attached configuration with two additional properties %property{trace_id} and %property{span_id}
<appender name="textFileAppender" type="log4net.Appender.FileAppender">
<file value="log-log4net-textFile.log" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger trace_id=%property{trace_id} span_id=%property{span_id} - %message%newline" />

Additional Information

Sumo Logic YouTubeSumo Logic Twitter
Privacy Statement
Terms of Use

Copyright © 2022 by Sumo Logic, Inc.