본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)41k · #6762

python-observability

하는 일

Python 프로그램 안에서 무슨 일이 일어나는지 이해하도록 돕습니다. 프로그램이 만드는 정보를 정리해서 오류를 찾거나 성능을 확인하기 쉽게 합니다.

사용하는 경우

  • ✓프로그램에 새 로그를 추가할 때.
  • ✓무언가가 얼마나 자주 일어나는지, 얼마나 오래 걸리는지 세고 싶을 때.
  • ✓여러 시스템을 거치는 요청을 추적해야 할 때.

스킬 링크

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-observability/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-observability/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“중요한 정보를 JSON 형식으로 로그에 남기도록 Python 프로그램을 어떻게 설정할 수 있나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

Python이 로그를 JSON 같은 구조화된 형식으로 만들도록 설정합니다. 이렇게 하면 컴퓨터가 정보를 쉽게 읽고 분석할 수 있어, 문제를 찾거나 프로그램 동작을 이해하는 데 도움이 됩니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Python Observability

Instrument Python applications with structured logs, metrics, and traces. When something breaks in production, you need to answer "what, where, and why" without deploying new code.

When to Use This Skill

  • Adding structured logging to applications
  • Implementing metrics collection with Prometheus
  • Setting up distributed tracing across services
  • Propagating correlation IDs through request chains
  • Debugging production issues
  • Building observability dashboards

Core Concepts

1. Structured Logging

Emit logs as JSON with consistent fields for production environments. Machine-readable logs enable powerful queries and alerts. For local development, consider human-readable formats.

2. The Four Golden Signals

Track latency, traffic, errors, and saturation for every service boundary.

3. Correlation IDs

Thread a unique ID through all logs and spans for a single request, enabling end-to-end tracing.

4. Bounded Cardinality

Keep metric label values bounded. Unbounded labels (like user IDs) explode storage costs.

Quick Start

import structlog

structlog.configure(
    processors=[
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.JSONRenderer(),
    ],
)

logger = structlog.get_logger()
logger.info("Request processed", user_id="123", duration_ms=45)

Fundamental Patterns

Pattern 1: Structured Logging with Structlog

Configure structlog for JSON output with consistent fields.

import logging
import structlog

def configure_logging(log_level: str = "INFO") -> None:
    """Configure structured logging for the application."""
    structlog.configure(
        processors=[
            structlog.contextvars.merge_contextvars,
            structlog.processors.add_log_level,
            structlog.processors.TimeStamper(fmt="iso"),
            structlog.processors.StackInfoRenderer(),
            structlog.processors.format_exc_info,
            structlog.processors.JSONRenderer(),
        ],
        wrapper_class=structlog.make_filtering_bound_logger(
            getattr(logging, log_level.upper())
        ),
        context_class=dict,
        logger_factory=structlog.PrintLoggerFactory(),
        cache_logger_on_first_use=True,
    )

# Initialize at application startup
configure_logging("INFO")
logger = structlog.get_logger()

Pattern 2: Consistent Log Fields

Every log entry should include standard fields for filtering and correlation.

import structlog
from contextvars import ContextVar

# Store correlation ID in context
correlation_id: ContextVar[str] = ContextVar("correlation_id", default="")

logger = structlog.get_logger()

def process_request(request: Request) -> Response:
    """Process request with structured logging."""
    logger.info(
        "Request received",
        correlation_id=correlation_id.get(),
        method=request.method,
        path=request.path,
        user_id=request.user_id,
    )

    try:
        result = handle_request(request)
        logger.info(
            "Request completed",
            correlation_id=correlation_id.get(),
            status_code=200,
            duration_ms=elapsed,
        )
        return result
    except Exception as e:
        logger.error(
            "Request failed",
            correlation_id=correlation_id.get(),
            error_type=type(e).__name__,
            error_message=str(e),
        )
        raise

Pattern 3: Semantic Log Levels

Use log levels consistently across the application.

Level Purpose Examples
DEBUG Development diagnostics Variable values, internal state
INFO Request lifecycle, operations Request start/end, job completion
WARNING Recoverable anomalies Retry attempts, fallback used
ERROR Failures needing attention Exceptions, service unavailable
# DEBUG: Detailed internal information
logger.debug("Cache lookup", key=cache_key, hit=cache_hit)

# INFO: Normal operational events
logger.info("Order created", order_id=order.id, total=order.total)

# WARNING: Abnormal but handled situations
logger.warning(
    "Rate limit approaching",
    current_rate=950,
    limit=1000,
    reset_seconds=30,
)

# ERROR: Failures requiring investigation
logger.error(
    "Payment processing failed",
    order_id=order.id,
    error=str(e),
    payment_provider="stripe",
)

…

자주 묻는 질문

'구조화된 로그'란 무엇인가요?

정해진 필드가 있는 일관된 형식(예: JSON)을 따르는 로그 메시지입니다. 컴퓨터가 검색하고 분석하기 쉽습니다.

'4대 골든 시그널'은 무엇인가요?

서비스를 모니터링하는 중요한 지표들입니다. 지연 시간(응답 시간), 트래픽(요청량), 오류(실패율), 포화도(자원 사용량)가 있습니다.

'상관 ID'란 무엇인가요?

특정 요청이 시스템의 여러 부분을 거치는 동안 따라가는 고유 식별자입니다. 요청의 전체 여정을 추적할 수 있게 합니다.

상세 정보

작성자의 원본 설명

Python observability patterns including structured logging, metrics, and distributed tracing. Use when adding logging, implementing metrics collection, setting up tracing, or debugging production systems.

repo: wshobson/agents

인기도

GitHub 스타
41k
순위
#6762
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