Skip to content

Kiberos-ai/checktrace

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

checktrace

Python SDK for distributed tracing via TraceHub.

Features

  • 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
  • @checkpoint decorator for function tracing
  • CLI for querying traces

Installation

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/

Quick Start

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"}

Using Environment Variables

from checktrace import CheckTraceConfig, init_tracing

# Load configuration from environment
config = CheckTraceConfig.from_env()
init_tracing(config)

Environment Variables

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

FastAPI Middleware

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-ID from 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-ID to 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}

Checkpoint Decorator

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)

Correlation ID Context

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()

CLI Usage

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 120

CLI Options

Global options:

  • --url, -u: TraceHub URL (default: TRACEHUB_URL env)
  • --secret, -s: TraceHub secret (default: TRACEHUB_SECRET env)

list command:

  • --limit, -l: Maximum number of correlations (default: 50)
  • --format, -f: Output format: table or json (default: table)

get command:

  • --source, -S: Filter by source ID (e.g., BK, WK)
  • --format, -f: Output format: table, json, or raw (default: table)

stream command:

  • --timeout, -t: Stream timeout in seconds (default: 60)

API Reference

Configuration

  • CheckTraceConfig - Configuration class with all settings
  • CheckTraceConfig.from_env() - Create config from environment variables
  • init_tracing(config) - Initialize global tracing (call once at startup)
  • get_config() - Get current configuration
  • is_initialized() - Check if tracing is initialized

Context

  • correlation_id - ContextVar for correlation ID
  • set_correlation_id(id) - Set correlation ID for current context
  • get_correlation_id() - Get current correlation ID
  • generate_correlation_id(prefix) - Generate new ID with prefix
  • correlation_context(id) - Context manager for scoped correlation ID

Logging

  • CheckpointLogger - Logger class for checkpoint traces
  • get_checkpoint_logger(source_id) - Get logger for source
  • checkpoint_entry(layer, endpoint, data) - Log entry checkpoint
  • checkpoint_exit(layer, endpoint, data) - Log exit checkpoint

Decorator

  • @checkpoint(layer, operation) - Decorator for function tracing

Client

  • TraceHubClient - Client for sending traces
  • TraceHubQueryClient - Client for querying traces
  • get_client() - Get global TraceHub client
  • send_trace(entry) - Send trace entry
  • TraceEntry - Trace entry data class

Middleware

  • CheckpointMiddleware - FastAPI/Starlette middleware
  • CORRELATION_ID_HEADER - Header name (X-Correlation-ID)
  • STARLETTE_AVAILABLE - Whether starlette is installed

Exceptions

  • CheckTraceError - Base exception for SDK errors

License

MIT

About

CheckTrace - Python SDK for distributed tracing via TraceHub

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages