structlog-python
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.
What this skill does
# structlog
## 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
```python
# 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
```python
# 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
```python
# 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 `contextvars` for 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)` not `log.info(f"Processed order {id}")`.
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.