C# Tracing with Serilog and SerilogTracing

Distributed tracing makes Seq even better for monitoring and troubleshooting the behavior and performance of complex distributed systems. The emerging standard for logging and tracing is OpenTelemetry, which Seq supports via the OpenTelemetry Protocol (OTLP).

If you are using Serilog another option you can consider is SerilogTracing. SerilogTracing is a new project that adds distributed, hierarchical tracing to applications that use Serilog. Traces can be created programmatically or generated by .NET components including HttpClient and ASP.NET Core. Traces can be sent to Seq or to any OTLP compatible server.

SerilogTracing Seq output
Seq trace viewer showing a hierarchical, distributed trace

Why SerilogTracing?

You might send logs to Seq with Serilog:

Using Serilog to send logs to Seq

Traces are useful and are easily added to Serilog's model (a span is just a log event with a start timestamp and zero or more child spans). The easiest and cleanest way to add traces with Serilog is to use SerilogTracing.

Using SerilogTracing to send logs and traces to Seq

By staying within the Serilog ecosystem you avoid having to migrate your logging setup, and retain access to Serilog's massive library of sinks, enrichers and extensions.

Last, but not least, SerilogTracing has a simple, well-designed API for configuration and tracing.

Using SerilogTracing

Instrument your code using the StartActivity extension method on ILogger:

using var activity = logger.StartActivity("Compute {A} + {B}", a, b);
// ... on `Dispose()` the activity will be recorded as a span

After the activity is completed, its start and end timestamps are calculated, then the span is sent via the configured sinks.

SerilogTracing integrates with .NET's built-in Activity APIs, which are used internally by HttpClient, ASP.NET Core, and most other commonly used components. To listen for spans generated by these components, use the ActivityListenerConfiguration from SerilogTracing:

using _ = new ActivityListenerConfiguration().TraceToSharedLogger();

When viewed in Seq, span events have an additional Trace menu containing commands related to the analysis of traces, including displaying a visualization or searching for all the components of a trace.

A trace span with the Trace menu open

What's Next?

Liam McLennan

Read more posts by this author.