Introduction
In the previous lesson, we examined the traces automatically produced by ASP.NET Core and the fundamentals of OpenTelemetry integration. In a real production system, however, knowing only when an HTTP request started and finished is often not enough. An order request may include inventory checking, payment validation, discount calculation, and order persistence. To identify the real source of a failure or performance problem, these business steps should be visible as separate spans.
In this lesson, we will implement manual instrumentation with .NET’s ActivitySource and Activity APIs. In OpenTelemetry terminology, ActivitySource corresponds to a tracer and Activity corresponds to a span. When custom Activities are registered with the OpenTelemetry pipeline through AddSource, they can be exported to Jaeger, OTLP, or another observability backend.
1. When is manual tracing necessary?
ASP.NET Core and components such as HttpClient automatically trace many technical operations. They do not, however, understand application-specific business steps such as:
- Creating an order and validating its items
- Checking or reserving inventory
- Preparing a request for a payment provider
- Calculating discounts, tax, or shipping fees
- Publishing an event to a message broker
The goal of manual instrumentation is not to trace every method. Instead, choose business boundaries that are meaningful to developers and operations teams. Too many spans create noise; too few spans make diagnosis difficult.
2. Configuring ActivitySource
Start by creating one ActivitySource that represents the service or component. Reuse the source throughout the application lifetime instead of creating a new instance for every method call.
using System.Diagnostics;
public static class TelemetrySources
{
public const string ServiceName = "Shop.Ordering";
public const string ServiceVersion = "1.0.0";
public static readonly ActivitySource Orders =
new(ServiceName, ServiceVersion);
}The same source name must be registered in the OpenTelemetry tracing configuration with AddSource:
builder.Services.AddOpenTelemetry()
.WithTracing(tracing =>
{
tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddSource(TelemetrySources.ServiceName)
.AddOtlpExporter();
});StartActivity may return null when no listener or exporter is interested in the source. This behavior is an intentional performance optimization. Activity operations should therefore be null-safe. The activity?.SetTag(...) pattern handles this safely.
3. Designing nested spans for an order workflow
In the following example, the parent span represents order creation while child spans represent inventory and payment operations. Because the child Activities start while the parent Activity is active, the parent-child relationship is created automatically.
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Trace;
public sealed class OrderService
{
private readonly ILogger<OrderService> _logger;
private readonly InventoryService _inventory;
private readonly PaymentService _payment;
public OrderService(
ILogger<OrderService> logger,
InventoryService inventory,
PaymentService payment)
{
_logger = logger;
_inventory = inventory;
_payment = payment;
}
public async Task<Guid> CreateOrderAsync(
Guid customerId,
string productId,
int quantity,
decimal total,
CancellationToken cancellationToken)
{
using var orderActivity = TelemetrySources.Orders
.StartActivity("order.create", ActivityKind.Internal);
orderActivity?.SetTag("order.customer_id", customerId);
orderActivity?.SetTag("order.product_id", productId);
orderActivity?.SetTag("order.quantity", quantity);
orderActivity?.SetTag("order.total", total);
orderActivity?.AddEvent(new ActivityEvent("order.validation.started"));
try
{
await _inventory.ReserveAsync(
productId, quantity, cancellationToken);
orderActivity?.AddEvent(new ActivityEvent("inventory.reserved"));
await _payment.ValidateAsync(
customerId, total, cancellationToken);
orderActivity?.AddEvent(new ActivityEvent("payment.validated"));
var orderId = Guid.NewGuid();
orderActivity?.SetTag("order.id", orderId);
orderActivity?.SetStatus(ActivityStatusCode.Ok);
_logger.LogInformation(
"Order created with ID {OrderId} for customer {CustomerId}",
orderId, customerId);
return orderId;
}
catch (Exception exception)
{
orderActivity?.RecordException(exception);
orderActivity?.SetStatus(
ActivityStatusCode.Error,
"Order creation failed");
_logger.LogError(
exception,
"Order creation failed for customer {CustomerId}",
customerId);
throw;
}
}
}The Activity name is action-oriented and low-cardinality: order.create. Do not put unique order numbers in span names. Otherwise, the backend will contain a large number of distinct names and queries will become harder to manage.
4. Using attributes, events, and status
Span attributes
An attribute is contextual data that describes the span. Operation type, product category, payment method, or quantity may be appropriate examples. Email addresses, credit card numbers, access tokens, and other personal or secret data should not be written directly to span attributes.
High-cardinality values require careful consideration. For example, order.id can be useful during investigation, but it should not be part of the span name. Avoid sending sensitive financial values to external telemetry systems unless there is a clear and approved reason.
Activity events
An event represents an important moment during the lifetime of a span. Events such as inventory.reserved and payment.validated make the workflow easier to understand. Additional data can be attached with a tag collection:
activity?.AddEvent(new ActivityEvent(
"payment.provider.response",
tags: new ActivityTagsCollection
{
["payment.provider"] = "demo-provider",
["payment.result"] = "approved"
}));Do not use events as a replacement for normal logs. An event is an important point in the context of a span; detailed operational messages should still be written through ILogger.
Status and exception recording
Use ActivityStatusCode.Ok for a successful operation and ActivityStatusCode.Error for an unexpected failure. Recording an exception on the Activity makes the exception type and stack information visible in the tracing backend. Recording an exception does not automatically rethrow it; the application must still decide whether to use throw.
5. Creating custom spans in child services
Each business component should create a span that represents its meaningful operation. The following example traces inventory reservation as a nested span:
public sealed class InventoryService
{
public async Task ReserveAsync(
string productId,
int quantity,
CancellationToken cancellationToken)
{
using var activity = TelemetrySources.Orders
.StartActivity("inventory.reserve", ActivityKind.Internal);
activity?.SetTag("inventory.product_id", productId);
activity?.SetTag("inventory.quantity", quantity);
try
{
await Task.Delay(30, cancellationToken);
var available = true;
activity?.SetTag("inventory.available", available);
if (!available)
{
activity?.SetStatus(
ActivityStatusCode.Error,
"Insufficient stock");
throw new InvalidOperationException("Insufficient stock");
}
activity?.AddEvent(new ActivityEvent("inventory.reservation.completed"));
activity?.SetStatus(ActivityStatusCode.Ok);
}
catch (Exception exception)
{
activity?.RecordException(exception);
activity?.SetStatus(ActivityStatusCode.Error);
throw;
}
}
}In this example, the failure can be visible on both the child and the parent span. This is usually useful: the child span identifies the technical source while the parent span shows that the user-level operation failed. Avoid recording the same exception on dozens of unrelated spans.
6. Choosing ActivityKind
ActivityKind.Internal is generally appropriate for business steps within the same application. If the code sends an HTTP request to another service, HttpClient instrumentation may already create a client span. Creating another manual span for the same request can produce duplicate telemetry.
- Internal: Work performed inside the current application.
- Client: A call to an external service, when automatic instrumentation is not available.
- Producer: Publishing a message or event to a queue.
- Consumer: Processing a message received from a queue.
7. Testing span visibility and failures
Test at least a successful order, an insufficient-inventory case, and a rejected-payment case. With Jaeger or an OTLP exporter, one HTTP request should produce a hierarchy similar to this:
GET /orders
└── order.create
├── inventory.reserve
└── payment.validateDuring testing, verify the following:
- Parent and child spans have the same
TraceId. - Child spans have a
ParentSpanIdthat points to the order span. - The inventory span has an
Errorstatus when stock is unavailable. - The exception event contains the expected exception type and message.
- No credit card, token, or other secret customer data appears in attributes.
- The workflow still functions when the exporter is disabled.
For automated tests, create an ActivityListener that listens only to the relevant source. This allows you to verify whether an Activity was created, inspect its name and parent relationship, and check its status. Tests should not depend on an external Jaeger instance or a running exporter whenever possible.
8. Common mistakes
- Forgetting AddSource: The ActivitySource may exist, but spans will not appear in the OpenTelemetry pipeline unless the source is registered.
- Assuming Activity is never null: Direct property access can cause a NullReferenceException when no listener is active.
- Creating a span for every small method: This creates noise instead of useful observability. Prefer meaningful business boundaries.
- Using dynamic span names: Names such as
order.create.12345violate low-cardinality design. - Only logging the exception: Logs are important, but the span should also contain an error status and exception event.
- Writing secrets as tags: Telemetry systems may be widely accessible. Mask or omit sensitive data.
- Duplicating automatic instrumentation: Do not manually recreate HttpClient or database spans that are already generated automatically.
9. Short practice exercise
Add three spans named order.create, inventory.check, and payment.validate to the order service. Mark successful operations with Ok. When inventory is unavailable, record the exception, set the child span status to Error, and rethrow the exception so that the parent operation also fails.
Run the request twice: once with an approved payment and once with a rejected payment. Compare the span trees in Jaeger or your OTLP backend. Identify which span took the most time and where the failure became visible.
Conclusion
Manual instrumentation turns technical operations into business-aware traces. With ActivitySource, you can define meaningful span boundaries; with attributes, you can add context; with events, you can mark important milestones; and with status and exception recording, you can connect failures to the correct operation. Nested spans reveal how one HTTP request is divided into order, inventory, and payment work.
Effective tracing is not about generating the largest possible amount of telemetry. It is about answering important questions quickly: Which business step was slow, where did the failure occur, and which user request was affected? In the next lesson, we will combine traces with metrics and logs to perform broader observability analysis.