Community生产力与协作github.com

elastic/observability-edot-python-migrate

将 Python 应用从经典的 Elastic APM Python 代理迁移到 EDOT Python 代理。适用于从 elastic-apm 切换至 elastic-opentelemetry 的场景。

observability-edot-python-migrate 是什么?

该技能用于指导开发者将 Python 应用程序从经典的 Elastic APM Python 代理(elastic-apm)迁移至 EDOT Python 代理(elastic-opentelemetry)。它提供了详细的迁移步骤,包括依赖项更新、代理初始化代码调整、配置选项映射以及错误和指标收集方式的变更。主要支持 Python 平台,适用于任何使用 Elastic APM 进行监控的 Flask、Django、FastAPI 等 Web 应用。通过该技能,用户可以顺利过渡到基于 OpenTelemetry 的新代理,享受更丰富、更标准的可观测性功能。迁移过程涉及替换导入路径、调整初始化调用、更新配置密钥,并利用上下文传播和自动检测等机制,确保代码改动最小化。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/elastic/agent-skills/tree/main/skills/observability-edot-python-migrate

Installed? Explore more 生产力与协作 skills: steipete/gemini, steipete/gh-issues, steipete/skill-creator · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

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_NAMEOTEL_SERVICE_NAME
SERVER_URLOTEL_EXPORTER_OTLP_ENDPOINT
SECRET_TOKENOTEL_EXPORTER_OTLP_HEADERS(格式:Authorization=Bearer <token>)
ENVIRONMENTOTEL_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

验证迁移

  1. 启动应用并检查日志中是否有错误。
  2. 在 Elastic APM UI 中确认数据被正确摄取。
  3. 运行集成测试,确保所有追踪点正常工作。

回滚计划

如需回滚,请恢复依赖项、代码更改和配置,然后重新部署应用。

附加资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

elastic/cloud-access-management

Manage Elastic Cloud organization access: invite users, assign roles to Serverless projects, and create or revoke Cloud API keys. Use when granting, modifying, or auditing user access.

elastic/cloud-create-project

Creates Elastic Cloud Serverless projects (Elasticsearch, Observability, or Security) via the REST API, saves credentials to file, and bootstraps a scoped Elasticsearch API key. Use when creating a new serverless project, provisioning a search or observability environment, or spinning up a new Elastic Cloud project.

elastic/cloud-manage-project

Manages existing Elastic Cloud Serverless projects: list, get, update, delete, reset credentials, resume, and load saved credentials. Connects to existing projects by resolving endpoints and acquiring scoped Elasticsearch API keys. Use when performing day-2 operations on serverless projects, connecting to an existing project, loading or resetting project credentials, or looking up project details.

elastic/cloud-network-security

Manage Serverless network security (traffic filters): create, update, and delete IP filters and AWS PrivateLink VPC filters. Use when restricting network access or configuring private connectivity.

elastic/cloud-setup

Configures Elastic Cloud authentication and environment defaults. Use when setting up EC_API_KEY, configuring Cloud API access, or when another cloud skill requires credentials.

elastic/elasticsearch-audit

Enable, configure, and query Elasticsearch security audit logs. Use when the task involves audit logging setup, event filtering, or investigating security incidents like failed logins.

elastic/elasticsearch-authn

Authenticate to Elasticsearch using native, file-based, LDAP/AD, SAML, OIDC, Kerberos, JWT, or certificate realms. Use when connecting with credentials, choosing a realm, or managing API keys. Assumes the target realms are already configured.

elastic/elasticsearch-authz

Manage Elasticsearch RBAC: native users, roles, role mappings, document- and field-level security. Use when creating users or roles, assigning privileges, or mapping external realms like LDAP/SAML.

elastic/elasticsearch-esql

Execute ES|QL (Elasticsearch Query Language) queries, use when the user wants to query Elasticsearch data, analyze logs, aggregate metrics, explore data, or create charts and dashboards from ES|QL results.

elastic/elasticsearch-file-ingest

Ingest and transform data files (CSV/JSON/Parquet/Arrow IPC) into Elasticsearch with stream processing and custom transforms. Use when loading files or batch importing data — not for reindexing, general ingest pipeline design, or bulk API patterns.

elastic/elasticsearch-onboarding

Help developers new to Elasticsearch get from zero to a working search experience. Guide them through understanding their intent, mapping their data, and building a search experience with best practices baked in. Use this when the user shows intent to build search-related functionality, asks about Elasticsearch-related concepts for their use case, or expresses the need for help getting started with Elasticsearch.

elastic/elasticsearch-security-troubleshooting

Diagnose and resolve Elasticsearch security errors: 401/403 failures, TLS problems, expired API keys, role mapping mismatches, and Kibana login issues. Use when the user reports a security error.

elastic/kibana-agent-builder

Create and manage Agent Builder agents and custom tools in Kibana. Use when asked to create, update, delete, test, or inspect agents or tools in Agent Builder.

elastic/kibana-alerting-rules

Create and manage Kibana alerting rules via REST API or Terraform. Use when creating, updating, or managing rule lifecycle (enable, disable, mute, snooze) or rules-as-code workflows.

elastic/kibana-audit

Enable and configure Kibana audit logging for saved object access, logins, and space operations. Use when setting up Kibana audit, filtering events, or correlating Kibana and ES audit logs.

elastic/kibana-connectors

Create and manage Kibana connectors for Slack, PagerDuty, Jira, webhooks, and more via REST API or Terraform. Use when configuring third-party integrations or managing connectors as code.

elastic/kibana-dashboards

Create and manage Kibana Dashboards and visualizations. Use when you need to define dashboards and visualizations declaratively, version control them, or automate their deployment.

elastic/kibana-streams

List, inspect, enable, disable, and resync Kibana Streams via the REST API. Use when the user needs stream details, ingest/query settings, queries, significant events, or attachments.

elastic/kibana-vega

Create Vega and Vega-Lite visualizations with ES|QL data sources in Kibana. Use when building custom charts, dashboards, or programmatic panel layouts beyond standard Lens charts.

elastic/observability-edot-dotnet-instrument

Instrument a .NET application with the Elastic Distribution of OpenTelemetry (EDOT) .NET SDK for automatic tracing, metrics, and logs. Use when adding observability to a .NET service that has no existing APM agent.

相关技能