structlog-python
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "structlog-python" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-bbab09724276d7ad288af35787b29ca45b33b82693bc0f96d73849db599bc6a9. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Add structured logging to Python using structlog to produce typed/structured output, add context to logs, configure logging pipelines, or replace the standard logger to emit structured logs.
Introduction source: third_party · TerminalSkills · 1.0.0 Reference
SkillPi interpretation
- Software, accounts and paid services
- import structlog import logging import sys def setup_logging(environment: str = "development"): """Configure structlog for the application. Args: environment: 'development' for pretty output, 'production' for JSON """ shared_processors = [ structlog.contextvars.merge_contextvars, structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.processors.TimeStamper(fmt="iso"), structlog.processors.StackInfoRenderer(), structlog.processors.UnicodeDecoder(), ] if environment == "production": renderer = structlog.processors.JSONRenderer() else: renderer = structlog.dev.ConsoleRenderer(colors=True) structlog.configure( processors=[ *shared_processors, structlog.stdlib.ProcessorFormat
- Testing
- Not tested
Browse files
Frontmatter
name: structlog-python
description: >-
Add structured logging to Python with structlog. Use when a user asks to
implement structured logging, add context to Python logs, configure log
processing pipelines, or replace standard logging with typed output.
license: Apache-2.0
compatibility: 'Python 3.8+'
metadata:
author: terminal-skills
version: 1.0.0
category: devops
tags:
- structlog
- logging
- python
- structured
- observabilitystructlog
Overview
structlog adds structured, context-rich logging to Python. Instead of format strings, you pass key-value pairs that render as JSON (production) or colorized human-readable output (development). Bound loggers carry context across function calls.
Instructions
Step 1: Configuration
# logging_config.py — structlog setup
import structlog
import logging
import sys
def setup_logging(environment: str = "development"):
"""Configure structlog for the application.
Args:
environment: 'development' for pretty output, 'production' for JSON
"""
shared_processors = [
structlog.contextvars.merge_contextvars,
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.StackInfoRenderer(),
structlog.processors.UnicodeDecoder(),
]
if environment == "production":
renderer = structlog.processors.JSONRenderer()
else:
renderer = structlog.dev.ConsoleRenderer(colors=True)
structlog.configure(
processors=[
*shared_processors,
structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
],
logger_factory=structlog.stdlib.LoggerFactory(),
cache_logger_on_first_use=True,
)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(structlog.stdlib.ProcessorFormatter(
processors=[*shared_processors, renderer],
))
root_logger = logging.getLogger()
root_logger.addHandler(handler)
root_logger.setLevel(logging.INFO)
Step 2: Usage
# services/orders.py — Structured logging in business logic
import structlog
log = structlog.get_logger()
async def process_order(order_id: str, user_id: str):
# Bind context that carries through the entire function
log_ctx = log.bind(order_id=order_id, user_id=user_id)
log_ctx.info("Processing order")
items = await fetch_order_items(order_id)
log_ctx.info("Items fetched", item_count=len(items), total=sum(i.price for i in items))
try:
payment = await charge_payment(order_id)
log_ctx.info("Payment charged", payment_id=payment.id, amount=payment.amount)
except PaymentError as e:
log_ctx.error("Payment failed", error=str(e), error_code=e.code)
raise
log_ctx.info("Order completed", status="success")
Step 3: Request Context
# middleware.py — Add request context to all logs
import structlog
from uuid import uuid4
async def logging_middleware(request, call_next):
request_id = request.headers.get("x-request-id", str(uuid4()))
structlog.contextvars.clear_contextvars()
structlog.contextvars.bind_contextvars(
request_id=request_id,
method=request.method,
path=request.url.path,
user_id=getattr(request.state, "user_id", None),
)
log = structlog.get_logger()
log.info("Request started")
response = await call_next(request)
log.info("Request completed", status_code=response.status_code)
response.headers["x-request-id"] = request_id
return response
Guidelines
- Use
contextvarsfor request-scoped context — all logs in the request include requestId, userId. - JSON output in production, pretty console in development — same code, different renderer.
- Bind context early (
log.bind(...)) and it carries through all subsequent log calls. - structlog wraps stdlib logging — it works with existing libraries that use
logging. - Log events, not strings:
log.info("order_processed", order_id=id)notlog.info(f"Processed order {id}").
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 为Python添加结构化日志,具有广泛受众的实用能力
- 适用于开发、运维、可观测性等多个场景
- 提供完整的配置、使用、上下文管理示例
Highlights
- 触发词精准完整,覆盖多种变体
- 边界清晰,不会与其他Skill重叠
Highlights
- Phase/步骤清晰,有出口条件
- 含端到端示例,frontmatter完整
- 单文件≤500行,结构良好
Highlights
- 工具来源明确,参数正确
- 覆盖主要异常,不可逆操作有确认机制
- 代码示例完整,可直接使用
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
import structlog import logging import sys def setup_logging(environment: str = "development"): """Configure structlog for the application. Args: environment: 'development' for pretty output, 'production' for JSON """ shared_processors = [ structlog.contextvars.merge_contextvars, structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.processors.TimeStamper(fmt="iso"), structlog.processors.StackInfoRenderer(), structlog.processors.UnicodeDecoder(), ] if environment == "production": renderer = structlog.processors.JSONRenderer() else: renderer = structlog.dev.ConsoleRenderer(colors=True) structlog.configure( processors=[ *shared_processors, structlog.stdlib.ProcessorFormat
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.