從追蹤匯出工具遷移至 OTLP 端點

您可以將手動檢測的 Java、Go、Python 和 Node.js 應用程式,從 Google Cloud 追蹤記錄匯出工具遷移至程序內 OpenTelemetry OTLP 匯出工具。OTLP 匯出工具會使用支援的匯出通訊協定 (gRPC 或 http/protobuf),將追蹤記錄資料直接傳送至 Google Cloud 專案中的 Telemetry (OTLP) API。

這項設定只會匯出追蹤記錄資料,且僅適用於程序內匯出工具。如果應用程式使用 OpenTelemetry 收集器,請參閱「以收集器為基礎的檢測範例」和「Google 建構的 OpenTelemetry 收集器」。

遷移的好處

OpenTelemetry SDK 產生的記錄、指標和追蹤記錄資料,格式通常與 OpenTelemetry 通訊協定定義的 proto 檔案一致。不過,欄位可能會先從 OpenTelemetry 專屬資料類型轉換為 JSON 資料類型,再儲存。

當應用程式使用 Google Cloud 匯出工具將資料匯出至 Google Cloud 專案時,匯出工具會執行下列步驟:

  1. 將記錄的資料從 OTLP 格式轉換為 Cloud Logging API、Cloud Monitoring API 或 Cloud Trace API 定義的專屬格式。
  2. 將轉換後的資料傳送至適當的 API,然後儲存在 Google Cloud 專案中。

如果是追蹤記錄資料,建議您將應用程式遷移至使用 Telemetry (OTLP) API 匯出資料,因為這項匯出作業不需要轉換資料。資料轉換可能會導致部分資料遺失。舉例來說,專屬格式對特定欄位的限制可能較低,或某些 OTLP 欄位可能無法對應至專屬格式中的欄位。

可用的範例

本頁面提及的範例應用程式可在 GitHub 取得。大多數應用程式都設定為使用 gRPC 匯出追蹤記錄資料,也就是透過 HTTP/2 連線,以 gRPC 線路格式傳送 protobuf 編碼資料。我們也為應用程式提供範例程式碼,這些應用程式設定為透過 HTTP 連線,將追蹤記錄資料匯出為 protobuf 編碼資料:

  • Java 應用程式

    範例應用程式已設為透過 HTTP 連線,將追蹤記錄匯出為 protobuf 編碼資料。如果您偏好使用 gRPC,則適用這個範例中的檢測。不過,您必須修改自動設定模組使用的系統屬性。範例應用程式會指定 http/protobuf 匯出工具。如要使用 gRPC,請將這項設定變更為 grpc。

    建議您的 Java 應用程式 (例如範例應用程式) 使用 OpenTelemetry SDK Autoconfigure 模組設定 SDK。

  • 使用 gRPC 的 Go 應用程式和使用 HTTP 的 Go 應用程式

    有兩個 Go 存放區。在其中一個存放區中,範例應用程式使用 gRPC。另一個存放區中的範例則透過 HTTP 連線使用 protobuf 編碼資料。

  • Python 存放區

    這個存放區包含兩個範例,一個用於 gRPC,另一個則透過 HTTP 連線使用 protobuf 編碼資料。

  • Node.js 應用程式

    這個存放區包含兩個範例,一個用於 gRPC,另一個則透過 HTTP 連線使用 protobuf 編碼資料。

事前準備

遷移應用程式,將追蹤記錄資料傳送至 OTLP 端點之前,請先啟用 Telemetry API,並確認您已取得必要的 Identity and Access Management (IAM) 角色。您可能也需要將 IAM 角色授予服務帳戶。

啟用計費功能和 Telemetry API

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎 建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  2. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Telemetry, Cloud Logging, Cloud Monitoring, and Cloud Trace APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  5. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Telemetry, Cloud Logging, Cloud Monitoring, and Cloud Trace APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

設定權限

手動檢測機制的遷移指南

本節說明如何修改應用程式,以便使用 Telemetry API 將追蹤記錄資料傳送至 Google Cloud 專案。

新增依附元件

第一步是在應用程式中,為 OpenTelemetry 的 OTLP 追蹤記錄匯出工具新增依附元件。選取適合應用程式和建構系統的依附元件版本。

Java

如果是 Java 應用程式,請在 build.gradle 指令碼中新增下列依附元件:

