structlog
structlog - structured logging library for Python with native JSON support, context binding, and processor pipeline. Integrates with FastAPI, Django, and standard logging module. USE WHEN: user mentions "structlog", "python structured logging", "context binding", asks about "JSON logging python", "fastapi logging", "django structured logging" DO NOT USE FOR: Standard Python logging - use `python-logging` instead, Node.js logging - use `pino` or `winston`, Java logging - use `slf4j` or `logback` instead
What this skill does
# structlog - Quick Reference
## When to Use This Skill
- Structured logging in Python
- Integration with JSON logging
- Context binding for request tracing
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `structlog` for comprehensive documentation.
## Basic Setup
```bash
pip install structlog
```
## Essential Patterns
### Basic Configuration
```python
import structlog
structlog.configure(
processors=[
structlog.stdlib.filter_by_level,
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.processors.UnicodeDecoder(),
structlog.processors.JSONRenderer()
],
wrapper_class=structlog.stdlib.BoundLogger,
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
cache_logger_on_first_use=True,
)
```
### Basic Usage
```python
import structlog
log = structlog.get_logger()
log.info("user_logged_in", user_id=123, ip="192.168.1.1")
log.warning("rate_limit_exceeded", endpoint="/api/users", count=100)
log.error("database_error", error="connection timeout", retry=3)
```
### Context Binding
```python
log = structlog.get_logger()
# Bind context for all subsequent logs
log = log.bind(request_id="abc-123", user_id=42)
log.info("processing_started") # Includes request_id and user_id
log.info("step_completed", step=1)
log.info("processing_finished")
# New context
log = log.new(request_id="xyz-789")
```
### FastAPI Integration
```python
from fastapi import FastAPI, Request
import structlog
app = FastAPI()
@app.middleware("http")
async def add_request_context(request: Request, call_next):
structlog.contextvars.clear_contextvars()
structlog.contextvars.bind_contextvars(
request_id=request.headers.get("X-Request-ID", str(uuid.uuid4())),
path=request.url.path,
)
return await call_next(request)
```
### Django Integration
```python
# settings.py
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"json": {
"()": structlog.stdlib.ProcessorFormatter,
"processor": structlog.processors.JSONRenderer(),
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "json",
},
},
"root": {
"handlers": ["console"],
"level": "INFO",
},
}
```
### Exception Logging
```python
try:
risky_operation()
except Exception:
log.exception("operation_failed", operation="risky")
# Automatically includes stack trace
```
## When NOT to Use This Skill
- **Simple scripts**: Standard logging module is sufficient for basic needs
- **Legacy codebases**: Migration effort may not be worth it for small projects
- **Text-only log requirements**: structlog is JSON-first, requires parsing
- **Non-Python projects**: Use language-appropriate logging frameworks
- **Applications without centralized logging**: Standard logging may be simpler
## Anti-Patterns
| Anti-Pattern | Why It's Bad | Solution |
|--------------|--------------|----------|
| Using ConsoleRenderer in production | Wastes CPU, not machine-parseable | Use JSONRenderer for production |
| Not clearing context variables | Leaks context across requests | Use `structlog.contextvars.clear_contextvars()` |
| Logging large objects | Serialization overhead | Log only necessary fields or IDs |
| Creating new logger per request | Performance overhead | Use `logger.bind()` to add context |
| Missing exception logging | Loses stack traces | Use `logger.exception()` in except blocks |
| Not configuring processors | Incomplete/inconsistent output | Configure full processor pipeline |
## Quick Troubleshooting
| Issue | Cause | Solution |
|-------|-------|----------|
| Plain text output instead of JSON | ConsoleRenderer configured | Change to `JSONRenderer()` in processors |
| Context not appearing in logs | Not using context binding | Use `logger.bind()` or `contextvars` |
| Performance issues | Too many processors | Remove unnecessary processors, use JSONRenderer |
| Missing timestamps | No TimeStamper processor | Add `TimeStamper(fmt='iso')` to processors |
| Logs not colorized in dev | Missing dev configuration | Use `ConsoleRenderer(colors=True)` for development |
| Context bleeding across requests | Not clearing contextvars | Clear context at request start with middleware |
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.