[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BWKXV9N4P9W22NMJB91ZW6":3,"skill-same:01M7BWKXV9N4P9W22NMJB91ZW6":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BWKXV9N4P9W22NMJB91ZW6","python-observability",null,"Python observability patterns including structured logging, metrics, and distributed tracing. Use when adding logging, implementing metrics collection, setting up tracing, or debugging production systems.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fpython-development\u002Fskills\u002Fpython-observability\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: python-observability\ndescription: Python observability patterns including structured logging, metrics, and distributed tracing. Use when adding logging, implementing metrics collection, setting up tracing, or debugging production systems.\n---\n\n# Python Observability\n\nInstrument 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.\n\n## When to Use This Skill\n\n- Adding structured logging to applications\n- Implementing metrics collection with Prometheus\n- Setting up distributed tracing across services\n- Propagating correlation IDs through request chains\n- Debugging production issues\n- Building observability dashboards\n\n## Core Concepts\n\n### 1. Structured Logging\n\nEmit logs as JSON with consistent fields for production environments. Machine-readable logs enable powerful queries and alerts. For local development, consider human-readable formats.\n\n### 2. The Four Golden Signals\n\nTrack latency, traffic, errors, and saturation for every service boundary.\n\n### 3. Correlation IDs\n\nThread a unique ID through all logs and spans for a single request, enabling end-to-end tracing.\n\n### 4. Bounded Cardinality\n\nKeep metric label values bounded. Unbounded labels (like user IDs) explode storage costs.\n\n## Quick Start\n\n```python\nimport structlog\n\nstructlog.configure(\n    processors=[\n        structlog.processors.TimeStamper(fmt=\"iso\"),\n        structlog.processors.JSONRenderer(),\n    ],\n)\n\nlogger = structlog.get_logger()\nlogger.info(\"Request processed\", user_id=\"123\", duration_ms=45)\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Structured Logging with Structlog\n\nConfigure structlog for JSON output with consistent fields.\n\n```python\nimport logging\nimport structlog\n\ndef configure_logging(log_level: str = \"INFO\") -> None:\n    \"\"\"Configure structured logging for the application.\"\"\"\n    structlog.configure(\n        processors=[\n            structlog.contextvars.merge_contextvars,\n            structlog.processors.add_log_level,\n            structlog.processors.TimeStamper(fmt=\"iso\"),\n            structlog.processors.StackInfoRenderer(),\n            structlog.processors.format_exc_info,\n            structlog.processors.JSONRenderer(),\n        ],\n        wrapper_class=structlog.make_filtering_bound_logger(\n            getattr(logging, log_level.upper())\n        ),\n        context_class=dict,\n        logger_factory=structlog.PrintLoggerFactory(),\n        cache_logger_on_first_use=True,\n    )\n\n# Initialize at application startup\nconfigure_logging(\"INFO\")\nlogger = structlog.get_logger()\n```\n\n### Pattern 2: Consistent Log Fields\n\nEvery log entry should include standard fields for filtering and correlation.\n\n```python\nimport structlog\nfrom contextvars import ContextVar\n\n# Store correlation ID in context\ncorrelation_id: ContextVar[str] = ContextVar(\"correlation_id\", default=\"\")\n\nlogger = structlog.get_logger()\n\ndef process_request(request: Request) -> Response:\n    \"\"\"Process request with structured logging.\"\"\"\n    logger.info(\n        \"Request received\",\n        correlation_id=correlation_id.get(),\n        method=request.method,\n        path=request.path,\n        user_id=request.user_id,\n    )\n\n    try:\n        result = handle_request(request)\n        logger.info(\n            \"Request completed\",\n            correlation_id=correlation_id.get(),\n            status_code=200,\n            duration_ms=elapsed,\n        )\n        return result\n    except Exception as e:\n        logger.error(\n            \"Request failed\",\n            correlation_id=correlation_id.get(),\n            error_type=type(e).__name__,\n            error_message=str(e),\n        )\n        raise\n```\n\n### Pattern 3: Semantic Log Levels\n\nUse log levels consistently across the application.\n\n| Level | Purpose | Examples |\n|-------|---------|----------|\n| `DEBUG` | Development diagnostics | Variable values, internal state |\n| `INFO` | Request lifecycle, operations | Request start\u002Fend, job completion |\n| `WARNING` | Recoverable anomalies | Retry attempts, fallback used |\n| `ERROR` | Failures needing attention | Exceptions, service unavailable |\n\n```python\n# DEBUG: Detailed internal information\nlogger.debug(\"Cache lookup\", key=cache_key, hit=cache_hit)\n\n# INFO: Normal operational events\nlogger.info(\"Order created\", order_id=order.id, total=order.total)\n\n# WARNING: Abnormal but handled situations\nlogger.warning(\n    \"Rate limit approaching\",\n    current_rate=950,\n    limit=1000,\n    reset_seconds=30,\n)\n\n# ERROR: Failures requiring investigation\nlogger.error(\n    \"Payment processing failed\",\n    order_id=order.id,\n    error=str(e),\n    payment_provider=\"stripe\",\n)\n```\n\nNever log expected behavior at `ERROR`. A user entering a wrong password is `INFO`, not `ERROR`.\n\n### Pattern 4: Correlation ID Propagation\n\nGenerate a unique ID at ingress and thread it through all operations.\n\n```python\nfrom contextvars import ContextVar\nimport uuid\nimport structlog\n\ncorrelation_id: ContextVar[str] = ContextVar(\"correlation_id\", default=\"\")\n\ndef set_correlation_id(cid: str | None = None) -> str:\n    \"\"\"Set correlation ID for current context.\"\"\"\n    cid = cid or str(uuid.uuid4())\n    correlation_id.set(cid)\n    structlog.contextvars.bind_contextvars(correlation_id=cid)\n    return cid\n\n# FastAPI middleware example\nfrom fastapi import Request\n\nasync def correlation_middleware(request: Request, call_next):\n    \"\"\"Middleware to set and propagate correlation ID.\"\"\"\n    # Use incoming header or generate new\n    cid = request.headers.get(\"X-Correlation-ID\") or str(uuid.uuid4())\n    set_correlation_id(cid)\n\n    response = await call_next(request)\n    response.headers[\"X-Correlation-ID\"] = cid\n    return response\n```\n\nPropagate to outbound requests:\n\n```python\nimport httpx\n\nasync def call_downstream_service(endpoint: str, data: dict) -> dict:\n    \"\"\"Call downstream service with correlation ID.\"\"\"\n    async with httpx.AsyncClient() as client:\n        response = await client.post(\n            endpoint,\n            json=data,\n            headers={\"X-Correlation-ID\": correlation_id.get()},\n        )\n        return response.json()\n```\n\n## Advanced Patterns\n\n### Pattern 5: The Four Golden Signals with Prometheus\n\nTrack these metrics for every service boundary:\n\n```python\nfrom prometheus_client import Counter, Histogram, Gauge\n\n# Latency: How long requests take\nREQUEST_LATENCY = Histogram(\n    \"http_request_duration_seconds\",\n    \"Request latency in seconds\",\n    [\"method\", \"endpoint\", \"status\"],\n    buckets=[0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],\n)\n\n# Traffic: Request rate\nREQUEST_COUNT = Counter(\n    \"http_requests_total\",\n    \"Total HTTP requests\",\n    [\"method\", \"endpoint\", \"status\"],\n)\n\n# Errors: Error rate\nERROR_COUNT = Counter(\n    \"http_errors_total\",\n    \"Total HTTP errors\",\n    [\"method\", \"endpoint\", \"error_type\"],\n)\n\n# Saturation: Resource utilization\nDB_POOL_USAGE = Gauge(\n    \"db_connection_pool_used\",\n    \"Number of database connections in use\",\n)\n```\n\nInstrument your endpoints:\n\n```python\nimport time\nfrom functools import wraps\n\ndef track_request(func):\n    \"\"\"Decorator to track request metrics.\"\"\"\n    @wraps(func)\n    async def wrapper(request: Request, *args, **kwargs):\n        method = request.method\n        endpoint = request.url.path\n        start = time.perf_counter()\n\n        try:\n            response = await func(request, *args, **kwargs)\n            status = str(response.status_code)\n            return response\n        except Exception as e:\n            status = \"500\"\n            ERROR_COUNT.labels(\n                method=method,\n                endpoint=endpoint,\n                error_type=type(e).__name__,\n            ).inc()\n            raise\n        finally:\n            duration = time.perf_counter() - start\n            REQUEST_COUNT.labels(method=method, endpoint=endpoint, status=status).inc()\n            REQUEST_LATENCY.labels(method=method, endpoint=endpoint, status=status).observe(duration)\n\n    return wrapper\n```\n\n### Pattern 6: Bounded Cardinality\n\nAvoid labels with unbounded values to prevent metric explosion.\n\n```python\n# BAD: User ID has potentially millions of values\nREQUEST_COUNT.labels(method=\"GET\", user_id=user.id)  # Don't do this!\n\n# GOOD: Bounded values only\nREQUEST_COUNT.labels(method=\"GET\", endpoint=\"\u002Fusers\", status=\"200\")\n\n# If you need per-user metrics, use a different approach:\n# - Log the user_id and query logs\n# - Use a separate analytics system\n# - Bucket users by type\u002Ftier\nREQUEST_COUNT.labels(\n    method=\"GET\",\n    endpoint=\"\u002Fusers\",\n    user_tier=\"premium\",  # Bounded set of values\n)\n```\n\n### Pattern 7: Timed Operations with Context Manager\n\nCreate a reusable timing context manager for operations.\n\n```python\nfrom contextlib import contextmanager\nimport time\nimport structlog\n\nlogger = structlog.get_logger()\n\n@contextmanager\ndef timed_operation(name: str, **extra_fields):\n    \"\"\"Context manager for timing and logging operations.\"\"\"\n    start = time.perf_counter()\n    logger.debug(\"Operation started\", operation=name, **extra_fields)\n\n    try:\n        yield\n    except Exception as e:\n        elapsed_ms = (time.perf_counter() - start) * 1000\n        logger.error(\n            \"Operation failed\",\n            operation=name,\n            duration_ms=round(elapsed_ms, 2),\n            error=str(e),\n            **extra_fields,\n        )\n        raise\n    else:\n        elapsed_ms = (time.perf_counter() - start) * 1000\n        logger.info(\n            \"Operation completed\",\n            operation=name,\n            duration_ms=round(elapsed_ms, 2),\n            **extra_fields,\n        )\n\n# Usage\nwith timed_operation(\"fetch_user_orders\", user_id=user.id):\n    orders = await order_repository.get_by_user(user.id)\n```\n\n### Pattern 8: OpenTelemetry Tracing\n\nSet up distributed tracing with OpenTelemetry.\n\n**Note:** OpenTelemetry is actively evolving. Check the [official Python documentation](https:\u002F\u002Fopentelemetry.io\u002Fdocs\u002Flanguages\u002Fpython\u002F) for the latest API patterns and best practices.\n\n```python\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import BatchSpanProcessor\nfrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter\n\ndef configure_tracing(service_name: str, otlp_endpoint: str) -> None:\n    \"\"\"Configure OpenTelemetry tracing.\"\"\"\n    provider = TracerProvider()\n    processor = BatchSpanProcessor(OTLPSpanExporter(endpoint=otlp_endpoint))\n    provider.add_span_processor(processor)\n    trace.set_tracer_provider(provider)\n\ntracer = trace.get_tracer(__name__)\n\nasync def process_order(order_id: str) -> Order:\n    \"\"\"Process order with tracing.\"\"\"\n    with tracer.start_as_current_span(\"process_order\") as span:\n        span.set_attribute(\"order.id\", order_id)\n\n        with tracer.start_as_current_span(\"validate_order\"):\n            validate_order(order_id)\n\n        with tracer.start_as_current_span(\"charge_payment\"):\n            charge_payment(order_id)\n\n        with tracer.start_as_current_span(\"send_confirmation\"):\n            send_confirmation(order_id)\n\n        return order\n```\n\n## Best Practices Summary\n\n1. **Use structured logging** - JSON logs with consistent fields\n2. **Propagate correlation IDs** - Thread through all requests and logs\n3. **Track the four golden signals** - Latency, traffic, errors, saturation\n4. **Bound label cardinality** - Never use unbounded values as metric labels\n5. **Log at appropriate levels** - Don't cry wolf with ERROR\n6. **Include context** - User ID, request ID, operation name in logs\n7. **Use context managers** - Consistent timing and error handling\n8. **Separate concerns** - Observability code shouldn't pollute business logic\n9. **Test your observability** - Verify logs and metrics in integration tests\n10. **Set up alerts** - Metrics are useless without alerting\n","# Python Observability\n\nInstrument 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.\n\n## When to Use This Skill\n\n- Adding structured logging to applications\n- Implementing metrics collection with Prometheus\n- Setting up distributed tracing across services\n- Propagating correlation IDs through request chains\n- Debugging production issues\n- Building observability dashboards\n\n## Core Concepts\n\n### 1. Structured Logging\n\nEmit logs as JSON with consistent fields for production environments. Machine-readable logs enable powerful queries and alerts. For local development, consider human-readable formats.\n\n### 2. The Four Golden Signals\n\nTrack latency, traffic, errors, and saturation for every service boundary.\n\n### 3. Correlation IDs\n\nThread a unique ID through all logs and spans for a single request, enabling end-to-end tracing.\n\n### 4. Bounded Cardinality\n\nKeep metric label values bounded. Unbounded labels (like user IDs) explode storage costs.\n\n## Quick Start\n\n```python\nimport structlog\n\nstructlog.configure(\n    processors=[\n        structlog.processors.TimeStamper(fmt=\"iso\"),\n        structlog.processors.JSONRenderer(),\n    ],\n)\n\nlogger = structlog.get_logger()\nlogger.info(\"Request processed\", user_id=\"123\", duration_ms=45)\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Structured Logging with Structlog\n\nConfigure structlog for JSON output with consistent fields.\n\n```python\nimport logging\nimport structlog\n\ndef configure_logging(log_level: str = \"INFO\") -> None:\n    \"\"\"Configure structured logging for the application.\"\"\"\n    structlog.configure(\n        processors=[\n            structlog.contextvars.merge_contextvars,\n            structlog.processors.add_log_level,\n            structlog.processors.TimeStamper(fmt=\"iso\"),\n            structlog.processors.StackInfoRenderer(),\n            structlog.processors.format_exc_info,\n            structlog.processors.JSONRenderer(),\n        ],\n        wrapper_class=structlog.make_filtering_bound_logger(\n            getattr(logging, log_level.upper())\n        ),\n        context_class=dict,\n        logger_factory=structlog.PrintLoggerFactory(),\n        cache_logger_on_first_use=True,\n    )\n\n# Initialize at application startup\nconfigure_logging(\"INFO\")\nlogger = structlog.get_logger()\n```\n\n### Pattern 2: Consistent Log Fields\n\nEvery log entry should include standard fields for filtering and correlation.\n\n```python\nimport structlog\nfrom contextvars import ContextVar\n\n# Store correlation ID in context\ncorrelation_id: ContextVar[str] = ContextVar(\"correlation_id\", default=\"\")\n\nlogger = structlog.get_logger()\n\ndef process_request(request: Request) -> Response:\n    \"\"\"Process request with structured logging.\"\"\"\n    logger.info(\n        \"Request received\",\n        correlation_id=correlation_id.get(),\n        method=request.method,\n        path=request.path,\n        user_id=request.user_id,\n    )\n\n    try:\n        result = handle_request(request)\n        logger.info(\n            \"Request completed\",\n            correlation_id=correlation_id.get(),\n            status_code=200,\n            duration_ms=elapsed,\n        )\n        return result\n    except Exception as e:\n        logger.error(\n            \"Request failed\",\n            correlation_id=correlation_id.get(),\n            error_type=type(e).__name__,\n            error_message=str(e),\n        )\n        raise\n```\n\n### Pattern 3: Semantic Log Levels\n\nUse log levels consistently across the application.\n\n| Level | Purpose | Examples |\n|-------|---------|----------|\n| `DEBUG` | Development diagnostics | Variable values, internal state |\n| `INFO` | Request lifecycle, operations | Request start\u002Fend, job completion |\n| `WARNING` | Recoverable anomalies | Retry attempts, fallback used |\n| `ERROR` | Failures needing attention | Exceptions, service unavailable |\n\n```python\n# DEBUG: Detailed internal information\nlogger.debug(\"Cache lookup\", key=cache_key, hit=cache_hit)\n\n# INFO: Normal operational events\nlogger.info(\"Order created\", order_id=order.id, total=order.total)\n\n# WARNING: Abnormal but handled situations\nlogger.warning(\n    \"Rate limit approaching\",\n    current_rate=950,\n    limit=1000,\n    reset_seconds=30,\n)\n\n# ERROR: Failures requiring investigation\nlogger.error(\n    \"Payment processing failed\",\n    order_id=order.id,\n    error=str(e),\n    payment_provider=\"stripe\",\n)\n```\n\nNever log expected behavior at `ERROR`. A user entering a wrong password is `INFO`, not `ERROR`.\n\n### Pattern 4: Correlation ID Propagation\n\nGenerate a unique ID at ingress and thread it through all operations.\n\n```python\nfrom contextvars import ContextVar\nimport uuid\nimport structlog\n\ncorrelation_id: ContextVar[str] = ContextVar(\"correlation_id\", default=\"\")\n\ndef set_correlation_id(cid: str | None = None) -> str:\n    \"\"\"Set correlation ID for current context.\"\"\"\n    cid = cid or str(uuid.uuid4())\n    correlation_id.set(cid)\n    structlog.contextvars.bind_contextvars(correlation_id=cid)\n    return cid\n\n# FastAPI middleware example\nfrom fastapi import Request\n\nasync def correlation_middleware(request: Request, call_next):\n    \"\"\"Middleware to set and propagate correlation ID.\"\"\"\n    # Use incoming header or generate new\n    cid = request.headers.get(\"X-Correlation-ID\") or str(uuid.uuid4())\n    set_correlation_id(cid)\n\n    response = await call_next(request)\n    response.headers[\"X-Correlation-ID\"] = cid\n    return response\n```\n\nPropagate to outbound requests:\n\n```python\nimport httpx\n\nasync def call_downstream_service(endpoint: str, data: dict) -> dict:\n    \"\"\"Call downstream service with correlation ID.\"\"\"\n    async with httpx.AsyncClient() as client:\n        response = await client.post(\n            endpoint,\n            json=data,\n            headers={\"X-Correlation-ID\": correlation_id.get()},\n        )\n        return response.json()\n```\n\n## Advanced Patterns\n\n### Pattern 5: The Four Golden Signals with Prometheus\n\nTrack these metrics for every service boundary:\n\n```python\nfrom prometheus_client import Counter, Histogram, Gauge\n\n# Latency: How long requests take\nREQUEST_LATENCY = Histogram(\n    \"http_request_duration_seconds\",\n    \"Request latency in seconds\",\n    [\"method\", \"endpoint\", \"status\"],\n    buckets=[0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],\n)\n\n# Traffic: Request rate\nREQUEST_COUNT = Counter(\n    \"http_requests_total\",\n    \"Total HTTP requests\",\n    [\"method\", \"endpoint\", \"status\"],\n)\n\n# Errors: Error rate\nERROR_COUNT = Counter(\n    \"http_errors_total\",\n    \"Total HTTP errors\",\n    [\"method\", \"endpoint\", \"error_type\"],\n)\n\n# Saturation: Resource utilization\nDB_POOL_USAGE = Gauge(\n    \"db_connection_pool_used\",\n    \"Number of database connections in use\",\n)\n```\n\nInstrument your endpoints:\n\n```python\nimport time\nfrom functools import wraps\n\ndef track_request(func):\n    \"\"\"Decorator to track request metrics.\"\"\"\n    @wraps(func)\n    async def wrapper(request: Request, *args, **kwargs):\n        method = request.method\n        endpoint = request.url.path\n        start = time.perf_counter()\n\n        try:\n            response = await func(request, *args, **kwargs)\n            status = str(response.status_code)\n            return response\n        except Exception as e:\n            status = \"500\"\n            ERROR_COUNT.labels(\n                method=method,\n                endpoint=endpoint,\n                error_type=type(e).__name__,\n            ).inc()\n            raise\n        finally:\n            duration = time.perf_counter() - start\n            REQUEST_COUNT.labels(method=method, endpoint=endpoint, status=status).inc()\n            REQUEST_LATENCY.labels(method=method, endpoint=endpoint, status=status).observe(duration)\n\n    return wrapper\n```\n\n### Pattern 6: Bounded Cardinality\n\nAvoid labels with unbounded values to prevent metric explosion.\n\n```python\n# BAD: User ID has potentially millions of values\nREQUEST_COUNT.labels(method=\"GET\", user_id=user.id)  # Don't do this!\n\n# GOOD: Bounded values only\nREQUEST_COUNT.labels(method=\"GET\", endpoint=\"\u002Fusers\", status=\"200\")\n\n# If you need per-user metrics, use a different approach:\n# - Log the user_id and query logs\n# - Use a separate analytics system\n# - Bucket users by type\u002Ftier\nREQUEST_COUNT.labels(\n    method=\"GET\",\n    endpoint=\"\u002Fusers\",\n    user_tier=\"premium\",  # Bounded set of values\n)\n```\n\n### Pattern 7: Timed Operations with Context Manager\n\nCreate a reusable timing context manager for operations.\n\n```python\nfrom contextlib import contextmanager\nimport time\nimport structlog\n\nlogger = structlog.get_logger()\n\n@contextmanager\ndef timed_operation(name: str, **extra_fields):\n    \"\"\"Context manager for timing and logging operations.\"\"\"\n    start = time.perf_counter()\n    logger.debug(\"Operation started\", operation=name, **extra_fields)\n\n    try:\n        yield\n    except Exception as e:\n        elapsed_ms = (time.perf_counter() - start) * 1000\n        logger.error(\n            \"Operation failed\",\n            operation=name,\n            duration_ms=round(elapsed_ms, 2),\n            error=str(e),\n            **extra_fields,\n        )\n        raise\n    else:\n        elapsed_ms = (time.perf_counter() - start) * 1000\n        logger.info(\n            \"Operation completed\",\n            operation=name,\n            duration_ms=round(elapsed_ms, 2),\n            **extra_fields,\n        )\n\n# Usage\nwith timed_operation(\"fetch_user_orders\", user_id=user.id):\n    orders = await order_repository.get_by_user(user.id)\n```\n\n### Pattern 8: OpenTelemetry Tracing\n\nSet up distributed tracing with OpenTelemetry.\n\n**Note:** OpenTelemetry is actively evolving. Check the [official Python documentation](https:\u002F\u002Fopentelemetry.io\u002Fdocs\u002Flanguages\u002Fpython\u002F) for the latest API patterns and best practices.\n\n```python\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import BatchSpanProcessor\nfrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter\n\ndef configure_tracing(service_name: str, otlp_endpoint: str) -> None:\n    \"\"\"Configure OpenTelemetry tracing.\"\"\"\n    provider = TracerProvider()\n    processor = BatchSpanProcessor(OTLPSpanExporter(endpoint=otlp_endpoint))\n    provider.add_span_processor(processor)\n    trace.set_tracer_provider(provider)\n\ntracer = trace.get_tracer(__name__)\n\nasync def process_order(order_id: str) -> Order:\n    \"\"\"Process order with tracing.\"\"\"\n    with tracer.start_as_current_span(\"process_order\") as span:\n        span.set_attribute(\"order.id\", order_id)\n\n        with tracer.start_as_current_span(\"validate_order\"):\n            validate_order(order_id)\n\n        with tracer.start_as_current_span(\"charge_payment\"):\n            charge_payment(order_id)\n\n        with tracer.start_as_current_span(\"send_confirmation\"):\n            send_confirmation(order_id)\n\n        return order\n```\n\n## Best Practices Summary\n\n1. **Use structured logging** - JSON logs with consistent fields\n2. **Propagate correlation IDs** - Thread through all requests and logs\n3. **Track the four golden signals** - Latency, traffic, errors, saturation\n4. **Bound label cardinality** - Never use unbounded values as metric labels\n5. **Log at appropriate levels** - Don't cry wolf with ERROR\n6. **Include context** - User ID, request ID, operation name in logs\n7. **Use context managers** - Consistent timing and error handling\n8. **Separate concerns** - Observability code shouldn't pollute business logic\n9. **Test your observability** - Verify logs and metrics in integration tests\n10. **Set up alerts** - Metrics are useless without alerting\n",{"name":5,"description":7},"main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fpython-development\u002Fskills\u002Fpython-observability",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill python-observability",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill python-observability",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill python-observability","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fpython-development\u002Fskills\u002Fpython-observability\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]