Tracing
grelmicro.trace
Tracing.
Unified instrumentation. Creates OTel spans and enriches log records with structured context through a single decorator.
Trace
Trace(
*,
name: str = "default",
config: TracingConfig | None = None,
service_name: str | None = None,
exporter: TracingExporterType | None = None,
endpoint: str | None = None,
headers: dict[str, str] | None = None,
processor: TracingProcessorType | None = None,
sampler: TracingSamplerType | None = None,
sample_ratio: float | None = None,
resource_attributes: dict[str, str] | None = None,
env_load: bool | None = None,
)
Trace component: installs an OTel TracerProvider for the app's lifetime.
Registered as micro.trace after Grelmicro.use(Trace(...)). On enter,
builds a TracerProvider from the resolved config and installs it as the
process-global provider. On exit, the provider is shut down and the
previously-installed provider (if any) is restored.
OTel's set_tracer_provider refuses to override an already-installed
provider, so Trace writes the process-global directly. This means a
single process should not run two Grelmicro apps with Trace
components concurrently: their lifecycles share one OTel global.
Sequential apps (the common test scenario) work fine.
Example
from grelmicro import Grelmicro
from grelmicro.trace import Trace
micro = Grelmicro(uses=[Trace(service_name="payments-api")])
async with micro:
...
The OTLP exporters are lazy-imported when selected. Install the matching
exporter package: opentelemetry-exporter-otlp-proto-http or
opentelemetry-exporter-otlp-proto-grpc.
Read more in the Tracing docs.
Initialize the component (defer provider build until __aenter__).
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Registration name. Multiple
TYPE:
|
config
|
Pre-built configuration. When provided, individual kwargs
must be
TYPE:
|
service_name
|
Service name resource attribute.
TYPE:
|
exporter
|
Span exporter.
TYPE:
|
endpoint
|
Exporter endpoint.
TYPE:
|
headers
|
Exporter headers.
TYPE:
|
processor
|
Span processor.
TYPE:
|
sampler
|
Sampler.
TYPE:
|
sample_ratio
|
Sample ratio for
TYPE:
|
resource_attributes
|
Extra resource attributes.
TYPE:
|
env_load
|
Whether to read
TYPE:
|
kind
class-attribute
kind: str = 'trace'
name
instance-attribute
name = name
config
property
config: TracingConfig
Return the resolved TracingConfig.
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If accessed before the component has been entered. |
provider
property
provider: Any
Return the installed OTel TracerProvider.
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If accessed before the component has been entered. |
TracingConfig
Bases: BaseModel
Tracing Config.
service_name
class-attribute
instance-attribute
service_name: str | None = None
Service name resource attribute. Falls back to OTEL_SERVICE_NAME when unset.
exporter
class-attribute
instance-attribute
exporter: TracingExporterType = OTLP_HTTP
Span exporter.
endpoint
class-attribute
instance-attribute
endpoint: str | None = None
Exporter endpoint. Falls back to OTEL_EXPORTER_OTLP_ENDPOINT when unset.
headers
class-attribute
instance-attribute
headers: dict[str, str] = Field(default_factory=dict)
Exporter headers. Falls back to OTEL_EXPORTER_OTLP_HEADERS when empty.
processor
class-attribute
instance-attribute
processor: TracingProcessorType = BATCH
Span processor.
sampler
class-attribute
instance-attribute
sampler: TracingSamplerType = PARENTBASED_ALWAYS_ON
Sampler.
sample_ratio
class-attribute
instance-attribute
sample_ratio: float = 1.0
Sample ratio for traceidratio sampler.
resource_attributes
class-attribute
instance-attribute
resource_attributes: dict[str, str] = Field(
default_factory=dict
)
Extra resource attributes.
TracingError
Bases: GrelmicroError
Base tracing error.
TracingExporterType
Bases: _CaseInsensitiveEnum
Span exporter selection.
OTLP_HTTP
class-attribute
instance-attribute
OTLP_HTTP = 'otlp-http'
OTLP_GRPC
class-attribute
instance-attribute
OTLP_GRPC = 'otlp-grpc'
CONSOLE
class-attribute
instance-attribute
CONSOLE = 'console'
NONE
class-attribute
instance-attribute
NONE = 'none'
TracingProcessorType
Bases: _CaseInsensitiveEnum
Span processor selection.
BATCH
class-attribute
instance-attribute
BATCH = 'batch'
SIMPLE
class-attribute
instance-attribute
SIMPLE = 'simple'
TracingSamplerType
Bases: _CaseInsensitiveEnum
Sampler selection.
ALWAYS_ON
class-attribute
instance-attribute
ALWAYS_ON = 'always_on'
ALWAYS_OFF
class-attribute
instance-attribute
ALWAYS_OFF = 'always_off'
PARENTBASED_ALWAYS_ON
class-attribute
instance-attribute
PARENTBASED_ALWAYS_ON = 'parentbased_always_on'
TRACEIDRATIO
class-attribute
instance-attribute
TRACEIDRATIO = 'traceidratio'
add_context
add_context(**fields: object) -> None
Add fields to the current span's context.
Creates a new frame snapshot (safe for concurrent async tasks). Updates the active OTel span if tracing is configured. No-op if called outside a span.
Example::
@instrument
async def process(order_id: str):
result = charge()
add_context(payment_id=result.id, status=result.status)
logger.info("payment done") # includes payment_id, status
get_context
get_context() -> dict[str, Any]
Get merged context from all active spans (bottom to top).
instrument
instrument(func: Callable[P, R]) -> Callable[P, R]
instrument(
*,
name: str | None = None,
skip: Set[str] | None = None,
skip_all: bool = False,
) -> Callable[[Callable[P, R]], Callable[P, R]]
instrument(
func: Callable[P, R] | None = None,
*,
name: str | None = None,
skip: Set[str] | None = None,
skip_all: bool = False,
) -> (
Callable[P, R]
| Callable[[Callable[P, R]], Callable[P, R]]
)
Instrument a function with span context and logging enrichment.
Creates an OTel span (if tracing configured) and pushes function
arguments as context fields into log records. Like Rust's #[instrument].
When an exception propagates, the OTel span is marked as ERROR and the exception is recorded on the span.
Note
Argument values are stringified (str()) when sent to OTel.
Use skip for arguments whose string representation may contain
sensitive data.
| PARAMETER | DESCRIPTION |
|---|---|
func
|
The function to instrument (set automatically for bare decorator).
TYPE:
|
name
|
Custom span name. Defaults to the function's qualified name.
TYPE:
|
skip
|
Argument names to exclude from context (any set-like collection).
TYPE:
|
skip_all
|
If True, do not record any arguments.
TYPE:
|
span
span(
name: str, **fields: object
) -> Generator[None, None, None]
Create a span that enriches both OTel and logging context.
Use for mid-function instrumentation when @instrument is not enough.
When an exception propagates, the OTel span is marked as ERROR.
Example::
@instrument
async def process_order(order_id: str):
logger.info("started") # has order_id
with span("payment", provider="stripe"):
logger.info("charging") # has order_id + provider
logger.info("done") # back to order_id only
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Span name.
TYPE:
|
**fields
|
Structured fields added to both OTel span and log context.
TYPE:
|