implementation("io.opentelemetry:opentelemetry-exporter-otlp:1.62.0")
implementation("io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:1.62.0")

Go

本節說明使用 gRPC 匯出時,需要對依附元件進行的變更。如果您透過 HTTP 連線使用 protobuf 編碼資料進行匯出,請將 otlptracehttp 套件納入為依附元件。詳情請參閱「使用 HTTP 的 Go 應用程式」。

如果 Go 應用程式使用 gRPC 匯出,請更新 go.mod 檔案,加入下列依附元件:

require (
	// ...
	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0
)

Python

本節說明使用 gRPC 匯出時,需要對依附元件進行的變更。如果您透過 HTTP 連線使用 protobuf 編碼資料進行匯出,請將 opentelemetry-exporter-otlp-proto-http 套件納入為必要項目。詳情請參閱 Python 存放區。

如果 Python 應用程式使用 gRPC 匯出,請安裝下列依附元件或更新 requirements.txt 檔案:

opentelemetry-exporter-otlp-proto-grpc==1.42.1
grpcio==1.80.0

Node.js

本節說明使用 gRPC 匯出時,需要對依附元件進行的變更。如果您透過 HTTP 連線使用 protobuf 編碼資料進行匯出,請將 @opentelemetry/exporter-trace-otlp-proto 套件納入為依附元件。詳情請參閱「Node.js 應用程式」。

如果 Node.js 應用程式使用 gRPC 匯出追蹤記錄資料,請新增下列依附元件:

"@opentelemetry/exporter-trace-otlp-grpc": "0.221.0",
"@grpc/grpc-js": "1.14.4"

改用 OTLP 匯出工具,而非 Google Cloud 匯出工具

更新應用程式程式碼,將 OpenTelemetry SDK 設為使用 OpenTelemetry OTLP 匯出工具,而非 Google Cloud 追蹤記錄匯出工具。必要變更因語言而異。

Java

如果是 Java 應用程式,請按照下列步驟操作:

  1. 新增下列匯入陳述式:

    import io.opentelemetry.sdk.OpenTelemetrySdk;
    import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
  2. 更新應用程式程式碼,使用 OpenTelemetry SDK Autoconfigure 模組設定 SDK:

    public static void main(String[] args) {
      // Configure the OpenTelemetry pipeline with Auto configuration
      openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk();
    
      // ...
    }
  3. 設定 autoconfigure 模組在執行階段使用的系統屬性。該模組會使用這些屬性啟動 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=otlptrace-example',
    	'-Dotel.exporter.otlp.protocol=http/protobuf',
    	'-Dotel.java.global-autoconfigure.enabled=true',
    ]

    此外,請將設定做為 JVM 引數傳遞:

    application {
    	mainClassName = 'com.google.cloud.opentelemetry.samples.otlptrace.OTLPTraceExample'
    	// Pass the config as JVM arguments to the Java application
    	applicationDefaultJvmArgs = autoconf_config
    }

    如要使用 gRPC 匯出追蹤記錄資料,請將 OTLP 通訊協定設為 grpc,而非 http/protobuf。

Go

本節說明使用 gRPC 匯出時需要進行的變更。如果您透過 HTTP 連線使用 protobuf 編碼資料進行匯出,則必須匯入 otlptracehttp 套件,並使用對應的選項設定匯出工具。詳情請參閱「使用 HTTP 的 Go 應用程式」。

如果 Go 應用程式使用 gRPC 匯出,請新增下列匯入陳述式:

import (
	"context"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"

	// ...
)

此外,請更新初始化程式碼,使用 gRPC 匯出工具設定 TraceProvider:

// Initializes OpenTelemetry with OTLP exporters
ctx := context.Background()

// Configure gRPC client with 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>"
// Configure exporter to use the credentials
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 存放區。

如果 Python 應用程式使用 gRPC 匯出,請新增下列匯入項目:

from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
    OTLPSpanExporter,
)

此外,請更新初始化程式碼,使用 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 應用程式」。

如果 Node.js 應用程式使用 gRPC 匯出,請新增下列匯入項目:

import {OTLPTraceExporter} from '@opentelemetry/exporter-trace-otlp-grpc';

此外,請更新初始化程式碼,使用 gRPC 匯出工具設定 TraceProvider:

