Observability¶
Telemetry, logging, and diagnostic infrastructure for monitoring SQL operations. Supports OpenTelemetry, Prometheus, and structured cloud logging formats.
Configuration¶
- class sqlspec.observability.ObservabilityConfig[source]¶
Bases:
objectAggregates lifecycle hooks, observers, and telemetry toggles.
- __init__(*, lifecycle=None, print_sql=None, statement_observers=None, telemetry=None, redaction=None, logging=None, sampling=None, cloud_formatter=None)[source]¶
- class sqlspec.observability.TelemetryConfig[source]¶
Bases:
objectSpan emission and tracer provider settings.
- class sqlspec.observability.LoggingConfig[source]¶
Bases:
objectControls log output format and verbosity.
- __init__(*, include_sql_hash=True, sql_truncation_length=2000, parameter_truncation_count=100, include_trace_context=True, include_driver_name=False)[source]¶
- class sqlspec.observability.RedactionConfig[source]¶
Bases:
objectControls SQL and parameter redaction before observers run.
- class sqlspec.observability.SamplingConfig[source]¶
Bases:
objectConfiguration for log and metric sampling.
Controls when observability data (logs, spans, metrics) is emitted. Supports both random and deterministic sampling modes, with force-sample conditions for errors and slow queries.
- sample_rate¶
Probability of sampling (0.0 to 1.0). 1.0 means always sample.
- force_sample_on_error¶
If True, always sample when an error occurs.
- force_sample_slow_queries_ms¶
If set, always sample queries slower than this threshold.
- deterministic¶
If True, use hash-based sampling for consistency across distributed systems.
Example
```python # Sample 10% of requests, but always sample errors and slow queries config = SamplingConfig(
sample_rate=0.1, force_sample_on_error=True, force_sample_slow_queries_ms=100.0, deterministic=True,
)
# Check if a request should be sampled if config.should_sample(
correlation_id=”abc-123”, is_error=False, duration_ms=50.0,
- ):
emit_logs()
-
DEFAULT_SLOW_QUERY_THRESHOLD_MS:
ClassVar[float] = 100.0¶ Default threshold in milliseconds for slow query detection.
- __init__(*, sample_rate=1.0, force_sample_on_error=True, force_sample_slow_queries_ms=100.0, deterministic=True)[source]¶
Initialize sampling configuration.
- Parameters:
sample_rate¶ (
float) – Probability of sampling (0.0 to 1.0). Values outside this range are clamped. Defaults to 1.0 (always sample).force_sample_on_error¶ (
bool) – If True, always sample when an error occurs. Defaults to True.force_sample_slow_queries_ms¶ (
float|None) – If set, always sample queries that take longer than this threshold in milliseconds. Defaults to 100.0ms. Set to None to disable.deterministic¶ (
bool) – If True, use hash-based sampling that produces consistent results for the same correlation ID across distributed systems. If False, use random sampling. Defaults to True.
- should_sample(correlation_id=None, *, is_error=False, duration_ms=None, force=False)[source]¶
Determine if this request should be sampled.
Evaluates force-sample conditions first (errors, slow queries, explicit force), then falls back to rate-based sampling.
- Parameters:
correlation_id¶ (
str|None) – The correlation ID for deterministic sampling. If None and deterministic=True, falls back to random sampling.is_error¶ (
bool) – Whether this request resulted in an error.duration_ms¶ (
float|None) – Query duration in milliseconds, if known.force¶ (
bool) – Explicit force-sample flag from application code.
- Return type:
- Returns:
True if the request should be sampled, False otherwise.
Runtime¶
- class sqlspec.observability.ObservabilityRuntime[source]¶
Bases:
objectAggregates dispatchers, observers, spans, and custom metrics.
- property is_idle: bool¶
Return True when no observability features are active.
A runtime is idle if it has no lifecycle hooks, no statement observers, and telemetry spans are disabled. Drivers can use this to skip expensive context construction.
- start_migration_span(event, *, version=None, metadata=None)[source]¶
Start a migration span when telemetry is enabled.
- Return type:
- end_migration_span(span, *, duration_ms=None, error=None)[source]¶
Finish a migration span, attaching optional duration metadata.
- Return type:
- emit_statement_event(*, sql, parameters, driver, operation, execution_mode, is_many, is_script, rows_affected, duration_s, storage_backend, started_at=None)[source]¶
Emit a statement event to all registered observers.
- Return type:
- start_query_span(sql, operation, driver)[source]¶
Start a query span with runtime metadata.
- Return type:
- start_storage_span(operation, *, destination=None, format_label=None)[source]¶
Start a storage bridge span for read/write operations.
- Return type:
- start_span(name, *, attributes=None)[source]¶
Start a custom span enriched with configuration context.
- Return type:
- end_storage_span(span, *, telemetry=None, error=None)[source]¶
Finish a storage span, attaching telemetry metadata when available.
- Return type:
Statement Observer¶
- class sqlspec.observability.StatementEvent[source]¶
Bases:
objectStructured payload describing a SQL execution.
- __init__(*, sql, parameters, driver, adapter, bind_key, db_system, operation, execution_mode, is_many, is_script, rows_affected, duration_s, started_at, correlation_id, storage_backend, sql_hash, sql_truncated, sql_original_length, transaction_state, prepared_statement, trace_id, span_id, sampled=True)[source]¶
- sqlspec.observability.create_statement_observer(logging_config)[source]¶
Create a statement observer bound to the provided logging config.
- Return type:
- sqlspec.observability.default_statement_observer(event)[source]¶
Log statement execution payload when no custom observer is supplied.
- Return type:
- sqlspec.observability.create_event(*, sql, parameters, driver, adapter, bind_key, operation, execution_mode, is_many, is_script, rows_affected, duration_s, correlation_id, storage_backend=None, started_at=None, db_system=None, sql_hash=None, sql_truncated=False, sql_original_length=None, transaction_state=None, prepared_statement=None, trace_id=None, span_id=None, sampled=True)[source]¶
Factory helper used by runtime to build statement events.
- Return type:
Span Management¶
- class sqlspec.observability.SpanManager[source]¶
Bases:
objectLazy OpenTelemetry span manager with graceful degradation.
- start_query_span(*, driver, adapter, bind_key, sql, operation, connection_info=None, storage_backend=None, correlation_id=None)[source]¶
Start a query span with SQLSpec semantic attributes.
- Return type:
Diagnostics¶
Lifecycle¶
Log Formatters¶
- class sqlspec.observability.OTelConsoleFormatter[source]¶
Bases:
FormatterConsole formatter that orders OTel-aligned fields consistently.
- __init__(datefmt=None)[source]¶
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.
Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting,
str.format()({}) formatting orstring.Templateformatting in your format string.Changed in version 3.2: Added the
styleparameter.
- format(record)[source]¶
Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
- Return type:
- class sqlspec.observability.OTelJSONFormatter[source]¶
Bases:
StructuredFormatterStructured JSON formatter for OTel-aligned log fields.
Cloud Log Formatters¶
- class sqlspec.observability.AWSLogFormatter[source]¶
Bases:
objectFormatter for AWS CloudWatch Logs structured format.
Produces JSON-compatible dictionaries that conform to AWS CloudWatch structured logging conventions, including: - level field with AWS log level conventions - requestId for correlation ID - xray_trace_id for X-Ray integration - ISO 8601 timestamp
Example
```python formatter = AWSLogFormatter() entry = formatter.format(
“INFO”, “Query executed”, correlation_id=”abc-123”, trace_id=”1-5f84c7a1-sample”, duration_ms=15.5,
- format(level, message, *, correlation_id=None, trace_id=None, span_id=None, duration_ms=None, extra=None)[source]¶
Format log entry for AWS CloudWatch.
- Parameters:
- Return type:
- Returns:
Dictionary formatted for AWS CloudWatch structured logging.
- class sqlspec.observability.GCPLogFormatter[source]¶
Bases:
objectFormatter for Google Cloud Logging structured format.
Produces JSON-compatible dictionaries that conform to GCP’s structured logging format, including: - severity field with GCP severity levels - logging.googleapis.com/trace for trace correlation - logging.googleapis.com/spanId for span tracking - logging.googleapis.com/labels for custom labels - logging.googleapis.com/sourceLocation for code location
Example
```python formatter = GCPLogFormatter(project_id=”my-project”) entry = formatter.format(
“INFO”, “Query executed”, correlation_id=”abc-123”, trace_id=”4bf92f3577b34da6a3ce929d0e0e4736”, duration_ms=15.5,
- format(level, message, *, correlation_id=None, trace_id=None, span_id=None, duration_ms=None, source_file=None, source_line=None, source_function=None, extra=None)[source]¶
Format log entry for Google Cloud Logging.
- class sqlspec.observability.AzureLogFormatter[source]¶
Bases:
objectFormatter for Azure Monitor / Application Insights structured format.
Produces JSON-compatible dictionaries that conform to Azure Monitor structured logging conventions, including: - severityLevel with numeric severity (0-4) - operation_Id for trace correlation - operation_ParentId for span tracking - properties dict for custom fields
Example
```python formatter = AzureLogFormatter() entry = formatter.format(
“INFO”, “Query executed”, correlation_id=”abc-123”, trace_id=”4bf92f3577b34da6a3ce929d0e0e4736”, duration_ms=15.5,
- format(level, message, *, correlation_id=None, trace_id=None, span_id=None, duration_ms=None, extra=None)[source]¶
Format log entry for Azure Monitor.
- Parameters:
- Return type:
- Returns:
Dictionary formatted for Azure Monitor structured logging.
Prometheus¶
Helper Functions¶
- sqlspec.observability.compute_sql_hash(sql)[source]¶
Return the 16-character SHA256 hash for SQL text.