本文档介绍了如何配置 OpenTelemetry SDK 将跟踪记录数据进程内导出到您的 Google Cloud 项目。Java、Go、Python 和 Node.js 示例展示了在使用手动插桩时,如何配置 SDK 以将跟踪记录数据发送到 Telemetry (OTLP) API。对于每种语言,该页面都提供了相关信息,说明如何使用 OTLP 导出器通过支持的导出协议发送跟踪记录数据。
本页面中介绍的插桩仅适用于轨迹数据。它不会向您的 Google Cloud 项目发送日志或指标数据。
如果您的应用依赖于 OpenTelemetry 收集器将跟踪记录数据发送到您的 Google Cloud 项目,则本文档不适用:
- 如需查看插桩示例,请参阅基于收集器的插桩示例。
- 如需了解收集器,请参阅 Google 构建的 OpenTelemetry 收集器。
为什么应进行迁移
OpenTelemetry SDK 会以通常与 OpenTelemetry OTLP 协议定义的 proto 文件一致的格式生成日志、指标和跟踪记录数据。不过,在存储之前,字段可能会从 OpenTelemetry 特定的数据类型转换为 JSON 数据类型。
当应用使用 Google Cloud 导出器将这些数据导出到 Google Cloud 项目时,该导出器会执行以下步骤:
- 将记录的数据从 OTLP 格式转换为由 Cloud Logging API、Cloud Monitoring API 或 Cloud Trace API 定义的专有格式。
- 将转换后的数据发送到相应的 API,随后存储在您的 Google Cloud 项目中。
对于跟踪记录数据,我们建议您迁移应用以使用 Telemetry (OTLP) API 来导出数据,因为这种导出不需要进行数据转换。数据转换可能会导致部分数据丢失。例如,专有格式对某些字段的限制可能较低,或者某些 OTLP 字段可能无法映射到专有格式中的字段。
可用的示例
本页中提及的示例应用可在 GitHub 中找到。 大多数应用都配置为使用 gRPC 导出轨迹数据,这意味着它们通过 HTTP/2 连接使用 gRPC 线格式的 protobuf 编码数据。我们还为配置为通过 HTTP 连接将轨迹数据导出为 protobuf 编码数据的应用提供了示例代码:
-
示例应用配置为通过 HTTP 连接以 protobuf 编码的数据格式导出轨迹。 如果您偏好使用 gRPC,则此示例中的插桩适用。不过,您需要修改自动配置模块使用的系统属性。示例应用指定了
http/protobuf导出工具。如需使用 gRPC,请将此设置更改为grpc。我们建议您的 Java 应用(例如示例应用)使用 OpenTelemetry SDK 自动配置模块来配置 SDK。
使用 gRPC 的 Go 应用和使用 HTTP 的 Go 应用
有两个 Go 代码库。在一个代码库中,示例应用使用 gRPC。另一个代码库中的示例通过 HTTP 连接使用 protobuf 编码的数据。
-
此代码库包含两个示例,一个用于 gRPC,另一个通过 HTTP 连接使用 protobuf 编码的数据。
-
此代码库包含两个示例,一个用于 gRPC,另一个通过 HTTP 连接使用 protobuf 编码的数据。
准备工作
在迁移应用以将跟踪记录数据发送到 OTLP 端点之前,请启用 Telemetry API 并确保您已被授予所需的 Identity and Access Management (IAM) 角色。您可能还需要向服务账号授予 IAM 角色。
启用结算功能和 Telemetry API
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Telemetry, Cloud Logging, Cloud Monitoring, and Cloud Trace APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles. -
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Telemetry, Cloud Logging, Cloud Monitoring, and Cloud Trace APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles. 向应用使用的服务账号授予以下 IAM 角色:
- Cloud Telemetry Traces Writer (
roles/telemetry.tracesWriter) - Logs Writer (
roles/logging.logWriter) | - Monitoring Metric Writer (
roles/monitoring.metricWriter)
如需了解应用默认凭证 (ADC),请参阅应用默认凭证的工作原理和为本地开发环境设置应用默认凭证 (ADC)。
- Cloud Telemetry Traces Writer (
-
如需获得查看日志、指标和跟踪记录数据所需的权限,请让管理员为您授予项目的以下 IAM 角色:
-
Logs Viewer (
roles/logging.viewer) -
Monitoring Viewer (
roles/monitoring.viewer) -
Cloud Trace User (
roles/cloudtrace.user)
如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。
-
Logs Viewer (
添加以下 import 语句:
import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;更新应用代码以使用 OpenTelemetry SDK 自动配置模块来配置 SDK:
public static void main(String[] args) { // Configure the OpenTelemetry pipeline with Auto configuration openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk(); ... }配置自动配置模块在运行时使用的系统属性。该模块使用这些属性来引导 SDK。您还可以使用环境变量代替系统属性。如需了解详情,请参阅环境变量和系统属性。
示例应用在
build.gradle脚本中定义了系统属性:// You can switch the desired protocol here by changing `otel.exporter.otlp.protocol`. def autoconf_config = [ '-Dotel.exporter.otlp.endpoint=https://telemetry.googleapis.com', '-Dotel.traces.exporter=otlp', '-Dotel.logs.exporter=none', '-Dotel.metrics.exporter=none', '-Dotel.service.name=my-service', '-Dotel.exporter.otlp.protocol=http/protobuf', '-Dotel.java.global-autoconfigure.enabled=true', // ID of your Google Cloud Project, required by the auth extension '-Dgoogle.cloud.project=PROJECT_ID', ] // Now pass the config as JVM arguments to your java application: application { // Replace with the fully qualified name of your Main class. mainClassName = 'com.example.Main' applicationDefaultJvmArgs = autoconf_config }如果您希望使用 gRPC 导出轨迹数据,请将 OTLP 协议设置为
grpc,而不是http/protobuf。
配置权限
手动插桩迁移指南
本部分介绍了如何修改应用,使其能够使用 Telemetry API 将跟踪记录数据发送到您的 Google Cloud 项目。您无法将指标或日志数据发送到此端点。
添加依赖项
第一步是在应用中添加 OpenTelemetry OTLP 跟踪记录导出器的依赖项。选择适合您的应用和构建系统的依赖项版本。
Java
对于 Java 应用,请在 build.gradle 脚本中添加以下依赖项:
// use the latest versions
implementation("io.opentelemetry:opentelemetry-exporter-otlp:1.56.0")
implementation("io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:1.56.0")
Go
本部分说明了在使用 gRPC 进行导出时,您需要对依赖项进行的更改。如果您使用通过 HTTP 连接进行导出的 protobuf 编码数据,请将 otlptracehttp 软件包作为依赖项包含在内。如需了解详情,请参阅使用 HTTP 的 Go 应用。
对于使用 gRPC 进行导出的 Go 应用,请更新 go.mod 文件以添加以下依赖项:
// go.mod file
require(
// OTLP exporter that uses grpc protocol for export
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0
)
Python
本部分说明了在将 gRPC 用于导出时,您需要对依赖项进行的更改。如果您使用通过 HTTP 连接进行导出的 protobuf 编码数据,请将 opentelemetry-exporter-otlp-proto-http 软件包作为必需项包含在内。如需了解详情,请参阅 Python 应用。
对于使用 gRPC 进行导出的 Python 应用,请安装以下依赖项或更新 requirements.txt 文件:
# Requirements.txt - use appropriate versions
#
# OTLP exporter that uses grcp protocol for export
opentelemetry-exporter-otlp-proto-grpc==1.39.0
grpcio==1.76.0
Node.js
本部分说明了在将 gRPC 用于导出时,您需要对依赖项进行的更改。如果您使用通过 HTTP 连接进行导出的 protobuf 编码数据,请将 @opentelemetry/exporter-trace-otlp-proto 软件包作为依赖项包含在内。如需了解详情,请参阅 Node.js 应用。
对于使用 gRPC 的 Node.js 应用,请添加以下依赖项。
"@opentelemetry/exporter-trace-otlp-grpc": "0.203.0",
"@grpc/grpc-js": "1.13.4",
将使用 Google Cloud 导出器替换为使用 OTLP 导出器
更新您的应用代码,以便 OpenTelemetry SDK 配置为使用 OpenTelemetry OTLP 导出器,而不是 Google Cloud 跟踪记录导出器。所需的更改因语言而异。
Java
对于 Java 应用,请执行以下操作:
Go
本部分说明了使用 gRPC 进行导出时需要做出的更改。如果您使用通过 HTTP 连接进行导出的 protobuf 编码数据,则必须导入 otlptracehttp 软件包,并使用相应的选项配置导出器。如需了解详情,请参阅使用 HTTP 的 Go 应用。
对于使用 gRPC 进行导出的 Go 应用,请添加以下 import 语句:
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
// other dependencies
)
此外,更新初始化代码以使用 gRPC 导出器配置 TraceProvider:
// Initializes OpenTelemetry with OTLP exporters
ctx := context.Background()
// creds: configure Application Default Credentials
// Initialize the OTLP gRPC exporter
exporter, err := otlptracegrpc.New(ctx)
if err != nil {
panic(err)
}
// set OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=<project_id>"
// set endpoint with OTEL_EXPORTER_OTLP_ENDPOINT=https://<endpoint>
// set OTEL_EXPORTER_OTLP_HEADERS="x-goog-user-project=<project_id>"
exporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithDialOption(grpc.WithPerRPCCredentials(creds)))
if err != nil {
panic(err)
}
tp := sdktrace.NewTracerProvider(
// For this example code we use sdktrace.AlwaysSample sampler to sample all traces.
// In a production application, use sdktrace.TraceIDRatioBased with a desired probability.
sdktrace.WithSampler(sdktrace.AlwaysSample()),
sdktrace.WithBatcher(exporter))
otel.SetTracerProvider(tp)
Python
本部分说明了使用 gRPC 进行导出时需要做出的更改。如果您使用通过 HTTP 连接进行导出的 protobuf 编码数据,则必须从 opentelemetry.exporter.otlp.proto.http 软件包导入,并使用相应的选项配置导出器。如需了解详情,请参阅 Python 应用。
对于使用 gRPC 进行导出的 Python 应用,请添加以下导入:
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
OTLPSpanExporter,
)
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
此外,更新初始化代码以使用 gRPC 导出器配置 TraceProvider:
# Initialize OpenTelemetry with OTLP exporters
# channel_creds: configure Application Default Credentials
trace_provider = TracerProvider(resource=resource)
processor = BatchSpanProcessor(
OTLPSpanExporter(
credentials=channel_creds,
endpoint="https://telemetry.googleapis.com:443/v1/traces",
)
)
trace_provider.add_span_processor(processor)
trace.set_tracer_provider(trace_provider)
tracer = trace.get_tracer("my.tracer.name")
Node.js
本部分说明了使用 gRPC 进行导出时需要做出的更改。如果您使用通过 HTTP 连接进行导出的 protobuf 编码数据,请导入 @opentelemetry/exporter-trace-otlp-proto 软件包。如需了解详情,请参阅 Node.js 应用。
对于使用 gRPC 进行导出的 Node.js 应用,请添加以下导入:
import {OTLPTraceExporter} from '@opentelemetry/exporter-trace-otlp-grpc';
此外,更新初始化代码以使用 gRPC 导出器配置 TraceProvider:
// Express App that exports traces via gRPC with protobuf
async function main() {
// authenticatedClient: configure Application Default Credentials
// Configure the TraceExporter
const sdk = new NodeSDK({
traceExporter: new OTLPTraceExporter({
credentials: credentials.combineChannelCredentials(
credentials.createSsl(),
credentials.createFromGoogleCredential(authenticatedClient),
),
}),
});
sdk.start();
}
配置身份验证
通过对 OpenTelemetry SDK 配置进行之前的更改,您的应用已配置为通过 gRPC 或 HTTP 使用 OpenTelemetry OTLP 导出器导出跟踪记录。接下来,您需要配置导出器以将这些跟踪记录发送到您的 Google Cloud 项目。
如需配置身份验证,请执行以下操作:
本部分将详细介绍每个步骤。
为导出调用配置身份验证标头
如需使用 Google Cloud应用默认凭证 (ADC) 配置导出器,请添加特定于语言的 Google Auth 库。
Java
如需向 Trace 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
对于使用 OpenTelemetry SDK 自动配置模块的 Java 应用,我们建议您同时使用 Google Cloud 身份验证扩展程序。
// build.gradle
implementation("io.opentelemetry.contrib:opentelemetry-gcp-auth-extension:1.52.0-alpha")
Go
如需向 Trace 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
对于使用 gRPC 进行导出的 Go 应用,请更新 go.mod 文件以添加以下依赖项:
// go.mod file
require (
// When using gRPC based OTLP exporter, auth is built-in
google.golang.org/grpc v1.75.1
)
对于使用 HTTP 进行导出的 Go 应用,请更新 go.mod 文件以包含以下依赖项:
// go.mod file
require (
// When using http based OTLP exported, use explicit auth library
golang.org/x/oauth2 v0.31.0
)
Python
如需向 Trace 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
对于 Python 应用,请添加以下导入:
# requirements.txt
# Google Auth Library
google-auth==2.38.0
Node.js
如需向 Trace 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
对于 Node.js 应用,请添加以下依赖项:
"google-auth-library": "9.15.1",
接下来,更新构造 OTLP span 导出器的应用代码,以便将从库中检索到的授权令牌添加到标头中。此步骤因语言而异,但所有语言的实现方式都是类似的。
Java
如果您有一个使用 OpenTelemetry SDK 自动配置模块和 Google Cloud 身份验证扩展程序的 Java 应用,则无需在应用初始化期间执行任何特殊步骤。自动配置模块会自动执行配置 ADC 所需的步骤。
Go
本部分说明了使用 gRPC 进行导出时需要做出的更改。如果您使用通过 HTTP 连接进行导出的 protobuf 编码数据,则必须导入 otlptracehttp 软件包,并将导出器配置为 otlptracehttp 对象。如需了解详情,请参阅使用 HTTP 的 Go 应用。
对于使用 gRPC 进行导出的 Go 应用,请添加以下 import 语句:
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
// other dependencies
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/oauth"
)
此外,请更新初始化代码,以便在实例化 gRPC 导出器之前配置 ADC:
// Initializes OpenTelemetry with OTLP exporters
ctx := context.Background()
// Retrieve and store Google application-default credentials
creds, err := oauth.NewApplicationDefault(ctx)
if err != nil {
panic(err)
}
// set OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=<project_id>"
// set endpoint with OTEL_EXPORTER_OTLP_ENDPOINT=https://<endpoint>
// set OTEL_EXPORTER_OTLP_HEADERS="x-goog-user-project=<project_id>"
exporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithDialOption(grpc.WithPerRPCCredentials(creds)))
if err != nil {
panic(err)
}
// Other OpenTelemetry configuration remains unaffected.
Python
本部分说明了使用 gRPC 进行导出时需要做出的更改。如果您通过 HTTP 连接使用 protobuf 编码的数据进行导出,请使用默认凭据。您还必须在实例化 BatchSpanProcessor 时传递这些凭据。如需了解详情,请参阅 Python 应用。
对于使用 gRPC 进行导出的 Python 应用,请添加以下导入:
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
OTLPSpanExporter,
)
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
import google.auth
import google.auth.transport.grpc
import google.auth.transport.requests
import grpc
from google.auth.transport.grpc import AuthMetadataPlugin
此外,请更新初始化代码,以便在实例化 gRPC 导出器之前配置 ADC:
credentials, _ = google.auth.default()
request = google.auth.transport.requests.Request()
resource = Resource.create(attributes={SERVICE_NAME: "otlp-gcp-grpc-sample"})
auth_metadata_plugin = AuthMetadataPlugin(credentials=credentials, request=request)
channel_creds = grpc.composite_channel_credentials(
grpc.ssl_channel_credentials(),
grpc.metadata_call_credentials(auth_metadata_plugin),
)
# Configure the TraceProvider
Node.js
本部分说明了使用 gRPC 进行导出时需要做出的更改。如果您使用通过 HTTP 连接进行导出的 protobuf 编码数据,则需要进行的更改与此处描述的略有不同。如需了解详情,请参阅 Node.js 应用中包含的 app-http-proto-export.ts 文件。
对于使用 gRPC 进行导出的 Node.js 应用,请添加以下导入:
import {AuthClient, GoogleAuth} from 'google-auth-library';
import {credentials} from '@grpc/grpc-js';
此外,请更新初始化代码,以便在实例化 gRPC 导出器之前配置 ADC:
async function getAuthenticatedClient(): Promise<AuthClient> {
const auth: GoogleAuth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
return await auth.getClient();
}
// Express App that exports traces via gRPC with protobuf
async function main() {
const authenticatedClient: AuthClient = await getAuthenticatedClient();
// Configure the TraceExporter
}
配置所需的 OpenTelemetry 资源属性
向 OTEL_RESOURCE_ATTRIBUTES 环境变量添加用于指定项目的键值对。对于键,请使用 gcp.project_id。对于值,请使用您的 Google Cloud 项目的 ID。
示例:
export OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=PROJECT_ID"
如果您使用 Java 并将应用配置为使用 Google Cloud 身份验证扩展程序(如示例 Java 应用所示),则无需将项目 ID 设置为 OpenTelemetry 资源属性的一部分。不过,设置此属性并无害处。
如需详细了解 OpenTelemetry 环境变量,请参阅常规 SDK 配置。
设置配额项目 ID
配额项目是用于跟踪 API 请求用量的 Google Cloud 项目。由于 Telemetry API 是基于客户端的 API,因此身份验证方式决定了是否会自动识别配额项目。例如,当您使用服务账号进行身份验证时,无需指定配额项目。不过,当使用用户凭证进行身份验证时,您需要指定配额项目。
您可以使用环境变量设置配额项目。如需确定要为编程语言设置的环境变量,请参阅使用环境变量设置配额项目。
例如,对于 Go,您可以按如下方式设置配额项目:
export GOOGLE_CLOUD_QUOTA_PROJECT="QUOTA_PROJECT_ID"
如需了解如何解决身份验证错误,请参阅用户凭证不起作用。
配置导出器端点
将 OTEL_EXPORTER_OTLP_ENDPOINT 环境变量的值设置为 Google Cloud的 OTLP 端点。
示例:
export OTEL_EXPORTER_OTLP_ENDPOINT=https://telemetry.googleapis.com
如果您使用 Java 和自动配置模块,则可以像示例 Java 应用一样,使用系统属性设置导出器端点。您无需为该配置设置导出器环境变量。
如需详细了解 OpenTelemetry 环境变量,请参阅常规 SDK 配置。