使用仪器库

在开发应用程序时,您可能会使用第三方库和框架来加速您的工作。如果您随后使用 OpenTelemetry instrumentation 您的应用程序,您可能希望避免花费额外的时间手动为您使用的第三方库和框架添加 traces、logs 和 metrics。

许多库和框架已经支持 OpenTelemetry,或者通过 OpenTelemetry instrumentation 进行支持,因此它们可以生成您可以导出到可观测性后端的 telemetry。

如果您正在 instrumentation 使用第三方库或框架的应用程序或服务,请遵循以下说明,了解如何为您的依赖项使用原生 instrumented 库和 instrumentation 库。

使用原生 instrumented 库

如果一个库默认包含 OpenTelemetry 支持,您可以通过在您的应用程序中添加和设置 OpenTelemetry SDK 来获取该库发出的 traces、metrics 和 logs。

该库可能需要一些额外的配置来进行 instrumentation。请参阅该库的文档以了解更多信息。

使用插装库

如果某个库没有内置 OpenTelemetry 支持,您可以使用Instrumentation 库来为该库或框架生成遥测数据。

例如,HTTPX 的 Instrumentation 库会根据 HTTP 请求自动创建Span

设置

您可以使用 pip 分别安装每个 Instrumentation 库。例如:

pip install opentelemetry-instrumentation-{instrumented-library}

在前面的示例中,{instrumented-library} 是 Instrumentation 的名称。

要安装开发版本,请克隆或 fork opentelemetry-python-contrib 仓库,然后运行以下命令进行可编辑安装:

pip install -e ./instrumentation/opentelemetry-instrumentation-{integration}

安装后,您需要初始化 Instrumentation 库。每个库通常有自己的初始化方式。

HTTPX 示例(带Instrumentation)

以下是如何对使用 httpx 库发出的 HTTP 请求进行 Instrumentation。

首先,使用 pip 安装 Instrumentation 库:

pip install opentelemetry-instrumentation-httpx

接下来,使用 instrumentor 自动跟踪所有客户端的请求:

import httpx
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor

url = "https://some.url/get"
HTTPXClientInstrumentor().instrument()

with httpx.Client() as client:
     response = client.get(url)

async with httpx.AsyncClient() as client:
     response = await client.get(url)

关闭 Instrumentation

如果需要,您可以使用 uninstrument_client 方法来取消特定客户端或所有客户端的 Instrumentation。例如:

import httpx
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor

HTTPXClientInstrumentor().instrument()
client = httpx.Client()

# Uninstrument a specific client
HTTPXClientInstrumentor.uninstrument_client(client)

# Uninstrument all clients
HTTPXClientInstrumentor().uninstrument()

可用检测库

OpenTelemetry 生成的 Instrumentation 库的完整列表可在 opentelemetry-python-contrib 仓库中找到。

您还可以在注册表中找到更多可用的 Instrumentation。

下一步

设置好 Instrumentation 库后,您可能想在代码中添加自己的Instrumentation,以收集自定义的遥测数据。

您可能还希望配置合适的 exporter,将您的遥测数据导出到一个或多个遥测后端。

您还可以查看Python 的零代码 Instrumentation