如何为Python应用添加监控和可观测性?

中等Python

答题要点

# Prometheus指标
from prometheus_client import Counter, Histogram, Gauge, start_http_server

# 定义指标
REQUEST_COUNT = Counter('request_total', 'Total requests', ['method', 'endpoint'])
REQUEST_LATENCY = Histogram('request_latency_seconds', 'Request latency',
                            ['endpoint'], buckets=[0.1, 0.5, 1.0, 5.0])
ACTIVE_CONNECTIONS = Gauge('active_connections', 'Active database connections')

# 使用指标
def handle_request(method, endpoint):
    REQUEST_COUNT.labels(method=method, endpoint=endpoint).inc()

    with REQUEST_LATENCY.labels(endpoint=endpoint).time():
        result = process_request()

    return result

# 启动metrics服务
start_http_server(8000)

# OpenTelemetry分布式追踪
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

# 配置追踪
provider = TracerProvider()
processor = BatchSpanProcessor(OTLPSpanExporter(endpoint="http://jaeger:4317"))
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

tracer = trace.get_tracer(__name__)

# 添加追踪
@tracer.start_as_current_span("process_data")
def process_data(data):
    current_span = trace.get_current_span()
    current_span.set_attribute("data.size", len(data))

    with tracer.start_as_current_span("transform"):
        transformed = transform(data)

    with tracer.start_as_current_span("save"):
        save(transformed)

# 结构化日志
import structlog

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

logger = structlog.get_logger()

def process_order(order_id: str):
    log = logger.bind(order_id=order_id)
    log.info("processing_started")

    try:
        result = do_process()
        log.info("processing_completed", result=result)
    except Exception as e:
        log.error("processing_failed", error=str(e))
        raise

# 健康检查
from fastapi import FastAPI
import asyncpg

app = FastAPI()

@app.get("/health")
async def health_check():
    checks = {}

    # 数据库检查
    try:
        await db_pool.fetchval('SELECT 1')
        checks['database'] = 'healthy'
    except Exception as e:
        checks['database'] = f'unhealthy: {e}'

    # Redis检查
    try:
        await redis_client.ping()
        checks['redis'] = 'healthy'
    except Exception as e:
        checks['redis'] = f'unhealthy: {e}'

    healthy = all(v == 'healthy' for v in checks.values())
    return {'status': 'healthy' if healthy else 'unhealthy', 'checks': checks}

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题