observability-edot-python-migrate 是做什么的?
将 Python 应用程序从经典的 Elastic APM Python 代理迁移到 EDOT Python 代理。适用于从 elastic-apm 切换至 elastic-opentelemetry 的场景。
概述
本指南将帮助你从 elastic-apm 库无缝迁移到 Elastic Distribution of OpenTelemetry (EDOT) Python 代理 (elastic-opentelemetry)。新代理基于 OpenTelemetry 标准,提供更强的可扩展性和与其他工具更好的互操作性。
前提条件
- Python 3.8 或更高版本
- 已安装
elastic-apm的现有项目 - 访问 Elastic Stack 部署(Elastic Cloud 或自托管)
迁移步骤
1. 更新依赖项
修改你的 requirements.txt、setup.py 或 pyproject.toml,移除 elastic-apm 并添加 elastic-opentelemetry。
# 移除旧代理
pip uninstall elastic-apm
# 安装 EDOT 代理
pip install elastic-opentelemetry[instrumentations]
2. 替换导入语句
在代码中找到所有对 elasticapm 的引用,并替换为对应的 OpenTelemetry 导入。
之前 (elastic-apm):
from elasticapm import Client
之后 (elastic-opentelemetry):
from opentelemetry.instrumentation.elastic import ElasticInstrumentor
from opentelemetry import trace
3. 更新初始化代码
将代理初始化代码从 elasticapm.Client() 更新为使用 OpenTelemetry 设置。
之前:
apm_client = elasticapm.Client({"SERVICE_NAME": "my-app", "SERVER_URL": "https://..."})
之后:
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
tracer_provider = TracerProvider()
exporter = OTLPSpanExporter(endpoint="https://...", headers={"Authorization": "Bearer ..."})
processor = BatchSpanProcessor(exporter)
tracer_provider.add_span_processor(processor)
trace.set_tracer_provider(tracer_provider)
4. 配置迁移
将以下配置从旧代理映射到新环境变量。
| 旧配置 (elastic-apm) | 新配置 (elastic-opentelemetry) |
|---|---|
SERVICE_NAME | OTEL_SERVICE_NAME |
SERVER_URL | OTEL_EXPORTER_OTLP_ENDPOINT |
SECRET_TOKEN | OTEL_EXPORTER_OTLP_HEADERS(格式:Authorization=Bearer <token>) |
ENVIRONMENT | OTEL_RESOURCE_ATTRIBUTES(如 deployment.environment=production) |
5. 处理中间件/装饰器
如果你的应用使用了 elasticapm.middleware 或 elasticapm.instrument(),相应替换为 OpenTelemetry 的自动检测。
Flask 应用示例
之前:
from elasticapm.contrib.flask import ElasticAPM
app = Flask(__name__)
apm = ElasticAPM(app, config={...})
之后:
from opentelemetry.instrumentation.flask import FlaskInstrumentor
app = Flask(__name__)
FlaskInstrumentor().instrument_app(app)
6. 自定义追踪
用 OpenTelemetry 的 API 替换 elasticapm.begin_transaction() 和 elasticapm.end_transaction()。
之前:
elasticapm.begin_transaction("my-transaction")
try:
# 业务逻辑
pass
finally:
elasticapm.end_transaction("my-transaction", "success")
之后:
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("my-span") as span:
span.set_attribute("key", "value")
# 业务逻辑
pass
验证迁移
- 启动应用并检查日志中是否有错误。
- 在 Elastic APM UI 中确认数据被正确摄取。
- 运行集成测试,确保所有追踪点正常工作。
回滚计划
如需回滚,请恢复依赖项、代码更改和配置,然后重新部署应用。