OpenTelemetry 日志(Logs)
介绍
OpenTelemetry(简称OTel)是一个开源的观测性框架,用于生成、收集和管理遥测数据(如日志、指标和追踪)。日志(Logs)是OpenTelemetry的三大信号类型之一,用于记录应用程序在运行过程中发生的事件和状态信息。它们对于调试、监控和审计应用程序的行为至关重要。
与传统的日志记录不同,OpenTelemetry日志提供了结构化的格式,并支持与其他信号类型(如追踪和指标)的关联,从而提供更全面的观测性。
日志的基本概念
日志是离散的事件记录,通常包含以下信息:
- 时间戳:事件发生的时间。
- 日志级别:如
DEBUG
、INFO
、WARN
、ERROR
等。 - 消息:描述事件的文本。
- 属性:键值对形式的附加上下文信息。
在OpenTelemetry中,日志可以与其他信号类型(如追踪)关联,从而提供更丰富的上下文信息。例如,一条错误日志可以与特定的请求追踪ID关联,帮助开发者快速定位问题。
OpenTelemetry 日志的结构
OpenTelemetry日志采用结构化格式,以下是一个典型的日志记录示例:
{
"timestamp": "2023-10-01T12:00:00Z",
"severity": "ERROR",
"body": "Failed to connect to database",
"attributes": {
"service.name": "auth-service",
"error.message": "Connection timeout",
"trace_id": "abc123",
"span_id": "def456"
}
}
备注
日志的 attributes
字段可以包含任意键值对,用于提供额外的上下文信息。trace_id
和 span_id
是可选字段,用于与追踪数据关联。
记录日志的代码示例
以下是一个使用OpenTelemetry SDK记录日志的Python示例:
from opentelemetry import trace
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import ConsoleLogExporter, SimpleLogRecordProcessor
import logging
# 设置日志记录器
logger_provider = LoggerProvider()
logger_provider.add_log_record_processor(SimpleLogRecordProcessor(ConsoleLogExporter()))
logging.getLogger().addHandler(LoggingHandler(logger_provider))
# 获取当前追踪上下文
tracer = trace.get_tracer(__name__)
ctx = trace.get_current_span().get_span_context()
# 记录日志
logging.error("Failed to connect to database", extra={
"attributes": {
"service.name": "auth-service",
"error.message": "Connection timeout",
"trace_id": hex(ctx.trace_id)[2:], # 转换为十六进制字符串
"span_id": hex(ctx.span_id)[2:],
}
})
输出:
{
"timestamp": "2023-10-01T12:00:00Z",
"severity": "ERROR",
"body": "Failed to connect to database",
"attributes": {
"service.name": "auth-service",
"error.message": "Connection timeout",
"trace_id": "abc123",
"span_id": "def456"
}
}
提示
在实际应用中,可以将日志导出到后端系统(如Loki、Elasticsearch或Fluentd),而不是仅打印到控制台。