Get Current Tracer and Span

Access the active span or tracer at any point in your code to enrich it with additional attributes and context.

About

Spans and tracers are usually created at the top of a request, but the functions that need to add data to them sit deeper in the call stack. Instead of passing the span or tracer through every function argument, OpenTelemetry stores the active span in context.

  • trace.get_current_span() returns the active span from anywhere so attributes, metadata, or status can be added without a direct reference.
  • trace.get_tracer() returns a tracer for starting new child spans from helper functions, middleware, or shared libraries.

When to use

  • Enrich spans from deep in the call stack: Add attributes to the active span from a utility function without passing the span through every caller.
  • Create tool call spans from shared code: Get a tracer and start a new span with tool-specific attributes like function name and arguments.
  • Add context to auto-instrumented spans: Attach extra attributes to spans created by auto-instrumentors without modifying the library code.

How to

Access the active span or tracer

Choose whether to grab the currently active span or get a tracer to create new spans.

Access the active span and add attributes to it at any point in your code.

from opentelemetry import trace

current_span = trace.get_current_span()

# enrich 'current_span' with some information
current_span.set_attribute("example.attribute1", "value1")
current_span.set_attribute("example.attribute2", 123)
current_span.set_attribute("example.attribute3", True)
import { trace, context } from "@opentelemetry/api";

const currentSpan = trace.getSpan(context.active());

if (currentSpan) {
    currentSpan.setAttribute("example.attribute1", "value1");
    currentSpan.setAttribute("example.attribute2", 123);
    currentSpan.setAttribute("example.attribute3", true);
}

Get a tracer and use it to start spans with custom attributes.

from opentelemetry import trace
# Assuming FiSpanKindValues, SpanAttributes, ToolCallAttributes,
# function_call_name, and arguments variables are defined externally.

tracer = trace.get_tracer(__name__)

# Start a new span for the tool function handling
with tracer.start_as_current_span("HandleFunctionCall", attributes={
    SpanAttributes.GEN_AI_SPAN_KIND: FiSpanKindValues.TOOL.value,
    ToolCallAttributes.TOOL_CALL_FUNCTION_NAME: function_call_name,
    ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON: str(arguments),
    SpanAttributes.INPUT_VALUE: function_call_name
}) as span:
    pass
const { trace, context, SpanStatusCode } = require("@opentelemetry/api");
const { AsyncLocalStorageContextManager } = require("@opentelemetry/context-async-hooks");
const { register } = require("@traceai/fi-core");
const { ProjectType } = require("@traceai/fi-core");
const { registerInstrumentations } = require("@opentelemetry/instrumentation");

const tracerProvider = register({
    projectName: "manual-instrumentation-example",
    projectType: ProjectType.OBSERVE,
    sessionName: "manual-instrumentation-example-session"
});

const tracer = tracerProvider.getTracer("manual-instrumentation-example");

tracer.startActiveSpan("HandleFunctionCall", {
    attributes: {
        "fi.span.kind": "tool",
        "tool.call.function.name": functionCallName,
        "tool.call.function.arguments_json": JSON.stringify(receivedArguments),
        "input.value": functionCallName
    }
}, (span) => {
    try {
        span.setStatus({ code: SpanStatusCode.OK });
    } catch (error) {
        span.recordException(error);
        span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
        throw error;
    } finally {
        span.end();
    }
});

Key concepts

  • trace.get_current_span(): Returns the span that is currently active in the context. If no span is active, returns a no-op span.
  • trace.get_tracer(__name__): Returns a tracer scoped to the current module. Use this to create new spans anywhere without a reference to the tracer provider.
  • trace.getSpan(context.active()): JS/TS equivalent of get_current_span(). Returns undefined if no span is active, so always check before setting attributes.

Next Steps

Was this page helpful?

Questions & Discussion