structlog-python

为 Python 添加结构化日志支持,使用 structlog 实现类型化输出、在日志中添加上下文、配置日志处理管道或替换标准日志以生成结构化日志。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
7

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "structlog-python":https://skillpi.com/zh/skills/deepskill-bbab09724276d7ad288af35787b29ca45b33b82693bc0f96d73849db599bc6a9。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

为 Python 添加结构化日志支持,使用 structlog 实现类型化输出、在日志中添加上下文、配置日志处理管道或替换标准日志以生成结构化日志。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

软件、账号及付费要求
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
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
    - observability

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

# 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 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}").

当前收录版本

1.0.0

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 为Python添加结构化日志,具有广泛受众的实用能力
  • 适用于开发、运维、可观测性等多个场景
  • 提供完整的配置、使用、上下文管理示例
触发精准90/100

亮点

  • 触发词精准完整,覆盖多种变体
  • 边界清晰,不会与其他Skill重叠
结构规范90/100

亮点

  • Phase/步骤清晰,有出口条件
  • 含端到端示例,frontmatter完整
  • 单文件≤500行,结构良好
执行可靠85/100

亮点

  • 工具来源明确,参数正确
  • 覆盖主要异常,不可逆操作有确认机制
  • 代码示例完整,可直接使用
证据可验 (前四项均值)88/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

翻译待完成,请参阅来源文档。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。