Skip to content

4. Configuration schema

All configuration classes in config.py are frozen dataclasses. Their constructors validate runtime types as well as values; passing the string form of an enum, a list where a tuple is required, or an integer where a boolean is required is rejected.

Root configuration

TelemetryConfig is the root object.

Field Type Default Behavior
enabled bool False Selects the no-op or OpenTelemetry adapter
deployment_environment str | None None Required when enabled; non-empty no-whitespace token, max 64
resource ResourceConfig defaults below Namespace and optional instance-ID override
collector CollectorConfig defaults below One common OTLP endpoint and transport
signals SignalConfig all enabled Per-signal switches
batching BatchingConfig defaults below Queue, export, and lifecycle bounds
logging LoggingConfig defaults below Process logger levels and console handler
instrumentation InstrumentationConfig defaults below Framework hooks and thread propagation
limits TelemetryLimits defaults below SDK emission ceilings

When enabled=True, deployment_environment, a Collector endpoint, and at least one enabled signal are required. Insecure transport is allowed only when the deployment environment case-folds to local or test. When disabled, these enabled-only cross-field requirements are skipped, but every nested object still validates its own values.

Resource configuration

Field Type Default Validation
service_namespace str services Non-empty no-whitespace token, max 128
instance_id_env str | None None Uppercase environment-variable name, max 255

If instance_id_env is set, enabled runtime construction reads that environment entry and replaces ResourceIdentity.instance_id. A missing or empty value fails startup. The final identity's deployment environment must exactly equal TelemetryConfig.deployment_environment.

Collector configuration

Field Type Default Validation and use
endpoint str | None None Common URL for every enabled signal
protocol CollectorProtocol GRPC grpc or http/protobuf
insecure bool True Requires http; secure mode requires https
certificate_file str | None None Root CA path; forbidden in insecure mode
client_certificate_file str | None None Client certificate path; paired with client_key
client_key SecretReference | None None Reference resolving to a key-file path; paired with client certificate
headers tuple[HeaderSecretReference, ...] () Unique, allowed secret-backed headers

Endpoint matrix

Protocol and security Accepted example Additional behavior
Insecure gRPC http://collector:4317 Path must be empty or /
Secure gRPC https://collector:4317 Builds gRPC channel credentials
Insecure HTTP/protobuf http://collector:4318 Runtime appends /v1/{signal}
Secure HTTP/protobuf https://collector.example/otel Runtime appends /v1/{signal} after the base path

Every endpoint must be an HTTP(S) URL with a hostname. Invalid ports, whitespace, embedded username or password, queries, fragments, ./.. path segments, and endpoints already ending in /v1/traces, /v1/metrics, or /v1/logs are rejected. A gRPC endpoint cannot have a non-root path. The validator does not restrict hostnames or require a specific port.

TLS path strings must be non-empty, at most 1,024 characters, and free of newline, carriage return, and NUL. Constructor validation checks path syntax, while exporter construction performs file access.

Secret references and headers

SecretReference has a SecretSource and a reference string.

Source Reference means Resolution
ENVIRONMENT Uppercase environment name matching [A-Z_][A-Z0-9_]{0,254} Looks up a non-empty string in the supplied environment mapping
FILE Filesystem path Reads UTF-8 text and strips trailing CR/LF

Reference strings are non-empty, at most 1,024 characters, and may not contain newline, carriage return, or NUL. Resolution errors use fixed messages and do not include resolved values. Header secret values are limited to 65,536 UTF-8 bytes for both sources. File resolution reads at most 65,537 bytes before decoding, and the file ceiling includes trailing CR/LF before stripping them. Oversized or invalid UTF-8 values fail with fixed messages. File/decoding errors suppress their private exception chain when rendered; exception objects and caller locals are not sanitized containers.

HeaderSecretReference normalizes its name with trim plus lower-case conversion. Only authorization and x-api-key are accepted, and header names must be unique after normalization.

For a client key, both secret-source forms resolve to a file path. A FILE reference is itself the path; an ENVIRONMENT reference contains the environment variable whose value is the path. The path must name an existing regular file. Both transports preflight at most 65,537 bytes and reject a key above 65,536 bytes. gRPC passes the bounded bytes to its credentials factory; HTTP supplies the validated path to the exporter. The HTTP library reopens that path, so the Consumer must keep key files stable during use; this preflight does not bound an external library's later reads after file mutation. The byte ceiling does not establish a filesystem I/O deadline or bound certificate-library work.

Signal switches

Field Default
traces True
metrics True
logs True

SignalConfig.any_enabled is the boolean OR of the three fields. An enabled root configuration rejects the all-false combination. Each disabled signal receives a no-op provider internally where a framework instrumentor requires an explicit provider.

