C++ and OpenTelemetry Stay organized with collections Save and categorize content based on your preferences.
This page guides you through the following steps:
- Install the OpenTelemetry packages.
- Configure your application to export spans to Cloud Trace.
- Configure your platform.
For release information, see the following:
For OpenTelemetry reference content, see the following:
For the latest details about OpenTelemetry for C++,along with additional documentation and examples, seeOpenTelemetry.
Before you begin
Enable the Cloud Trace API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.
Install the OpenTelemetry packages
- Set up a C++ development environment.
- Install the Google Cloud C++ OpenTelemetry exporter library. Forinstallation information, see theOpenTelemetry quickstart.
Configure the export of spans to Cloud Trace
To configure the export of trace data, call thegoogle::cloud::otel::ConfigureBasicTracing(...) method in yourmain()method:
namespacegc=::google::cloud;[](std::stringproject_id){autoproject=gc::Project(std::move(project_id));autoconfiguration=gc::otel::ConfigureBasicTracing(project);MyApplicationCode();}The fieldproject_id is the Google Cloud project where you want to store thetraces.
The methodConfigureBasicTracing(...) instantiates aTracerProvider object that implementsa Cloud Trace exporter. If the object returned by the call toConfigureBasicTracing(...) goes out of scope, then the previousTracerProvider object is reinstated, when one exists.
Configure sample rate
Applications might generate a large volume of trace data. The followingsample illustrates how to configure the sampling rate:
namespacegc=::google::cloud;[](std::stringproject_id){autoproject=gc::Project(std::move(project_id));autooptions=gc::Options{}.set<gc::otel::BasicTracingRateOption>(.001);autoconfiguration=gc::otel::ConfigureBasicTracing(project,options);MyApplicationCode();}Export to Cloud Trace with a customTracerProvider
You might have use cases that require a customTracerProvider object. Forexample, if you want to use multiple exporters at the same time, you needto make a customTracerProvider object. In these cases, you can use theCloud Trace exporter directly:
namespacegc=::google::cloud;using::opentelemetry::trace::Scope;[](std::stringproject_id){// Use the Cloud Trace Exporter directly.autoproject=gc::Project(std::move(project_id));autoexporter=gc::otel::MakeTraceExporter(project);// Advanced use cases may need to create their own tracer provider, e.g. to// export to Cloud Trace and another backend simultaneously. In this// example, we just tweak some OpenTelemetry settings that google-cloud-cpp// does not expose.opentelemetry::sdk::trace::BatchSpanProcessorOptionsoptions;options.schedule_delay_millis=std::chrono::milliseconds(1000);autoprocessor=opentelemetry::sdk::trace::BatchSpanProcessorFactory::Create(std::move(exporter),options);// Create a tracer provider and set it as the global trace provideropentelemetry::trace::Provider::SetTracerProvider(std::shared_ptr<opentelemetry::trace::TracerProvider>(opentelemetry::sdk::trace::TracerProviderFactory::Create(std::move(processor))));MyApplicationCode();// Clear the global trace provideropentelemetry::trace::Provider::SetTracerProvider(opentelemetry::nostd::shared_ptr<opentelemetry::trace::TracerProvider>());}Instrument your own application
For information about how to configure your application to capture tracespans, seeOpenTelemetry Tracing.This page describes how to do all of the following:
- Create a span
- Create nested spans
- Set span attributes
- Create spans with events
- Create spans with links
// For more details on the OpenTelemetry code in this sample, see:// https://opentelemetry.io/docs/instrumentation/cpp/manual/namespacegc=::google::cloud;using::opentelemetry::trace::Scope;[](std::stringproject_id){autoproject=gc::Project(std::move(project_id));autoconfiguration=gc::otel::ConfigureBasicTracing(project);// Initialize the `Tracer`. This would typically be done once.autoprovider=opentelemetry::trace::Provider::GetTracerProvider();autotracer=provider->GetTracer("my-application");// If your application makes multiple client calls that are logically// connected, you may want to instrument your application.automy_function=[tracer]{// Start an active span. The span is ended when the `Scope` object is// destroyed.autoscope=Scope(tracer->StartSpan("my-function-span"));// Any spans created by the client library will be children of// "my-function-span". i.e. In the distributed trace, the client calls are// sub-units of work of `my_function()`, and will be displayed as such in// Cloud Trace.Clientclient;client.CreateFoo();client.DeleteFoo();};// As an example, start a span to cover both calls to `my_function()`.autoscope=Scope(tracer->StartSpan("my-application-span"));my_function();my_function();}Sample application
For a sample application, seethequickstart.
Configure your platform
You can use Cloud Trace on Google Cloud and other platforms.
Running on Google Cloud
When your application is running on Google Cloud, you don't need toprovide authentication credentials in the form of a service account to theclient library. However, you do need to ensure thatyour Google Cloud platform has theCloud Trace API access scope enabled.
For a list of supported Google Cloud environments, seeEnvironment support.
For the following configurations, the default access-scope settings enablethe Cloud Trace API:
- App Engine flexible environment
App Engine standard environment
Google Kubernetes Engine (GKE)
Note: If you use Autopilot or if you enable Workload Identity Federation for GKE foryour GKE cluster, then ensure that youconfigure your application to use Workload Identity Federation for GKE.Compute Engine
Cloud Run
If you use custom access scopes, then you must ensure thatCloud Trace API access scope is enabled:
For information about how to configure theaccess scopes for your environment by using the Google Cloud console, seeConfiguring your Google Cloud project.
For
gcloudusers, specify access scopes using the--scopesflagand include thetrace.appendCloud Trace API access scope.For example, to create a GKE cluster with onlythe Cloud Trace API enabled, do the following:gcloud container clusters create example-cluster-name --scopes=https://www.googleapis.com/auth/trace.append
Running locally and elsewhere
If your application is running outside of Google Cloud, then you mustprovide authentication credentials in the form of a service account to theclient library. The service account must contain theCloud Trace agent role.For instructions, seeCreating a service account.
Google Cloud client libraries useApplication Default Credentials (ADC) to find yourapplication's credentials.
You can provide these credentials in one of three ways:
Run
gcloud auth application-default loginPlace the service account in a default path for your operating system.The following lists the default paths for Windows and Linux:
Windows:
%APPDATA%/gcloud/application_default_credentials.jsonLinux:
$HOME/.config/gcloud/application_default_credentials.json
Set the
GOOGLE_APPLICATION_CREDENTIALSenvironment variable tothe path to your service account:
Linux/macOS
exportGOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key
Windows
setGOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key
PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="path-to-your-service-accounts-private-key"
View traces
In the Google Cloud console, go to the
Trace explorer page:
You can also find this page by using the search bar.
Troubleshooting
For information on troubleshooting issues with Cloud Trace, go to theTroubleshooting page.
To debug the C++ Cloud Trace exporter, see theTroubleshooting section of the referencedocumentation.
Resources
- https://opentelemetry.io/
- open-telemetry/opentelemetry-cppGitHub repository
- google-cloud-cpp OpenTelemetry Exporters LibraryGitHub repository.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-18 UTC.