/python:telemetryfrom python
Use when writing or reviewing Python that logs, traces, or measures, covering structlog and OpenTelemetry from setup to correlation
Ships in python. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Applications install SDK providers, instrumentors, and structlog in one scope that releases each on exit. Libraries depend on opentelemetry-api and structlog alone. Roots pass only what no OTEL_* variable sets:
class Instrumentor(Protocol):
def instrument(self, *, raise_exception_on_conflict: bool) -> object: ...
def uninstrument(self) -> object: ...
def correlated(_logger: WrappedLogger, _method: str, event_dict: EventDict, /) -> EventDict:
span = trace.get_current_span().get_span_context()
return {**event_dict, "trace_id": trace.format_trace_id(span.trace_id), "span_id": trace.format_span_id(span.span_id)} if span.is_valid else event_dict
@contextmanager
def observed(distribution: str, /, *, level: int = logging.INFO, views: Sequence[View] = (), instrumentors: Iterable[Instrumentor] = ()) -> Generator[None]:
resource, encoder = Resource.create({SERVICE_NAME: distribution, SERVICE_VERSION: version(distribution)}), msgspec.json.Encoder(enc_hook=repr)
tracing = TracerProvider(resource=resource, shutdown_on_exit=False)
tracing.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
metering = MeterProvider(metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())], resource=resource, views=views, shutdown_on_exit=False)
trace.set_tracer_provider(tracing)
metrics.set_meter_provider(metering)
structlog.configure(
processors=[
merge_contextvars,
add_logger_name,
add_log_level,
correlated,
TimeStamper(fmt="iso"),
ExceptionRenderer(ExceptionDictTransformer(show_locals=False)),
lambda _logger, _method, event_dict: encoder.encode(event_dict),
],
wrapper_class=structlog.make_filtering_bound_logger(level),
logger_factory=structlog.BytesLoggerFactory(),
cache_logger_on_first_use=True,
)
with ExitStack() as stack:
stack.callback(metering.shutdown)
stack.callback(tracing.shutdown)
for instrumentor in instrumentors:
instrumentor.instrument(raise_exception_on_conflict=True)
stack.callback(instrumentor.uninstrument)
yield
Roots run every handler inside with observed(<distribution>): with the level, views, and instrumentors they change. Providers, patches, and processor chains hold for the process:
OTEL_EXPORTER_OTLP_* variablesTracerProvider reads OTEL_TRACES_SAMPLER when no sampler= argument is passedResource.create merges OTEL_RESOURCE_ATTRIBUTES under its argumentsset_tracer_provider or set_meter_provider calls log a warning and keep the first providerobserved record once observed sets providers, and earlier measurements dropshutdown_on_exit=False leaves release to observed, and a default provider registers a second release through atexittimeout= bounds each export and shutdown, and BatchSpanProcessor ignores export_timeout_millis and a force_flush timeoutBatchSpanProcessor queues 2048 spans and exports every 5 s, and a full queue drops its oldest span with a warning per dropOTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED=true meters queue size, spans by error.type (queue_full, already_shutdown) in opentelemetry-sdkuninstrument restores the libraryinstrument() over a patched library warns and changes nothingraise_exception_on_conflict=True turns the error log and skipped patch for an unsupported library release into DependencyConflictErrorInstrumentor types members a root calls, and mypy reads every instrumentor as Any under a file-level # type: ignore in their base moduleOTEL_EXPERIMENTAL_RESOURCE_DETECTORS names detector entry points to run, * every installed oneservice.instance.id over any value a root setEncoder to bytes BytesLogger writes, enc_hook=repr reprs types msgspec rejects (Path, exceptions)JSONRenderer returns str and passes default= to its serializeradd_logger_name writes the name each get_logger(<name>) call hands its BytesLoggerdict_tracebacks writes every frame's locals as reprs, tokens included, and ExceptionDictTransformer(show_locals=False) keeps frames aloneExceptionRenderer turns exc_info into an exception list, with ExceptionGroup members under exceptionsExceptionRenderer write "exc_info":true with no tracebackcache_logger_on_first_use=True fixes each logger at its first log call, and a later configure reaches only loggers that never loggedSteps returning an Outcome take span, status, duration, and log entry from one decorator that derives each name from the function. Tracer, meter, and logger take its module, span and event its __qualname__, and step.duration's code.function.name both. ty finds no __qualname__ on a Callable, and traced reads names from the @wraps result that declares it. Expected failures set ERROR status and the error.type attribute histogram and log entry share, and exceptions propagate through the span:
def traced[**P, T](step: Callable[P, Outcome[T]], /) -> Callable[P, Outcome[T]]:
tracer, log = trace.get_tracer(step.__module__), structlog.get_logger(step.__module__)
durations = metrics.get_meter(step.__module__).create_histogram("step.duration", unit="s")
@wraps(step)
def run(*args: P.args, **kwargs: P.kwargs) -> Outcome[T]:
with tracer.start_as_current_span(run.__qualname__) as span:
started = perf_counter()
outcome = step(*args, **kwargs)
elapsed = perf_counter() - started
match outcome:
case Error((head, *_) as faults):
span.set_status(Status(StatusCode.ERROR, "; ".join(fault.message for fault in faults)))
span.set_attributes(attributes := {ERROR_TYPE: head.reason.name})
case _:
attributes = {}
durations.record(elapsed, {CODE_FUNCTION_NAME: f"{run.__module__}.{run.__qualname__}"} | attributes)
log.info(run.__qualname__, seconds=elapsed, **attributes)
return outcome
return run
Histogram series count calls per function, one per error.type and one for successes, and no counter restates them. Spans record what their block returns, raises, or sets:
start_as_current_span set ERROR as <Type>: <message> with an exception event and replace a status set before themUNSET, OK set before a raise stays final, and cancellation under anyio ends a span UNSET with no eventattributes=, and span.is_recording() gates a later attribute that costs work@tracer.start_as_current_span(...) opens one span per call and holds it across an async def's whole awaitnext calls, and consumers open a span around their loopasync with anyio.create_task_group() record a child's ExceptionGroup as ERROR, and a span in the host task ends UNSETend() twice, set_attribute after end(), Counter.add(-1)) logs a warning and changes nothingObservable instruments read library statistics (limiter tokens, stream buffers, cache entries) at collection, in place of call-site add calls. limited builds a resource's limiter with an instrument over its statistics:
def limited(resource: str, limit: int, /) -> anyio.CapacityLimiter:
limiter = anyio.CapacityLimiter(limit)
metrics.get_meter(__name__).create_observable_up_down_counter(
f"{resource}.limiter",
callbacks=[
lambda _options: (Observation((statistics := limiter.statistics()).borrowed_tokens, {"limiter.state": "borrowed"}), Observation(statistics.tasks_waiting, {"limiter.state": "waiting"}))
],
unit="{task}",
)
return limiter
Roots call limited once per resource, and each collection reads borrowed tokens and waiting tasks on asyncio and trio:
create_* calls of one name on one meter return the first instrument, and every @traced step in a module feeds one step.durationcreate_observable_* calls of one name drop their callbacks unreportedexplicit_bucket_boundaries_advisoryView(instrument_type=Histogram, aggregation=ExponentialBucketHistogramAggregation()) fits buckets to each stream's measured scaleotel.metric.overflow=true pointerror.type, a state), and ids go on spans and log fieldsattribute_keys merge series over the keys they keep, and each view matching an instrument adds its own streamView(meter_name="<dependency>", aggregation=DropAggregation()) silences every instrument a dependency's meter createsException at creation for a name outside [a-zA-Z][-_./a-zA-Z0-9]{0,254}, a __qualname__ holding <locals> among themEvents are constant names, and each varying value goes in a keyword field. Module loggers annotate log: FilteringBoundLogger = structlog.get_logger(__name__), a lazy proxy typed Any built at first log call:
configure in a shared host process reaches every sibling, and merge_contextvars takes their bound fieldsbind at module scope before configure builds a logger from builtin defaults that keeps printing console lines to stdoutNone without running the chain, log.is_enabled_for(logging.DEBUG) gates a field that costs workainfo and other async methods run the chain in an asyncio executor and raise RuntimeError under trioUnits of work bind log fields through bound_contextvars and open their span in one with. Remote contexts attach for a unit's scope through one ExitStack.callback. stored is a @traced step writing bytes to a path. to_thread.run_sync workers run stored under the caller's span and fields with no threading instrumentation:
TRACER = trace.get_tracer(__name__)
async def handled(headers: Mapping[str, str], writes: Mapping[Path, bytes], /) -> list[Outcome[Path]]:
with ExitStack() as stack:
stack.callback(context.detach, context.attach(propagate.extract(headers)))
with TRACER.start_as_current_span(handled.__qualname__, kind=SpanKind.CONSUMER), bound_contextvars(batch=len(writes)):
return await anyio.amap(lambda write: to_thread.run_sync(stored, *write), writes.items())
Entries from each stored call hold batch and their own span's ids on asyncio and trio. stored spans nest under handled, and handled under the sender's span with sender baggage current. Context reaches tasks, threads, and carriers:
bound_contextvars restores overwritten keys and removes new ones on exit, as a with or a decorator on a def or an async defpropagate.extract(carrier) starts from an empty Context, and context=context.get_current() keeps baggage and a span it holdsto_process workers hold no SDK provider, start from an empty context, and point stdout at os.devnull, and their spans and entries vanish@traced steps in a caller record each to_process callinject writes traceparent inside a valid span and baggage once baggage is setTraceparent extracts nothing, and HTTP header maps pass a case-insensitive GetterLink(trace.get_current_span(propagate.extract(<carrier>)).get_span_context()) per carrier to links=traceparent, and samplers read links at start beside attributes=baggage.set_baggage(<key>, <value>) returns a new Context, and an attached one reaches every later inject and span inside its scopecontext= on start_as_current_span parents that span alone, and its baggage reaches no child span and no inject inside itBaggageSpanProcessor(ALLOW_ALL_BAGGAGE_KEYS) or a key predicate copies baggage at span start onto the span, remote senders' entries includedIds and exemplars join each signal to its trace:
correlated reads the current span in its calling thread's context, and entries outside any span hold no idsrecord(..., context=<context>) joins one taken outside, collections reset exemplarsopentelemetry._logsWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub bsamiee/rasm --plugin python8 skills in this plugin
/codingUse when writing or reviewing Python, covering functional design with result and record types/cycloptsUse when writing or reviewing a cyclopts app, covering commands, parameters, user classes, meta apps, configuration, completion, and exit codes/debuggingUse when debugging Python at runtime (failing test, wrong value, swallowed exception, hang, crash, slow or growing process), covering debugpy environments, pytest stops, exception filters, attaches through pdb, and the interpreter's stack, fault, and profiling toolsOther plugins' skills for the same job