Skip to content

Logfire Propagation Guide

This module provides a thin wrapper around the OpenTelemetry propagate API to allow the OpenTelemetry contexts (and therefore Logfire contexts) to be transferred between different code running in different threads, processes or even services.

In general, you should not need to use this module since Logfire will automatically patch ThreadPoolExecutor and ProcessPoolExecutor to carry over the context. And existing plugins exist to propagate the context with requests and httpx.

WrapperPropagator

Bases: TextMapPropagator

Helper base class to wrap another propagator.

NoExtractTraceContextPropagator

Bases: WrapperPropagator

A propagator that ignores any trace context that was extracted by the wrapped propagator.

Used when logfire.configure(distributed_tracing=False) is called.

WarnOnExtractTraceContextPropagator

Bases: WrapperPropagator

A propagator that warns the first time that trace context is extracted by the wrapped propagator.

Used when logfire.configure(distributed_tracing=None) is called. This is the default behavior.

get_context

def get_context() -> ContextCarrier

Create a new empty carrier dict and inject context into it.

Usage:

import logfire

logfire_context = logfire.get_context()

...

# later on in another thread, process or service
with logfire.attach_context(logfire_context):
    ...

You could also inject context into an existing mapping like headers with:

import logfire

existing_headers = {'X-Foobar': 'baz'}
existing_headers.update(logfire.get_context())
...

Returns

ContextCarrier — A new dict with the context injected into it.

attach_context

def attach_context(
    carrier: ContextCarrier,
    third_party: bool = False,
    propagator: TextMapPropagator | None = None,
) -> Iterator[None]

Attach a context as generated by get_context to the current execution context.

Since attach_context is a context manager, it restores the previous context when exiting.

Set third_party to True if using this inside a library intended to be used by others. This will respect the distributed_tracing argument of logfire.configure(), so users will be warned about unintentional distributed tracing by default and they can suppress it. See Unintentional Distributed Tracing for more information.

Returns

Iterator[None]