本文說明如何遷移已使用 OpenTelemetry 檢測,並依賴 Google Cloud 匯出器的應用程式,改用 OpenTelemetry 的 OTLP 匯出器。這兩項設定都會將遙測資料傳送至您的 Google Cloud 專案。 本文中的步驟適用於 OpenTelemetry SDK 執行的程序內匯出作業。
本文說明如何在使用手動檢測時匯出追蹤資料。這份指南適用於 Java、Go 和 Python,但不適用於將記錄或指標資料傳送至 Google Cloud 專案。
遷移的好處
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 欄位可能無法對應至專有格式的欄位。
事前準備
將應用程式遷移至 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
      (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
      (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 遙測資料追蹤記錄寫入者  (roles/telemetry.tracesWriter)
- 
  
  
    
      記錄寫入者  (roles/logging.logWriter)
- 
  
  
    
      Monitoring 指標寫入者  (roles/monitoring.metricWriter)
 
- 
  
  
    
      Cloud 遙測資料追蹤記錄寫入者  (
- 
  
  
  
  
  
  
  
    
    
    
    
    
    
      
      
        
        
      
      
    
      
      
        
        
      
      
    
      
      
        
        
      
      
    
    
    
    
    
  
  如要取得查看記錄、指標和追蹤資料所需的權限,請要求管理員為您授予專案的下列 IAM 角色: - 
  
  
    
      記錄檢視器  (roles/logging.viewer)
- 
  
  
    
      監控檢視器  (roles/monitoring.viewer)
- 
  
  
    
      Cloud Trace 使用者  (roles/cloudtrace.user)
 如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。 
- 
  
  
    
      記錄檢視器  (
設定權限
手動插碼遷移指南
本節說明如何修改應用程式,以便使用 Telemetry API 將追蹤資料傳送至 Google Cloud 專案。您無法將指標或記錄資料傳送至這個端點。
新增依附元件
第一步是在應用程式中新增 OpenTelemetry 的 OTLP 追蹤記錄匯出工具的依附元件。選取適合應用程式和建構系統的依附元件版本。
Java
如果是使用 Gradle 建構系統的 Java 應用程式:
// build.gradle
implementation("io.opentelemetry:opentelemetry-exporter-otlp:1.47.0")
Go
如果是 Golang 應用程式,請確認 go.mod 檔案包含下列依附元件:
// go.mod file
require(
  // OTLP exporter that uses grpc protocol for export
  go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.34.0
  // Alternatively, for export using http/protobuf protocol, use:
  go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.34.0
)
Python
如果是 Python 應用程式,請安裝下列依附元件或更新 requirements.txt 檔案:
# Requirements.txt - use appropriate versions
#
# OTLP exporter that uses grcp protocol for export
opentelemetry-exporter-otlp-proto-grpc==1.30.0
grpcio==1.70.0
# Alternatively, for export using http/protobuf protocol, use:
opentelemetry-exporter-otlp-proto-http==1.30.0
將 Google Cloud 匯出工具替換為 OTLP 匯出工具
更新應用程式程式碼,將 OpenTelemetry SDK 設為使用 OpenTelemetry OTLP 匯出工具,而非 Google Cloud 追蹤記錄匯出工具。所需變更會因語言而異。
Java
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import io.opentelemetry.sdk.trace.samplers.Sampler;
// Initialize OpenTelemetry SDK with OTLP exporters
public static OpenTelemetry initOpenTelemetry() {
    // Initialize the OTLP gRPC exporter
    SpanExporter otlpGrpcSpanExporter =
        OtlpGrpcSpanExporter.builder()
            .setTimeout(2, TimeUnit.SECONDS)
            .build();
    // Initialize OpenTelemetry tracer provider
    SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
        .setResource(resource)
        .setSampler(Sampler.traceIdRatioBased(0.02))
        .addSpanProcessor(
            BatchSpanProcessor.builder(otlpGrpcSpanExporter)
                .setScheduleDelay(100, TimeUnit.MILLISECONDS)
                .build());
    // Configure OpenTelemetry SDK instacne to use the tracer provider
    // configured with OTLP exporter
    OpenTelemetrySdk openTelemetrySdk =
        OpenTelemetrySdk.builder()
            .setTracerProvider(tracerProvider)
            .build();
}
Go
import (
    "context"
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
    sdktrace "go.opentelemetry.io/otel/sdk/trace"
    // other dependencies
)
// Initializes OpenTelemetry with OTLP exporters
func init() {
    ctx := context.Background()
    // Initialize the OTLP gRPC exporter
    exporter, err := otlptracegrpc.New(ctx)
    if err != nil {
        panic(err)
    }
    // initialize OpenTelemetry tracer provdier
    tp := sdktrace.NewTracerProvider(
        sdktrace.WithSampler(sdktrace.TraceIDRatioBased(0.02)),
        sdktrace.WithBatcher(exporter)
    )
    // configure OpenTelemetry SDK instance to use the tracer provider
    // configured with OTLP exporter
    otel.SetTracerProvider(tp)
}
Python
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
    OTLPSpanExporter,
)
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
# Initialize OpenTelemetry with OTLP exporters
def init():
    # Initialize the OTLP gRPC or http exporter
    otlp_grpc_exporter = OTLPSpanExporter()
    # Initialize OpenTelemetry TracerProvider
    trace_provider = TracerProvider(resource=resource).add_span_processor(
    BatchSpanProcessor(otlp_grpc_exporter)
    )
    # Configure OpenTelemetry tracing API with the initialized tracer provider
    trace.set_tracer_provider(trace_provider)
設定驗證機制
完成先前對 OpenTelemetry SDK 設定的變更後,應用程式就會設定為使用 OpenTelemetry OTLP 匯出工具,透過 gRPC 或 HTTP 匯出追蹤記錄。接著,您需要設定匯出工具,將這些追蹤記錄傳送至您的 Google Cloud 專案。
如要設定驗證,請按照下列步驟操作:
本節將詳細說明每個步驟。
為匯出呼叫設定驗證標頭
如要使用 Google Cloud 應用程式預設憑證 (ADC) 設定匯出工具,請新增特定語言的 Google Auth 程式庫。
Java
如要向 Trace 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。
// build.gradle
// Google Auth Library
implementation("com.google.auth:google-auth-library-oauth2-http:1.32.1")
Go
如要向 Trace 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。
// go.mod file
require (
    // When using gRPC based OTLP exporter, auth is built-in
    google.golang.org/grpc v1.70.0
    // When using http based OTLP exported, use explicit auth library
    golang.org/x/oauth2 v0.26.0
)
Python
如要向 Trace 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。
# requirements.txt
# Google Auth Library
google-auth==2.38.0
接著,請更新建構 OTLP span 匯出器的應用程式程式碼,將從程式庫擷取的授權權杖新增至標頭。這個步驟會因語言而異,但所有語言的實作方式都類似。
Java
使用 OpenTelemetry SDK Autoconfigure 模組時,建議使用 Google Cloud Authentication Extension。如需使用這項擴充功能的完整範例,請參閱「OTLP Trace with Google Auth Example」。
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import io.opentelemetry.sdk.trace.samplers.Sampler;
import com.google.auth.oauth2.GoogleCredentials;
// Initialize OpenTelemetry SDK with OTLP exporters
public static OpenTelemetry initOpenTelemetry() {
    // Retrieve and store application-default credentials
    GoogleCredentials credentials;
    try {
       credentials = GoogleCredentials.getApplicationDefault();
    } catch (IOException e) {
      // Handle authentication error
      throw new RuntimeException(e);
    }
    // Update gRPC span exporter to add the authorization headers
    // If you are using the Autoconfigure module, we recommend using
    // Google Cloud Authentication Extension.
    // See https://github.com/open-telemetry/opentelemetry-java-contrib/tree/main/gcp-auth-extension
    SpanExporter otlpGrpcSpanExporter =
        OtlpGrpcSpanExporter.builder()
            .setHeaders(
                () -> {
                  Map<String, List<String>> gcpHeaders;
                  try {
                    credentials.refreshIfExpired();
                    gcpHeaders = credentials.getRequestMetadata();
                  } catch (IOException e) {
                    // Handle authentication error
                    throw new RuntimeException(e);
                  }
                  Map<String, String> flattenedHeaders =
                      gcpHeaders.entrySet().stream()
                          .collect(
                              Collectors.toMap(
                                  Map.Entry::getKey,
                                  entry ->
                                      entry.getValue().stream()
                                          .filter(Objects::nonNull)
                                          .filter(s -> !s.isEmpty())
                                          .collect(Collectors.joining(",")),
                                  (v1, v2) -> v2));
                  return flattenedHeaders;
                })
            .setTimeout(2, TimeUnit.SECONDS)
            .build();
  // Other OpenTelemetry configuration remains unaffected
}
Go
import (
    "context"
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
    sdktrace "go.opentelemetry.io/otel/sdk/trace"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/oauth"
)
// Initializes OpenTelemetry with OTLP exporters
func init() {
    ctx := context.Background()
    // Retrieve and store Google application-default credentials
    creds, err := oauth.NewApplicationDefault(ctx)
    if err != nil {
        panic(err)
    }
    // Update the previously created OTLP gRPC span exporter to
    // add authorization headers
    exporter, err := otlptracegrpc.New(
        ctx,
        otlptracegrpc.WithDialOption(grpc.WithPerRPCCredentials(creds))
    )
    // Other OpenTelemetry configuration remains unaffected.
}
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
# Initialize OpenTelemetry with OTLP exporters
def init():
    # Retrieve and store Google application-default credentials
    credentials, project_id = google.auth.default()
    # Request used to refresh credentials upon expiry
    request = google.auth.transport.requests.Request()
    # Supply the request and credentials to AuthMetadataPlugin
    # AuthMeatadataPlugin inserts credentials into each request
    auth_metadata_plugin = AuthMetadataPlugin(
        credentials=credentials, request=request
    )
    # Initialize gRPC channel credentials using the AuthMetadataPlugin
    channel_creds = grpc.composite_channel_credentials(
        grpc.ssl_channel_credentials(),
        grpc.metadata_call_credentials(auth_metadata_plugin),
    )
    # Update the previously created OTLP gRPC span exporter to add authorization
    # credentials
    otlp_grpc_exporter = OTLPSpanExporter(credentials=channel_creds)
    # Other OpenTelementry configuration remains unaffected
設定必要的 OpenTelemetry 資源屬性
在 OTEL_RESOURCE_ATTRIBUTES 環境變數中,新增指定專案的鍵值配對。如需金鑰,請使用 gcp.project_id。
請使用 Google Cloud 專案的 ID 做為值。
範例:
export OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=PROJECT_ID"
如要進一步瞭解 OpenTelemetry 環境變數,請參閱「一般 SDK 設定」。
設定配額專案 ID
配額專案是 Google Cloud 專案,可追蹤 API 要求的使用情形。由於 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
如要進一步瞭解 OpenTelemetry 環境變數,請參閱「一般 SDK 設定」。