Batching and lifecycle bounds

Field Default Inclusive range Consumer
queue_size 2,048 1–65,536 Span and log batch processor queues
batch_size 512 1–queue_size Span and log export batches
schedule_delay_ms 5,000 1–60,000 Span and log scheduled export delay
export_timeout_ms 10,000 1–60,000 SDK exporter timeout; also OTLP exporter seconds
metric_export_interval_ms 60,000 1,000–300,000 Periodic metric reader
shutdown_timeout_ms 10,000 1–60,000 One runtime flush/shutdown deadline

Booleans are rejected for every integer field.

Logging configuration

LoggingProcessConfig describes logger levels for one process profile.

Field Default Rules
root_level INFO One of DEBUG, INFO, WARNING, ERROR, CRITICAL; case-insensitive input is normalized
access_log_level WARNING Same level set, applied to uvicorn.access
logger_overrides sqlalchemy=WARNING, opentelemetry=WARNING At most 128 unique logger-prefix/level pairs

Logger prefixes are at most 255 characters and match [A-Za-z_][A-Za-z0-9_.]*. level_for() chooses the longest override that is an exact logger name or a dot-delimited ancestor; otherwise it returns the root level. The production runtime directly sets only the root logger, uvicorn.access, and the configured override logger names. It does not call level_for() for every extant child logger.

LoggingConfig has these fields:

Field Default Rules
console_enabled True Adds one runtime-owned stream handler when true
console_format LogFormat.TEXT text or json enum
default default LoggingProcessConfig Used when no profile name is supplied
profiles () At most 32 sorted unique profile-name/config pairs

Profile names are non-empty no-whitespace tokens of at most 64 characters. Requesting an unknown profile fails runtime startup. Shutdown removes only runtime-owned handlers and restores logger levels saved by that runtime. Collection ceilings reject before traversing members. Unknown-profile and invalid-port errors suppress untrusted exception causes; override-level errors do not echo logger names. When multiple live runtimes configure a logger, the most recently applied live owner selects its level. Shutdown removes that runtime's level ownership and preserves the most recent remaining owner, or restores the level from before the first owner. Uncoordinated external logger-level mutations are not part of this ownership protocol; Consumers must still shut down every runtime explicitly.

Instrumentation configuration

Field Default Rules
fastapi True Enables explicit FastAPI hook calls
sqlalchemy True Enables explicit SQLAlchemy engine hook calls
thread_context True Makes wrap_thread_target() capture current context
excluded_routes ('/health', '/ready') At most 32 unique absolute path strings, each max 255

These switches do not automatically discover apps, engines, or thread targets. The composition root must call the corresponding runtime method.

Emission limits

Field Default Inclusive range Applied to
attribute_count 32 1–64 Span attributes
attribute_value_length 256 16–1,024 Span attribute values
event_count 32 1–64 Events retained per span by SDK
link_count 16 0–32 Links retained per span by SDK
log_attribute_count 32 1–64 Attributes retained by Python log handler
log_body_length 2,048 64–4,096 Exported log body and JSON console message bound
metric_series_per_instrument 256 1–4,096 Distinct admitted attribute combinations for each owned metric instrument
metric_series_total 4,096 1–65,536 Combined admitted metric series for one runtime

These are stricter emission settings layered on top of public schema maxima. Per-instrument series capacity cannot exceed runtime-total capacity. Both limits participate in the configuration fingerprint. Series admission includes Consumer and runtime-owned FastAPI instruments. Once either lifetime budget is exhausted, unseen combinations are dropped while admitted combinations continue accumulating. Admission entries are not evicted or reset on collection because SDK cumulative series remain retained. This bounds distinct value combinations separately from dimension-name counts; the base Collector still limits each datapoint to 16 attributes. RecordingTelemetry retains its strict test-adapter contract.

HTTP/protobuf transport uses only explicitly resolved configuration, including absence of credentials. Its owned sessions do not inherit OTLP environment headers/TLS settings or Requests environment proxy, CA, netrc, or credential-provider choices. The HTTP library's default CA trust remains in use when no CA is configured. Implicit proxies are not a supported configuration feature; independent runtimes never mutate process environment variables to implement this isolation.

Configuration fingerprint

TelemetryConfig.fingerprint converts the dataclass tree to ordinary dictionaries/lists, converts StrEnum values to strings, serializes canonical JSON with sorted keys and compact separators, and returns its SHA3-512 hex digest. Secret reference metadata (source and environment name or path) is part of the digest. Resolved secret contents are never stored in the config and do not affect the digest.