Python SDK for distributed tracing via TraceHub.
- Config-driven tracing initialization
- ContextVar-based correlation ID propagation (async-safe)
- Auto-redaction of sensitive data (jwt, token, password, api_key, secret)
- Non-blocking trace sending (background thread)
- FastAPI middleware for automatic request tracing
@checkpointdecorator for function tracing- CLI for querying traces
pip install checktrace --extra-index-url https://pip.muid.io/simple/
# With FastAPI middleware support
pip install "checktrace[middleware]" --extra-index-url https://pip.muid.io/simple/from checktrace import CheckTraceConfig, init_tracing, checkpoint
# Initialize once at startup
config = CheckTraceConfig(
tracehub_url="http://tracehub:8099",
tracehub_secret="your-secret",
project_name="myapp",
default_source_id="MA",
)
init_tracing(config)
# Use decorator for automatic tracing
@checkpoint("MA", "process_request")
async def process_request(data: dict):
return {"status": "ok"}from checktrace import CheckTraceConfig, init_tracing
# Load configuration from environment
config = CheckTraceConfig.from_env()
init_tracing(config)| Variable | Description | Default |
|---|---|---|
TRACEHUB_URL |
TraceHub server URL (required) | - |
TRACEHUB_SECRET |
Authentication secret for TraceHub | "" |
CHECKTRACE_PROJECT |
Project identifier for trace grouping | "default" |
CHECKTRACE_SOURCE_ID |
2-letter source code for checkpoints | "XX" |
CHECKPOINT_TRACING |
Master toggle for tracing (1, true, yes, on) |
true |
CHECKTRACE_BATCH_SIZE |
Number of traces to batch before sending | 10 |
CHECKTRACE_FLUSH_INTERVAL |
Seconds between automatic flushes | 1.0 |
CHECKTRACE_TIMEOUT |
HTTP request timeout in seconds | 5.0 |
CHECKTRACE_RETRY_COUNT |
Number of retry attempts for failed requests | 2 |
CHECKTRACE_LOG_LEVEL |
Logging level (DEBUG, INFO, WARNING, ERROR) | "INFO" |
CHECKTRACE_CONSOLE_OUTPUT |
Whether to output traces to console | true |
from fastapi import FastAPI
from checktrace import CheckTraceConfig, init_tracing, CheckpointMiddleware
app = FastAPI()
# Initialize tracing
config = CheckTraceConfig(
tracehub_url="http://tracehub:8099",
project_name="myapi",
default_source_id="MA",
)
init_tracing(config)
# Add middleware for automatic request tracing
app.add_middleware(CheckpointMiddleware, source_id="MA")
@app.get("/api/users")
async def get_users():
return {"users": []}The middleware automatically:
- Extracts
X-Correlation-IDfrom incoming requests (or generates one) - Propagates correlation ID via ContextVar for downstream logging
- Logs request entry/exit with path, method, status, and duration
- Adds
X-Correlation-IDto response headers
Log format:
[MA:xyz] [corr_id] -> REST:GET /api/users {path="/api/users", method="GET"}
[MA:xyz] [corr_id] <- REST:GET /api/users {status=200, duration_ms=15}
from checktrace import checkpoint
@checkpoint("VB", "process_document")
async def process_document(doc_id: str, options: dict):
# Function entry/exit automatically logged
return {"processed": True}
@checkpoint("WK", "sync_operation")
def sync_operation(data: dict):
# Works with sync functions too
return process(data)Features:
- Works with both sync and async functions
- Logs function arguments (truncated for large values)
- Logs return value or exception
- Automatically redacts sensitive parameters (password, token, jwt, api_key, secret)
from checktrace import (
set_correlation_id,
get_correlation_id,
generate_correlation_id,
correlation_context,
)
# Set correlation ID for current async context
set_correlation_id("my-correlation-id")
# Get current correlation ID
corr_id = get_correlation_id()
# Generate new correlation ID
new_id = generate_correlation_id("ma") # Returns: "ma-a1b2c3d4"
# Use context manager for scoped correlation ID
async with correlation_context("scoped-id"):
# All traces in this block use "scoped-id"
await process_data()The CLI requires TRACEHUB_URL environment variable or --url option.
# List recent correlation IDs
checktrace list
checktrace list --limit 100 --format json
# Get all traces for a correlation ID
checktrace get <correlation_id>
checktrace get <correlation_id> --source BK --format json
# Stream traces in real-time
checktrace stream <correlation_id>
checktrace stream <correlation_id> --timeout 120Global options:
--url,-u: TraceHub URL (default:TRACEHUB_URLenv)--secret,-s: TraceHub secret (default:TRACEHUB_SECRETenv)
list command:
--limit,-l: Maximum number of correlations (default: 50)--format,-f: Output format:tableorjson(default: table)
get command:
--source,-S: Filter by source ID (e.g., BK, WK)--format,-f: Output format:table,json, orraw(default: table)
stream command:
--timeout,-t: Stream timeout in seconds (default: 60)
CheckTraceConfig- Configuration class with all settingsCheckTraceConfig.from_env()- Create config from environment variablesinit_tracing(config)- Initialize global tracing (call once at startup)get_config()- Get current configurationis_initialized()- Check if tracing is initialized
correlation_id- ContextVar for correlation IDset_correlation_id(id)- Set correlation ID for current contextget_correlation_id()- Get current correlation IDgenerate_correlation_id(prefix)- Generate new ID with prefixcorrelation_context(id)- Context manager for scoped correlation ID
CheckpointLogger- Logger class for checkpoint tracesget_checkpoint_logger(source_id)- Get logger for sourcecheckpoint_entry(layer, endpoint, data)- Log entry checkpointcheckpoint_exit(layer, endpoint, data)- Log exit checkpoint
@checkpoint(layer, operation)- Decorator for function tracing
TraceHubClient- Client for sending tracesTraceHubQueryClient- Client for querying tracesget_client()- Get global TraceHub clientsend_trace(entry)- Send trace entryTraceEntry- Trace entry data class
CheckpointMiddleware- FastAPI/Starlette middlewareCORRELATION_ID_HEADER- Header name (X-Correlation-ID)STARLETTE_AVAILABLE- Whether starlette is installed
CheckTraceError- Base exception for SDK errors
MIT