引言

在微服务架构和容器化部署成为主流的当下,系统的复杂性呈指数级增长。一个请求可能跨越数十个服务实例,传统的日志查看和单点监控已无法满足故障排查的需求。云原生可观测性(Observability)应运而生,它通过Metrics、Logs、Traces三大支柱,为复杂系统提供全方位的洞察能力。

本文将深入探讨云原生可观测性的核心概念、技术栈选型以及生产环境中的最佳实践,帮助团队构建强大的全链路监控体系。

一、可观测性的三大支柱

1.1 Metrics(指标)

Metrics是可量化的时序数据,用于描述系统的状态和性能。与Logs和Traces相比,Metrics具有存储成本低、查询速度快、易于聚合分析的特点。

核心指标类型:

| 指标类型 | 说明 | 示例 | |----------|------|------| | Counter | 单调递增的计数器 | 请求总数、错误数 | | Gauge | 可增可减的瞬时值 | CPU使用率、内存占用 | | Histogram | 采样观测值并分桶 | 请求延迟分布 | | Summary | 类似Histogram,但计算分位数 | P99延迟 |

# 使用Prometheus客户端定义指标
from prometheus_client import Counter, Histogram, Gauge, start_http_server

# 定义指标
request_count = Counter('http_requests_total', 'Total requests', ['method', 'endpoint', 'status'])
request_duration = Histogram('http_request_duration_seconds', 'Request duration', ['endpoint'])
active_connections = Gauge('active_connections', 'Number of active connections')

# 在应用中埋点
@app.get("/api/users")
async def get_users():
    start_time = time.time()
    try:
        users = await fetch_users()
        request_count.labels(method='GET', endpoint='/api/users', status='200').inc()
        return users
    except Exception as e:
        request_count.labels(method='GET', endpoint='/api/users', status='500').inc()
        raise
    finally:
        request_duration.labels(endpoint='/api/users').observe(time.time() - start_time)

1.2 Logs(日志)

日志记录了系统中发生的事件,包含详细的上下文信息。结构化日志是现代可观测性的基础。

日志级别规范:

import logging
import json
from datetime import datetime

class JSONFormatter(logging.Formatter):
    def format(self, record):
        log_data = {
            'timestamp': datetime.utcnow().isoformat(),
            'level': record.levelname,
            'logger': record.name,
            'message': record.getMessage(),
            'trace_id': getattr(record, 'trace_id', None),
            'span_id': getattr(record, 'span_id', None),
            'service': 'user-service',
            'host': socket.gethostname(),
        }
        if record.exc_info:
            log_data['exception'] = self.formatException(record.exc_info)
        return json.dumps(log_data, ensure_ascii=False)

# 配置结构化日志
logger = logging.getLogger('user-service')
handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())
logger.addHandler(handler)
logger.setLevel(logging.INFO)

# 使用示例
logger.info("用户登录成功", extra={
    'trace_id': 'abc123',
    'user_id': '10086',
    'login_method': 'oauth'
})

1.3 Traces(链路追踪)

链路追踪记录了一个请求在分布式系统中的完整调用路径,是排查跨服务问题的核心工具。

# 使用OpenTelemetry进行链路追踪
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProce

更多推荐