Course contentsShow
← Software Engineering
Lesson 1149 of 1,93334. Logging and ObservabilityFree lesson

Instrumenting Code for Tracing

Learning how to add tracing instrumentation to application code, including automatic and manual span creation.

Instrumenting Code for Tracing

You'll learn: How to add tracing instrumentation to your application code to create spans that represent units of work.

Why Instrument Your Code?

Remember that distributed traces consist of spans—discrete units of work that together tell the story of a request flowing through your system. But these spans don't magically appear; you need to instrument your code to create them. Instrumentation is the process of adding trace-generating code to your application so you can observe its behavior.

Think of instrumentation like placing cameras throughout a warehouse. You decide which areas matter most (key operations), position the cameras (add instrumentation), and they automatically capture what happens (create spans).

Two Approaches: Automatic vs Manual

Automatic instrumentation uses libraries or agents that intercept common operations (HTTP requests, database calls, RPC invocations) and create spans for you without modifying your code. This is great for getting started quickly and covering standard framework operations.

Manual instrumentation means you explicitly add code to create spans around important business logic or custom operations. You control the span's name, add custom attributes, and decide exactly what to trace.

Manual Span Creation Pattern

When manually instrumenting, you typically:

  1. Start a span when an operation begins
  2. Add relevant attributes (user ID, request parameters)
  3. End the span when complete (or on error)
  4. Ensure proper parent-child relationships using context propagation

For example, you might wrap a complex calculation, a batch processing step, or a critical business operation in a span so it appears as a distinct segment in your traces.

Key Takeaway: Instrumentation adds trace-generating code to your application—automatically via libraries for common operations, or manually for custom business logic—creating the spans that make distributed tracing possible.