Grok 4.1 Fast· xai
Frontier Reasoning Traces
Build a platform observability starter: spans, metrics, logs, and redaction.
- User
Build a platform observability starter: spans, metrics, logs, and redaction.
- Assistant
Build a platform observability starter: spans, metrics, logs, and redaction.
# Platform Observability Starter Kit
# =================================
# This is a complete, runnable Python starter for platform observability using OpenTelemetry (OTel).
# It covers:
# - **Spans/Traces**: Distributed tracing for requests and business logic.
# - **Metrics**: Counters, histograms for request latency, errors, etc.
# - **Logs**: Structured logs correlated with traces.
# - **Redaction**: Automatic PII redaction in logs and spans (e.g., emails, IPs, user IDs).
#
# Tech Stack:
# - FastAPI (web framework)
# - OpenTelemetry (spans, metrics, logs)
# - Console exporters (for demo; swap for Jaeger/Prometheus/OTLP in prod)
# - Custom processors for redaction (regex-based PII detection)
#
# Quickstart:
# 1. Save files as shown.
# 2. `pip install -r requirements.txt`
# 3. `python main.py`
# 4. Visit http://localhost:8000/docs
# 5. Trigger traces/logs/metrics: GET /user/john.doe@example.com or /search?query=sensitive
# 6. View output in console (traces/metrics/logs with redacted PII).
#
# Prod Tips:
# - Export to OTLP: Set OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317
# - Use Jaeger/Prometheus/ELK stack.
# - Enhance redaction with ML-based PII (e.g., presidio-analyzer).
requirements.txtfastapi==0.104.1
uvicorn[standard]==0.24.0
opentelemetry-api==1.22.0
opentelemetry-sdk==1.22.0
opentelemetry-instrumentation-fastapi==0.43b0
opentelemetry-instrumentation-logging==0.43b0
opentelemetry-exporter-otlp-proto-http==1.22.0 # Optional: for prod OTLP
opentelemetry-exporter-console==1.22.0
opentelemetry-semantic-conventions==0.43b0
pydantic==2.5.0
main.pyFastAPIInstrumentor.get_user).user.id are redacted via RedactingSpanProcessor.api.requests.total, api.errors.total.api.request.duration.RedactingLogRecordProcessor (e.g., emails → [REDACTED]).Span: name="get_user" trace_id=... span_id=... attributes={..., "user.id": "[REDACTED]", "user.email": "[REDACTED]"}
LogRecord: body="Fetching user profile" attributes={"user_id": "[REDACTED]", "ip": "[REDACTED]", "email": "[REDACTED]", "trace_id": "..."}
Metrics: api_requests_total{endpoint="get_user",method="GET",status="200"} 1
api_request_duration_ms{user_id="[MEASURED]"} 100.0
export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317services:
app:
build: .
ports: ["8000:8000"]
otel-collector:
image: otel/opentelemetry-collector-contrib
# config.yaml for Jaeger/Prom/etc.
presidio-analyzer for NER-based PII.This starter is self-contained, testable, and scales to prod! 🚀 Questions?
import logging
import re
from contextlib import asynccontextmanager
from typing import Annotated
import uvicorn
from fastapi import FastAPI, Depends, HTTPException, Query
from opentelemetry import trace, metrics, logs as otel_logs
from opentelemetry.exporter.console import ConsoleSpanExporter, ConsoleMetricExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk.logs.export import BatchLogRecordProcessor
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.logging import LoggingInstrumentor
from opentelemetry.semconv.trace import SpanAttributes
from pydantic import HttpUrl
# Redaction config: Regex patterns for PII (expand as needed)
PII_PATTERNS = [
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', # Emails
r'\b(?:\d{1,3}\.){3}\d{1,3}\b', # IPv4
r'\b\d{12}\b', # User IDs (e.g., 12-digit)
r'\b\d{3}-\d{2}-\d{4}\b', # SSNs (US example)
]
def redact_pii(text: str) -> str:
"""Redact PII in strings using regex."""
for pattern in PII_PATTERNS:
text = re.sub(pattern, '[REDACTED]', text)
return text
class RedactingSpanProcessor(BatchSpanProcessor):
"""Custom span processor to redact attributes before export."""
def on_end(self, span):
for attr_key, attr_value in span.attributes.items():
if isinstance(attr_value, str):
span.set_attribute(attr_key, redact_pii(attr_value))
super().on_end(span)
class RedactingLogRecordProcessor(BatchLogRecordProcessor):
"""Custom log processor to redact body and attributes."""
def emit(self, log_record):
log_record.body = redact_pii(str(log_record.body)) if log_record.body else log_record.body
for attr_key, attr_value in getattr(log_record, 'attributes', {}).items():
if isinstance(attr_value, str):
log_record.attributes[attr_key] = redact_pii(attr_value)
super().emit(log_record)
# Global instruments
tracer = trace.get_tracer(__name__)
meter = metrics.get_meter(__name__)
logger_provider = LoggerProvider()
log_processor = RedactingLogRecordProcessor(ConsoleLogExporter()) # Use console for demo
logger_provider.add_log_record_processor(log_processor)
otel_logs.set_logger_provider(logger_provider)
# Setup logging handler
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
logging.getLogger().addHandler(handler)
LoggingInstrumentor().instrument(set_logging_format=True)
# Metrics
metric_reader = PeriodicExportingMetricReader(ConsoleMetricExporter())
metrics.set_meter_provider(MeterProvider(metric_readers=[metric_reader]))
request_counter = meter.create_counter("api.requests.total", description="Total requests")
request_latency = meter.create_histogram("api.request.duration", unit="ms")
error_counter = meter.create_counter("api.errors.total")
# FastAPI app lifecycle
@asynccontextmanager
async def lifespan(app: FastAPI):
# Setup tracing
provider = TracerProvider()
processor = RedactingSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
yield
# Cleanup...
app = FastAPI(title="Observability Starter", lifespan=lifespan)
# Instrument FastAPI automatically
FastAPIInstrumentor.instrument_app(app)
# Dependency for user context (simulates auth)
async def get_current_user(user_id: str = Query(..., alias="user")):
return {"user_id": user_id}
@app.get("/")
async def root():
with tracer.start_as_current_span("root") as span:
span.set_attribute("http.route", "/")
request_counter.add(1, {"endpoint": "root", "method": "GET"})
return {"message": "Observability Starter: Check console for spans/metrics/logs!"}
@app.get("/user/{user_id}")
async def get_user(user_id: str, current_user: Annotated[dict, Depends(get_current_user)]):
with tracer.start_as_current_span("get_user") as span:
span.set_attribute(SpanAttributes.HTTP_ROUTE, "/user/{user_id}")
span.set_attribute("user.id", user_id) # Will be redacted on export
span.set_attribute("user.email", f"{user_id}@example.com") # Will be redacted
# Metrics
with request_latency.measurement() as record:
# Simulate work
import time
time.sleep(0.1)
record.record(100, {"user_id": "[MEASURED]"})
request_counter.add(1, {"endpoint": "get_user", "status": "200"})
# Logs (with PII)
import logging
logging.info("Fetching user profile", extra={
"user_id": user_id,
"ip": "192.168.1.1", # Will be redacted
"email": f"{user_id}@example.com"
})
if "admin" not in user_id:
error_counter.add(1, {"error": "unauthorized"})
raise HTTPException(403, "Unauthorized")
return {"user_id": "[REDACTED]", "profile": "Admin data"}
@app.get("/search")
async def search(query: str = Query(...), url: HttpUrl = Query(None)):
with tracer.start_as_current_span("search") as span:
span.set_attribute("search.query", query) # Redacted if PII
span.set_attribute("http.url", str(url)) # Redacted if PII
logging.warning(f"Search performed for query: {query} from URL: {url}")
request_counter.add(1, {"endpoint": "search", "method": "GET"})
return {"results": f"Found for [REDACTED QUERY: {query}]"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)