opentelemetry-dotnet/docs/logs/correlation
Cijo Thomas 33f617299b
Add AspNetCore example for log correlation (#1267)
* Add AspNetCore example for log correlation

* remove space

* link to non host console
2020-09-15 09:47:02 -07:00
..
Program.cs Add doc on how to correlate ILogger with trace (#1214) 2020-09-01 07:15:39 -07:00
README.md Add AspNetCore example for log correlation (#1267) 2020-09-15 09:47:02 -07:00
correlation.csproj Add doc on how to correlate ILogger with trace (#1214) 2020-09-01 07:15:39 -07:00

README.md

Correlate Logs with Traces

Starting from Microsoft.Extensions.Logging version 5.0, logs can be correlated with distributed tracing by enriching each log entry with the information from the enclosing Activity. This can be achieved by enabling the ActivityTrackingOptions. In a non-host console app, it can be achieved as shown below.

using var loggerFactory = LoggerFactory.Create(builder =>
{
    builder.Configure(options => options.ActivityTrackingOptions =
        ActivityTrackingOptions.TraceId |
        ActivityTrackingOptions.SpanId);
});

Please refer to the example here.

In an ASP.NET Core app, the above can be achieved by modifying the host building, as shown below.

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(loggingBuilder =>
            loggingBuilder.Configure(options =>
                options.ActivityTrackingOptions =
                    ActivityTrackingOptions.TraceId
                    | ActivityTrackingOptions.SpanId))
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Microsoft.Extensions.Logging.ActivityTrackingOptions supports TraceId, SpanId, ParentId, TraceFlags and TraceState.

References