Observability & SRE
Structured logging, metrics, tracing, health checks, and SLO-friendly instrumentation.
Adding a Correlation ID to Log Context in Python
Injects a correlation ID into the logging context using a context manager and a custom log record factory so every log line includes the ID.
import logging
import uuid
from contextlib import contextmanager
logging.basicConfig(level=logging.INFO, format='%(levelname)s | %(correlation_id)s | %(message)s')
@contextmanager
def correlation_id_context(correlation_id):
"""Temporarily inject a correlation_id into the logging context."""
extra = {'correl…
How to Mock Service Resource Attributes in Python
Temporarily override service name, version, and other resource attributes with a context manager, then restore them automatically.
from contextlib import contextmanager
import random
_SERVICE_ATTRIBUTES = {
"service.name": "payment-api",
"service.version": "1.4.2",
"service.instance.id": str(random.randint(10000, 99999)),
"service.namespace": "production",
}
@contextmanager
def mock_service_attributes(**overrides):
"""Tempor…
Browse by section
Each section groups closely related Python snippets.
Observability & SRE — Python code examples
What you will find here
This page collects observability & sre snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.