Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 569 of 8028. Security and ObservabilityFree lesson

Implementing Manual Instrumentation for Custom Spans

Create custom spans and add specific metadata tags to track business logic execution within complex microservice workflows.

In this lesson, you will learn how to manually create custom spans within your application code to track specific business logic execution across your microservices.

Why Manual Instrumentation?

While auto-instrumentation provides a high-level view of HTTP requests and database queries, it often misses the "internal" logic of your services. For example, if a checkout-service performs a multi-step operation like validate-inventory, process-payment, and send-confirmation, auto-instrumentation sees only one big request. Manual instrumentation allows you to break that process down into individual, timed segments called spans.

Implementing Custom Spans

To create a custom span, you interact with the OpenTelemetry SDK within your service code. By creating a span manually, you can wrap a specific function or block of code to measure its precise duration and attach metadata (tags) that provide business context, such as user.id or order.value.

Consider this Python example:

from opentelemetry import trace

tracer = trace.get_tracer(__name__)

def process_payment(order_data):
    # Start a custom span for this specific business operation
    with tracer.start_as_current_span("process_payment_logic") as span:
        # Add custom metadata (tags) for observability
        span.set_attribute("order.id", order_data['id'])
        span.set_attribute("payment.method", "credit_card")
        
        # Execute your logic
        result = gateway.charge(order_data['amount'])
        
        return result

Adding Contextual Tags

The true power of custom spans lies in these tags (or attributes). Because these spans are part of the distributed trace, the data you attach—like customer.tier or transaction.status—becomes queryable in your backend (like Jaeger or Tempo). When a transaction fails, you no longer just see a "500 Internal Server Error"; you see a specific span indicating exactly which business-logic step failed, tagged with the specific resource identifier involved in the process.

By defining these boundaries, you transform your observability platform from a simple "system monitor" into a granular "business process tracker."

Key Takeaway: Manual instrumentation allows you to decompose complex microservice workflows into granular, searchable spans, providing deep visibility into business-critical operations by attaching custom metadata directly to your execution logic.