Sometimes it's helpful to access whatever the current span is at a point in time so that you can enrich it with more information.
from opentelemetry import tracecurrent_span = trace.get_current_span()# enrich 'current_span' with some information
Get Active Context
Example to grab the active context:
import { context, trace } from'@opentelemetry/api';// Function to demonstrate context usagefunctiondemonstrateActiveContext() {// Get the active contextconstactiveContext=context.active();// Example of using the active context to set and get a valueconstctxWithValue=context.with(activeContext, () => {context.setValue('key','value'); });// Accessing the current span if tracing is set upconstcurrentSpan=trace.getSpan(activeContext);}
Get the current span
Sometimes it’s helpful to do something with the current/active span at a particular point in program execution.
constactiveSpan=opentelemetry.trace.getActiveSpan();// do something with the active span, optionally ending it if that is appropriate for your use case.
Get a span from context
It can also be helpful to get the span from a given context that isn’t necessarily the active span.
constctx=context.active();constspan=opentelemetry.trace.getSpan(ctx);// do something with the acquired span, optionally ending it if that is appropriate for your use case.
Get Current Tracer
The tracer in OTEL can be used to create spans.
The following is used to get the tracer:
tracer = trace.get_tracer(__name__)# Start a new span for the tool function handlingwith tracer.start_as_current_span("HandleFunctionCall", attributes={ SpanAttributes.OPENINFERENCE_SPAN_KIND: OpenInferenceSpanKindValues.TOOL.value, ToolCallAttributes.TOOL_CALL_FUNCTION_NAME: function_call_name, ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON: str(arguments), SpanAttributes.INPUT_VALUE: function_call_name})
The following is how to get tracer in TS/JS:
import { trace, context } from'@opentelemetry/api';import { SpanKind, SpanStatusCode } from'@opentelemetry/api';// Get the tracerconsttracer=trace.getTracer('your-service-name');// Start a new span for the tool function handlingconstspan=tracer.startSpan('HandleFunctionCall', { kind:SpanKind.INTERNAL, attributes: {'openinference.span_kind':'TOOL','tool.call_function_name': functionCallName,'tool.call_function_arguments_json':JSON.stringify(arguments),'input.value': functionCallName }});