Setting up Stackdriver Trace for Java

Trace's Java support is provided by OpenCensus, a set of tracing and application metrics instrumentation libraries that work with multiple backends. You can find the latest details about OpenCensus for Java, along with additional documentation and examples, on its GitHub page.

Installing the library

To collect traces, add OpenCensus tracing and the Stackdriver exporter to your applications Maven or Gradle file:

Maven

<dependency>
  <groupId>io.opencensus</groupId>
  <artifactId>opencensus-api</artifactId>
  <version>0.12.2</version>
</dependency>
<dependency>
  <groupId>io.opencensus</groupId>
  <artifactId>opencensus-exporter-trace-stackdriver</artifactId>
  <version>0.12.2</version>
</dependency>
<dependency>
  <groupId>io.opencensus</groupId>
  <artifactId>opencensus-impl</artifactId>
  <version>0.12.2</version>
  <scope>runtime</scope>
</dependency>

Gradle

compile 'io.opencensus:opencensus-api:0.12.2'
compile 'io.opencensus:opencensus-exporter-trace-stackdriver:0.12.2'
runtime 'io.opencensus:opencensus-impl:0.12.2'

Configuring the Stackdriver exporter

In order to export the collected Trace data, use a Stackdriver exporter. The Stackdriver exporter uses the Application Default Credentials for authentication. You can omit the project ID if your code is running on Google Cloud Platform (GCP):

public static void createAndRegisterGoogleCloudPlatform(String projectId) throws IOException {
  StackdriverTraceExporter.createAndRegister(
      StackdriverTraceConfiguration.builder()
          .setProjectId(projectId)
          .build());
}

Add a custom Trace span

While Stackdriver Trace library for Java contains automatic integrations for several popular web and RPC frameworks, you can also manually interact with traces:

private static final Tracer tracer = Tracing.getTracer();

public static void doWork() {
  // Create a child Span of the current Span.
  try (Scope ss = tracer.spanBuilder("MyChildWorkSpan").startScopedSpan()) {
    doInitialWork();
    tracer.getCurrentSpan().addAnnotation("Finished initial work");
    doFinalWork();
  }
}

private static void doInitialWork() {
  // ...
  tracer.getCurrentSpan().addAnnotation("Doing initial work");
  // ...
}

private static void doFinalWork() {
  // ...
  tracer.getCurrentSpan().addAnnotation("Hello world!");
  // ...
}

Enabling full sampling

By default, only 1 in 10,000 traces is sampled.

In a developer environment, this sampling rate is often too low to show you trace data. You can use the alwaysSample option to sample all traces. Do not use this option in a production environment; doing so can generate a large volume of trace data and increase your usage bill.

To enable full sampling, use the setSampler method and specify the alwaysSample option:

public static void doWorkFullSampled() {
  try (
      Scope ss = tracer.spanBuilder("MyChildWorkSpan")
                   .setSampler(Samplers.alwaysSample())
                   .startScopedSpan()) {
    doInitialWork();
    tracer.getCurrentSpan().addAnnotation("Finished initial work");
    doFinalWork();
  }
}

Running on Google Cloud Platform

You don't need to provide authentication credentials for instances running on Google Cloud Platform, provided Stackdriver Trace API access scope is enabled on that instance. However, we recommend setting the broadest possible access scope for your instance and then using Cloud Identity and Access Management to restrict access.

To override the automatic authentication and project selection, use the following:

public static void createAndRegisterWithToken(String accessToken) throws IOException {
  Date expirationTime = DateTime.now().plusSeconds(60).toDate();

  GoogleCredentials credentials =
      GoogleCredentials.create(new AccessToken(accessToken, expirationTime));
  StackdriverTraceExporter.createAndRegister(
      StackdriverTraceConfiguration.builder()
          .setProjectId("MyStackdriverProjectId")
          .setCredentials(credentials)
          .build());
}

App Engine flexible environment

On App Engine flexible environment, the Stackdriver Trace API access scope is enabled by default, and the OpenCensus client library can be used without providing credentials or a project ID.

App Engine standard environment

On App Engine standard environment, the Stackdriver Trace API access scope is enabled by default, and the OpenCensus client library can be used without providing credentials or a project ID.

GKE

To use Trace with GKE, add the trace.append OAuth access scope when you create your cluster.

To create a cluster using gcloud, do the following:

  1. (Optional) Update gcloud to the latest version:
    gcloud components update
  2. Set your default project ID:
    gcloud config set project [PROJECT_ID]
  3. If you're working with zonal clusters, set your default compute zone:
    gcloud config set compute/zone [COMPUTE_ZONE]
  4. If you're working with regional clusters, set your default compute region:
    gcloud config set compute/region [COMPUTE_REGION]
  5. Issue the create command:
    gcloud container clusters create example-cluster-name --scopes https://www.googleapis.com/auth/trace.append

For more detailed information on creating a cluster, see Creating a cluster.

Compute Engine

For Compute Engine VM instances, you need to explicitly enable the trace.append Stackdriver Trace API access scope for each VM instance. When creating a new instance through the Google Cloud Platform Console, select the following values in the Identity and API access section of the Create an instance panel:

  1. Select Compute Engine default service account for Service account
  2. Select Allow full access to all Cloud APIs for Access Scopes

To use something other than the Compute Engine default service account see the Creating and enabling service accounts for instances and Running locally and elsewhere sections. The important thing is that the service account you use has the Cloud Trace Agent role.

Running locally and elsewhere

To run Stackdriver Trace outside of GCP you must supply your GCP project ID and appropriate service account credentials directly to OpenCensus client library . Your service account must contain the Cloud Trace agent role. For instructions, see Creating a service account.

Project ID

Provide a project ID to the OpenCensus as shown in Configuring the Stackdriver exporter. We recommend that you set the environment variable GOOGLE_CLOUD_PROJECT to your project ID and modify your application to read this variable. For Java, the latter step is not mandatory as the google-cloud-java library, which is invoked by OpenCensus, reads and uses this environment variable when it's available. See google-cloud-library specifying a project id, for more information:

Linux or macOS

export GOOGLE_CLOUD_PROJECT=your-project-id

Windows

set GOOGLE_CLOUD_PROJECT=your-project-id

PowerShell:

$env:GOOGLE_CLOUD_PROJECT="your-project-id"

Credentials

GCP client libraries use Application default credentials (ADC) to find your application's credentials. You provide credentials to the OpenCensus client library by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable:

Linux/macOS

    export GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

Windows

    set GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

PowerShell:

    $env:GOOGLE_APPLICATION_CREDENTIALS="path-to-your-service-accounts-private-key"

Viewing the traces

After deployment, you can view the traces in the GCP Console Trace Viewer.

Go to the Trace Viewer page

Was this page helpful? Let us know how we did:

Send feedback about...

Stackdriver Trace
Need help? Visit our support page.