tracekit-python-sdk
TraceKit Python SDK Setup
Auth Bootstrap
Do not tell the user to go sign up, log in separately, or manually create an API key before setup. First check for existing TraceKit auth. If ~/.tracekitconfig does not contain the production profile or TRACEKIT_API_KEY is missing, apply the tracekit-auth skill first. Use ./scripts/run-tracekit-auth.sh status to check, then guide the user through the TraceKit email verification flow with register and verify. That flow signs the user into an existing account for that email or creates the account automatically, then saves the returned credentials for the rest of the setup.
When To Use
Use this skill when the user asks to:
- Add TraceKit to a Python application
- Add observability or APM to a Python service
- Instrument a Django, Flask, or FastAPI app with distributed tracing
- Configure TraceKit API keys in a Python project
- Debug production Python services with live breakpoints
- Set up code monitoring in a Python app
Non-Negotiable Rules
- Never hardcode API keys in code. Always use
os.getenv("TRACEKIT_API_KEY")oros.environ["TRACEKIT_API_KEY"]. - Always call
tracekit.init()before creating the app - initialization must happen before framework setup so auto-instrumentation patches are applied. - Always include a verification step confirming traces appear in
https://app.tracekit.dev/traces. - Always enable code monitoring (
enable_code_monitoring=True) - it is TraceKit's differentiator.
Detection
Before applying this skill, detect the project type:
- Check for Python project files -
requirements.txt,pyproject.toml, orPipfileconfirms this is a Python project. - Detect framework by scanning dependencies or imports:
djangoin dependencies/imports => Django framework (use Django branch)flaskin dependencies/imports => Flask framework (use Flask branch)fastapiin dependencies/imports => FastAPI framework (use FastAPI branch)
- Only ask the user if multiple frameworks are detected or if no project file is found.
Step 1: Environment Setup
Set the TRACEKIT_API_KEY environment variable. This is the only required secret.
Add to your .env file or environment:
export TRACEKIT_API_KEY=ctxio_your_api_key_here
The OTLP endpoint is hardcoded in the SDK init - no need to configure it separately.
Where to get your API key:
- Log in to TraceKit
- Go to API Keys page
- Generate a new key (starts with
ctxio_)
Do not commit real API keys. Use .env files, deployment secret managers, or CI variables.
Step 2: Install SDK
pip install tracekit-apm
Framework-specific extras are available:
pip install tracekit-apm[flask] # For Flask
pip install tracekit-apm[django] # For Django
pip install tracekit-apm[fastapi] # For FastAPI
pip install tracekit-apm[all] # All frameworks
This installs the TraceKit Python SDK with built-in OpenTelemetry support, framework middleware, and code monitoring.
Step 3: Initialize TraceKit
Add initialization at the top of your application entry point, before creating the framework app:
import tracekit
import os
# Initialize TraceKit - MUST be before app creation
client = tracekit.init(
api_key=os.getenv("TRACEKIT_API_KEY"),
service_name="my-python-service",
endpoint="https://app.tracekit.dev/v1/traces",
enable_code_monitoring=True,
)
Key points:
service_nameshould match your service's logical name (e.g.,"api-gateway","user-service")enable_code_monitoring=Trueenables live breakpoints and snapshots in production- Call
tracekit.init()beforeFlask(__name__),FastAPI(), or Django'sMIDDLEWAREsetup
Step 4: Framework Integration
Choose the branch matching your framework. Apply one of the following.
Branch A: Flask
# app.py
from flask import Flask, request, jsonify
import tracekit
from tracekit.middleware.flask import init_flask_app
import os
# Initialize TraceKit (before app creation!)
client = tracekit.init(
api_key=os.getenv("TRACEKIT_API_KEY"),
service_name="my-flask-app",
endpoint="https://app.tracekit.dev/v1/traces",
enable_code_monitoring=True,
)
# Create Flask app
app = Flask(__name__)
# Add TraceKit middleware (auto-traces all routes!)
init_flask_app(app, client)
@app.route("/api/users/<int:user_id>")
def get_user(user_id):
return jsonify({"id": user_id, "name": "Alice"})
if __name__ == "__main__":
app.run(port=5000)
Order matters: tracekit.init() then Flask(__name__) then init_flask_app(app, client) then route definitions.
Branch B: Django
Add TraceKit initialization to your Django settings and middleware.
1. Initialize in settings.py:
# settings.py
import tracekit
import os
# Initialize TraceKit at Django startup
client = tracekit.init(
api_key=os.getenv("TRACEKIT_API_KEY"),
service_name="my-django-app",
endpoint="https://app.tracekit.dev/v1/traces",
enable_code_monitoring=True,
)
2. Add middleware to MIDDLEWARE:
# settings.py
MIDDLEWARE = [
'tracekit.middleware.django.TracekitDjangoMiddleware',
# ... other middleware (keep TraceKit first for complete request tracing)
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# ...
]
Order matters: Place TracekitDjangoMiddleware at the top of MIDDLEWARE to trace the full request lifecycle.
Branch C: FastAPI
# main.py
from fastapi import FastAPI
import tracekit
from tracekit.middleware.fastapi import init_fastapi_app
import os
# Initialize TraceKit (before app creation!)
client = tracekit.init(
api_key=os.getenv("TRACEKIT_API_KEY"),
service_name="my-fastapi-app",
endpoint="https://app.tracekit.dev/v1/traces",
enable_code_monitoring=True,
)
# Create FastAPI app
app = FastAPI()
# Add TraceKit middleware (auto-traces all routes!)
init_fastapi_app(app, client)
@app.get("/api/users/{user_id}")
async def get_user(user_id: int):
return {"id": user_id, "name": "Alice"}
Order matters: tracekit.init() then FastAPI() then init_fastapi_app(app, client) then route definitions.
Step 5: Error Capture
Capture errors explicitly in except blocks:
try:
result = some_operation()
except Exception as e:
tracekit.capture_exception(e)
# handle the error...
Step 5b: Snapshot Capture (Code Monitoring)
For programmatic snapshots, use the snapshot client directly - do not call through the SDK wrapper. The SDK uses stack inspection internally to identify the call site. Adding extra layers shifts the frame and causes snapshots to report the wrong source location.
Create a thin wrapper module (e.g., app/breakpoints.py):
_snapshot_client = None
def init(sdk):
"""Store the snapshot client. No-op when sdk is None."""
global _snapshot_client
if sdk is not None:
_snapshot_client = sdk.snapshot_client()
def capture(name: str, data: dict):
"""Fire a code monitoring snapshot. No-op when tracing is disabled."""
if _snapshot_client is None:
return
_snapshot_client.check_and_capture(name, data)
Initialize after SDK setup:
from app.breakpoints import init as init_breakpoints
init_breakpoints(sdk)
Use at call sites:
from app.breakpoints import capture
capture("payment-failed", {"order_id": order.id, "error": str(e)})
See the tracekit-code-monitoring skill for the full pattern across all languages.
Code Monitoring v25.0 Features
The latest SDK release adds these code monitoring capabilities (configured via the dashboard, no code changes needed):
- Logpoint mode -- capture expressions only without full variable snapshots, reducing overhead
- Per-breakpoint limits -- individual max captures (default: 100) and rate limits per breakpoint
- Dynamic stack traces -- configurable stack depth per breakpoint (1-50 frames)
- Idle auto-expiry -- breakpoints auto-expire after inactivity (default: 24h), pinnable to prevent expiry
- Conditional expressions -- server-side evaluated conditions with full operator support (
==,!=,>,<,&&,||)
These features are available when enable_code_monitoring is set to True. No SDK code changes required -- all configuration is done through the TraceKit dashboard.
For full details, see the tracekit-code-monitoring skill.
Step 6: Verification
After integrating, verify traces are flowing:
- Start your application with
TRACEKIT_API_KEYset in the environment. - Hit your endpoints 3-5 times - e.g.,
curl http://localhost:5000/api/users/1(Flask) orcurl http://localhost:8000/api/users/1(FastAPI/Django). - Open
https://app.tracekit.dev/traces. - Confirm new spans and your service name appear within 30-60 seconds.
If traces do not appear, see Troubleshooting below.
Troubleshooting
Traces not appearing in dashboard
- Check
TRACEKIT_API_KEY: Ensure the env var is set in the runtime environment. Print it:print(os.getenv("TRACEKIT_API_KEY")). - Check outbound access: Your service must reach
https://app.tracekit.dev/v1/traces. Verify with:curl -X POST https://app.tracekit.dev/v1/traces(expect 401 - means the endpoint is reachable). - Check init order:
tracekit.init()must be called before creating the Flask/FastAPI app or before Django processes the first request. If init happens too late, auto-instrumentation patches miss early imports.
Init order wrong
Symptoms: Server starts fine but no traces appear despite traffic.
Fix: Move tracekit.init() to the very top of your entry module, before importing route modules or creating the app object.
# DO: Init before app creation
tracekit.init()
app = Flask(__name__)
# DON'T: Import route modules before tracekit.init()
Missing environment variable
Symptoms: None API key warning on startup, or traces are rejected by the backend.
Fix: Ensure TRACEKIT_API_KEY is set in your .env file (loaded via python-dotenv), virtualenv activation script, Docker Compose, or deployment config.
Django middleware order
Symptoms: Partial traces or missing request context.
Fix: Place 'tracekit.middleware.django.TracekitDjangoMiddleware' as the first entry in MIDDLEWARE.
Service name collisions
Symptoms: Traces appear under the wrong service in the dashboard.
Fix: Use a unique service_name per deployed service. Avoid generic names like "app" or "server".
Next Steps
Once your Python app is traced, consider:
- Code Monitoring - Set live breakpoints and capture snapshots in production without redeploying (already enabled via
enable_code_monitoring=True) - Distributed Tracing - Connect traces across multiple services for full request visibility
- Frontend Observability - Add
@tracekit/browserto your frontend for end-to-end trace correlation
References
- Python SDK docs:
https://app.tracekit.dev/docs/languages/python - TraceKit docs root:
https://app.tracekit.dev/docs - Dashboard:
https://app.tracekit.dev - Quick start:
https://app.tracekit.dev/docs/quickstart
More from tracekit-dev/tracekit-for-ai
tracekit-code-monitoring
Enable live breakpoints and snapshots for production debugging with TraceKit Code Monitoring. Works with all backend SDKs. Use when the user asks to debug production code, set breakpoints, capture variable state, or enable code monitoring.
9tracekit-alerts
Set up alerting rules and notification channels in TraceKit for errors, performance degradation, and availability monitoring. Covers dashboard setup, API-based rules, Slack integration, and a starter kit of recommended alerts. Use when the user asks about alerts, notifications, error spikes, latency monitoring, or uptime.
8tracekit-browser-sdk
Sets up TraceKit APM in vanilla JavaScript/TypeScript applications for automatic error capture, breadcrumbs, performance monitoring, and distributed tracing. Use when the user has a plain HTML/JS, Web Components, or vanilla TypeScript project without a framework like React, Vue, or Angular.
8tracekit-react-sdk
Sets up TraceKit APM in React applications with error boundaries, component performance tracking, and distributed tracing. Use when the user asks to add TraceKit, add observability, instrument a React app, or configure APM in a React/TypeScript project.
8tracekit-nextjs-sdk
Sets up TraceKit APM in Next.js applications with multi-runtime support, error boundaries, and distributed tracing. Covers both App Router and Pages Router architectures.
8tracekit-session-replay
Set up TraceKit Session Replay to record and replay user sessions with linked distributed traces. Covers privacy settings, sampling rates, and GDPR compliance. Use when the user asks to record sessions, replay user interactions, or debug user-reported issues visually.
8