Setting up Cloud Trace for Java

You can enable Cloud Trace for Java applications by using OpenCensus. OpenCensus is a set of instrumentation libraries for collecting trace and metric data that work with multiple backends. For the latest details about OpenCensus for Java, along with additional documentation and examples, go to census-instrumentation/opencensus-java.

Installing the library

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

Maven

<dependency>
  <groupId>io.opencensus</groupId>
  <artifactId>opencensus-api</artifactId>
  <version>0.28.2</version>
</dependency>
<dependency>
  <groupId>io.opencensus</groupId>
  <artifactId>opencensus-exporter-trace-stackdriver</artifactId>
  <version>0.28.2</version>
</dependency>
<dependency>
  <groupId>io.opencensus</groupId>
  <artifactId>opencensus-impl</artifactId>
  <version>0.28.2</version>
  <scope>runtime</scope>
</dependency>
<dependency>
   <groupId>joda-time</groupId>
   <artifactId>joda-time</artifactId>
   <version>2.10.6</version>
</dependency>

Gradle

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

Configuring the Stackdriver exporter

To export the collected Trace data, use a StackdriverTraceExporter object:

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

If you are running on Google Cloud infrastructure, then you don't need to call setProjectID and supply your Google Cloud project ID. If you don't set this field, the client library for Java automatically gathers this data from a Google Cloud metadata server.

If you aren't running on Google Cloud infrastructure, then you must supply your Google Cloud project ID to your application.

When you don't explicitly set the Google Cloud project ID, the google-cloud Java library automatically determines whether the environment variable GOOGLE_CLOUD_PROJECT is set. If this variable is set, the library uses the value of GOOGLE_CLOUD_PROJECT as your Google Cloud project ID.

For more information, go to google-cloud-library specifying a project id. To set the environment variable, do the following:

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"

Add a custom Trace span

While the OpenCensus library contains automatic integrations for several popular web frameworks and RPC frameworks, you can also create custom 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!");
  // ...
}

Configuring integration with Cloud Logging

For information on how to send Cloud Trace data to Cloud Logging, see Integrating with Cloud Logging.

Enabling full sampling

By default, out of 10,000 traces, only 1 trace is sampled.

In a developer environment, this sampling rate might be too slow to show you trace data. To sample all traces, you can use the alwaysSample option.

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

Overriding automatic authentication

You can override the automatic authentication and project selection. For example, the following sample illustrates how to create an exporter whose credentials expire 60 seconds from creation time:

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

Configuring 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 to provide authentication credentials in the form of a service account to the client library. However, you do need to ensure that your Google Cloud platform has the Cloud Trace API access scope enabled.

For the following configurations, the default access-scope settings enable the Cloud Trace API:

  • App Engine flexible environment
  • App Engine standard environment

  • Google Kubernetes Engine (GKE)

  • Compute Engine

If you use custom access scopes, then you must ensure that Cloud Trace API access scope is enabled. For gcloud users, specify access scopes using the --scopes flag and include the trace.append Cloud Trace API access scope. For example, to create a GKE cluster with only the 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 must provide authentication credentials in the form of a service account to the client library. The service account must contain the Cloud Trace agent role. For instructions, see Creating a service account.

Google Cloud client libraries use Application Default Credentials (ADC) to find your application's credentials. You provide these credentials 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 Cloud Console Trace Viewer.

Go to the Trace Viewer page

Troubleshooting

For information on troubleshooting issues with Cloud Trace, go to the Troubleshooting page.

Resources