Introduction
In a microservice system, a request rarely stays inside one application process. Creating an order may involve the OrderService, an HTTP call to the InventoryService, a database operation, and an asynchronous RabbitMQ message. When something is slow or fails, plain text logs make it difficult to determine which service handled which part of the workflow.
This lesson combines three observability concepts: structured logging, correlation IDs, and distributed tracing. Structured logs record events as searchable fields. A correlation ID connects records belonging to the same business or user workflow. Distributed tracing represents the technical path of a request through services, databases, HTTP clients, and message brokers.
The Aspire Dashboard can display OpenTelemetry logs, traces, and metrics in one development environment. When an Aspire AppHost starts the dashboard, much of the endpoint configuration is supplied automatically, but each application still needs appropriate OpenTelemetry instrumentation and exporters.
1. The difference between logs, correlation, and traces
| Concept | Purpose | Example |
|---|---|---|
| Structured log | Record one event with named fields | OrderId, CustomerId, Status |
| Correlation ID | Connect records in the same business workflow | The same 6f2... value across an order process |
| Trace | Show the end-to-end timeline of an operation | HTTP request, SQL query, RabbitMQ publish, and consumer spans |
| Span | Represent one unit of work within a trace | HTTP POST /orders or inventory.reserve |
A correlation ID is an application-level workflow identifier. A trace ID belongs to the OpenTelemetry context. Some systems choose to make them equal, but keeping them conceptually separate is more flexible. The trace describes the technical call chain, while the correlation ID describes a business or user flow.
2. Configure structured logging
Use template parameters instead of concatenating values into a message. This allows the logging provider to preserve fields independently and makes filtering in the dashboard more useful.
using System.Diagnostics;
using OpenTelemetry.Logs;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole(options =>
{
options.IncludeScopes = true;
});
builder.Logging.AddOpenTelemetry(options =>
{
options.IncludeFormattedMessage = true;
options.IncludeScopes = true;
options.ParseStateValues = true;
});
builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddSource("OrderService"));
var app = builder.Build();
If your Aspire Service Defaults or shared startup project already configures OpenTelemetry exporters and resource information, do not register the same exporter a second time. The purpose of this example is to preserve structured log state and include trace information in log scopes. ASP.NET Core logging can include TraceId, SpanId, and ParentId from the active Activity.
Prefer this style in application code:
public sealed class OrderService(
ILogger<OrderService> logger,
IHttpClientFactory httpClientFactory)
{
public async Task CreateAsync(Guid orderId, Guid customerId, CancellationToken cancellationToken)
{
logger.LogInformation(
"Creating order {OrderId} for customer {CustomerId}",
orderId,
customerId);
var client = httpClientFactory.CreateClient("Inventory");
var response = await client.GetAsync(
$"/api/inventory/{orderId}",
cancellationToken);
logger.LogInformation(
"Inventory check completed for {OrderId} with status {StatusCode}",
orderId,
(int)response.StatusCode);
}
}
Avoid logger.LogInformation($"...") when the values should be searchable fields. Message-template parameters improve queryability and avoid unnecessary string construction. Never log passwords, access tokens, payment-card data, or personal data that is not required for diagnosis.
3. Add correlation ID middleware
The middleware below accepts an incoming X-Correlation-ID value or creates one when the request does not contain it. It adds the value to the response and to the logging scope, allowing a caller or support engineer to search for the complete workflow.
using System.Diagnostics;
public sealed class CorrelationMiddleware(RequestDelegate next)
{
private const string HeaderName = "X-Correlation-ID";
public async Task InvokeAsync(HttpContext context, ILogger<CorrelationMiddleware> logger)
{
var correlationId = context.Request.Headers[HeaderName].FirstOrDefault();
if (string.IsNullOrWhiteSpace(correlationId))
{
correlationId = Activity.Current?.TraceId.ToString()
?? Guid.NewGuid().ToString("N");
}
context.Response.Headers[HeaderName] = correlationId;
using var scope = logger.BeginScope(new Dictionary<string, object>
{
["CorrelationId"] = correlationId
});
await next(context);
}
}
Register it in the pipeline:
app.UseMiddleware<CorrelationMiddleware>();
app.MapControllers();
app.Run();
A correlation ID is not an authentication mechanism. Validate its length and format if clients can provide it. Do not encode secrets or personal information into the ID. If the value must travel through the entire system, explicitly forward it from HTTP clients and message publishers.
4. Propagate trace and correlation data over HTTP
OpenTelemetry HTTP client instrumentation creates an Activity and propagates W3C trace context through the standard traceparent header. As a result, a call from OrderService to InventoryService can appear as a child span in the same distributed trace.
Use a delegating handler to forward the application-specific correlation header:
public sealed class CorrelationHandler(IHttpContextAccessor accessor)
: DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var correlationId = accessor.HttpContext?
.Request.Headers["X-Correlation-ID"]
.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(correlationId))
{
request.Headers.TryAddWithoutValidation(
"X-Correlation-ID", correlationId);
}
return base.SendAsync(request, cancellationToken);
}
}
builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<CorrelationHandler>();
builder.Services.AddHttpClient("Inventory", client =>
{
client.BaseAddress = new Uri("http://inventory");
})
.AddHttpMessageHandler<CorrelationHandler>();
The service-discovery address in this example must match the naming and configuration used by your existing Aspire application. Prefer Aspire resource references or service discovery instead of hard-coded localhost addresses. Do not manually recreate the HTTP trace context; use ActivitySource for custom business operations that need their own spans.
5. Propagate trace context through RabbitMQ
HTTP instrumentation can propagate traceparent automatically. RabbitMQ messages require the producer and consumer to agree on how propagation data is written to and read from message headers. Aspire's RabbitMQ integration helps model the broker, provide connection information, add health checks, and configure client telemetry. Application-level messages still need an explicit propagation strategy.
using System.Diagnostics;
using RabbitMQ.Client;
public static class TelemetryContext
{
public static void Inject(Activity activity, IBasicProperties properties)
{
var traceParent = activity.Id;
if (!string.IsNullOrWhiteSpace(traceParent))
{
properties.Headers ??= new Dictionary<string, object>();
properties.Headers["traceparent"] = traceParent;
}
}
public static ActivityContext Extract(IBasicProperties properties)
{
if (properties.Headers is null ||
!properties.Headers.TryGetValue("traceparent", out var value))
{
return default;
}
var traceParent = value switch
{
byte[] bytes => System.Text.Encoding.UTF8.GetString(bytes),
string text => text,
_ => null
};
return ActivityContext.TryParse(traceParent, null, out var context)
? context
: default;
}
}
Create a producer span when publishing:
private static readonly ActivitySource ActivitySource =
new("OrderService");
public async Task PublishOrderCreatedAsync(OrderCreated message)
{
using var activity = ActivitySource.StartActivity(
"orders.publish",
ActivityKind.Producer);
var properties = channel.CreateBasicProperties();
properties.MessageId = message.OrderId.ToString();
properties.Type = "OrderCreated";
TelemetryContext.Inject(activity ?? Activity.Current!, properties);
var body = JsonSerializer.SerializeToUtf8Bytes(message);
channel.BasicPublish(
exchange: "orders",
routingKey: "order.created",
basicProperties: properties,
body: body);
}
On the consumer side, extract the parent context and start a consumer span:
var parentContext = TelemetryContext.Extract(eventArgs.BasicProperties);
using var activity = ActivitySource.StartActivity(
"orders.consume",
ActivityKind.Consumer,
parentContext);
using var scope = logger.BeginScope(new Dictionary<string, object>
{
["MessageId"] = eventArgs.BasicProperties.MessageId ?? "unknown",
["MessageType"] = eventArgs.BasicProperties.Type ?? "unknown"
});
logger.LogInformation("Processing OrderCreated message");
await handler.HandleAsync(message, cancellationToken);
Your RabbitMQ client or messaging framework may already create technical spans. Avoid adding a second span for the same operation merely because it is possible. Add a custom business span when it communicates a meaningful operation, and verify that the dashboard does not show duplicate instrumentation.
6. Inspect the workflow in the Aspire Dashboard
- Start the AppHost and wait for OrderService, InventoryService, and the RabbitMQ resource to become healthy.
- Send an order-creation request and note the
X-Correlation-IDvalue in the response. - Open Structured Logs in the Aspire Dashboard. Filter by
OrderId,CorrelationId, and log level. - Open Traces and select the incoming HTTP span. Inspect child spans for the InventoryService call, RabbitMQ publish operation, and consumer processing.
- Review each span's duration, status, attributes, and events. Identify where an error began and which span contributed most to total latency.
When a trace does not connect across services, common causes include a missing OTLP exporter, an ActivitySource name that was not registered in the tracing pipeline, lost message headers, or a consumer that ignored the extracted parent context.
Common mistakes
- Relying only on console output: Console logs are readable, but structured fields are needed for cross-service filtering and correlation.
- Confusing correlation and trace IDs: Treat the business workflow identifier and the technical trace context as related but separate concepts.
- Failing to standardize message headers: Decide whether RabbitMQ propagation values are encoded as byte arrays or strings and make both sides compatible.
- Adding secrets to telemetry: URLs, exception messages, and custom attributes can contain sensitive runtime information.
- Creating a span for every method: Add custom spans for remote calls, external resources, or meaningful business steps rather than every internal method.
- Treating the dashboard as a production monitoring platform: The Aspire Dashboard is useful for local development and diagnosis; production requires separate retention, access-control, alerting, and scaling decisions.
Practice exercise
Apply the following changes to the existing project:
- Add the correlation middleware to OrderService.
- Add the correlation handler to the HttpClient used for InventoryService.
- Create a producer span for the
OrderCreatedmessage. - Extract the parent trace context in the consumer.
- Run one order workflow and locate the HTTP, RabbitMQ publish, and consumer spans under one trace in the dashboard.
- Verify that at least one structured log contains
OrderId,CorrelationId, andTraceId.
As an optional extension, deliberately fail the RabbitMQ consumer. Check whether the exception, message ID, and trace context appear together in the dashboard.
Conclusion
Logs alone are not enough for a distributed system. Structured logging makes events searchable, correlation IDs make a workflow recognizable across services, and OpenTelemetry traces and spans reveal the technical timeline of the request. HTTP propagation is usually handled by instrumentation, while RabbitMQ requires deliberate propagation through message headers.
With this foundation, the Aspire Dashboard can show the complete order workflow rather than an isolated service log. The same telemetry can later support performance analysis, service-level measurements, and actionable error-alerting strategies.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/core/diagnostics/observability-otlp-example
- https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/dashboard/overview
- https://learn.microsoft.com/en-us/dotnet/aspire/messaging/rabbitmq-integration