const sdk = new NodeSDK({
  traceExporter: new OTLPTraceExporter({
    credentials: credentials.combineChannelCredentials(
      credentials.createSsl(),
      credentials.createFromGoogleCredential({
        async getRequestHeaders(
          url?: string,
        ): Promise<{[index: string]: string}> {
          const rawHeaders = await authenticatedClient.getRequestHeaders(url);
          return Object.fromEntries(rawHeaders.entries());
        },
      }),
    ),
  }),
});
sdk.start();

設定驗證機制

完成上述 OpenTelemetry SDK 設定變更後,應用程式會設為使用 gRPC 或 HTTP,透過 OpenTelemetry OTLP 匯出工具匯出追蹤記錄。接下來,您必須設定匯出工具,將這些追蹤記錄傳送至 Google Cloud 專案。

如要設定驗證機制,請按照下列步驟操作:

  1. 設定匯出呼叫的驗證標頭。
  2. 設定必要的 OpenTelemetry 資源屬性和 OTLP 標頭。
  3. 設定匯出工具端點。

本節將詳細說明各個步驟。

設定匯出呼叫的驗證標頭

如要使用 Google Cloud 應用程式預設憑證 (ADC) 設定匯出工具,請新增特定語言的 Google 驗證程式庫。

Java

如果 Java 應用程式使用 OpenTelemetry SDK 自動設定模組,建議您也使用 Google Cloud 驗證擴充功能。

implementation("io.opentelemetry.contrib:opentelemetry-gcp-auth-extension:1.56.0-alpha")

Go

如果 Go 應用程式使用 gRPC 匯出,請更新 go.mod 檔案,加入下列依附元件:

// When using gRPC based OTLP exporter, the auth is built in.
google.golang.org/grpc v1.82.1

如果 Go 應用程式使用 HTTP 匯出,請更新 go.mod 檔案,加入下列依附元件:

// When using http based OTLP exporter, use explicit auth library
golang.org/x/oauth2 v0.36.0

Python

如果是 Python 應用程式,請將下列依附元件新增至 requirements.txt 檔案:

# Google Auth Library
google-auth==2.53.0

Node.js

如果是 Node.js 應用程式,請新增下列依附元件:

"google-auth-library": "10.5.0"

接著,更新建構 OTLP 跨距匯出工具的應用程式程式碼,將從程式庫擷取的授權權杖新增至標頭。這個步驟因語言而異,但所有語言的實作方式都類似。

Java

如果 Java 應用程式使用 OpenTelemetry SDK Autoconfigure 模組和 Google Cloud 驗證擴充功能,則在初始化應用程式時,不需要執行任何特殊步驟。自動設定模組會自動執行設定 ADC 所需的步驟。

Go

本節說明使用 gRPC 匯出時需要進行的變更。如果您透過 HTTP 連線使用 protobuf 編碼資料進行匯出,則必須匯入 otlptracehttp 套件,並將匯出工具設定為 otlptracehttp 物件。詳情請參閱「使用 HTTP 的 Go 應用程式」。

如果 Go 應用程式使用 gRPC 匯出,請新增下列匯入陳述式:

"google.golang.org/grpc"
"google.golang.org/grpc/credentials/oauth"

此外,請更新初始化程式碼,先設定 ADC,再例項化 gRPC 匯出工具:

// Initializes OpenTelemetry with OTLP exporters
ctx := context.Background()

// Configure gRPC client with 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>"
// Configure exporter to use the credentials
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 編碼資料進行匯出,請使用預設憑證。例項化 BatchSpanProcessor 時,也必須傳遞這些憑證。詳情請參閱 Python 存放區。

如果 Python 應用程式使用 gRPC 匯出,請新增下列匯入項目:

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),
)

Node.js

本節說明使用 gRPC 匯出時需要進行的變更。如果您透過 HTTP 連線使用 protobuf 編碼資料進行匯出,則需要進行的變更與此處所述略有不同。詳情請參閱 Node.js 應用程式中的 app-http-proto-export.ts 檔案。

如果 Node.js 應用程式使用 gRPC 匯出,請新增下列匯入項目:

import {AuthClient, GoogleAuth} from 'google-auth-library';
import {credentials} from '@grpc/grpc-js';

此外,請更新初始化程式碼,先設定 ADC,再例項化 gRPC 匯出工具:

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();

  // ...
}

設定必要的 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 設定」。