Setting up Stackdriver Trace for Node.js

You can enable Stackdriver Trace for Node.js applications by using the Stackdriver Trace library for Node.js.

Installing the client library

  1. Before installing the Stackdriver Trace library for Node.js, make sure you've prepared your environment for Node.js development.

  2. To install the Stackdriver Trace library for Node.js, use npm:

    npm install --save @google-cloud/trace-agent
  3. Import the Stackdriver Trace library for Node.js at the top of your application's main script or entry point before any other code:

    require('@google-cloud/trace-agent').start();

For more information or to report issues with the Stackdriver Trace library for Node.js, see the agent's cloud-trace-nodejs GitHub repository.

Configuring the client library

You can customize the behavior of the Stackdriver Trace library for Node.js. See the library's configuration on GitHub for a list of configuration options that you can pass to the library's start method by using an options object.

The following example demonstrates specifying the Google Cloud project ID and setting the path to your credential file. These two statements are optional when you're running on Google Cloud:

require('@google-cloud/trace-agent').start({
  projectId: 'your-project-id',
  keyFilename: '/path/to/key.json'
});

If you're running on Google Cloud infrastructure, then you don't need to set projectId to your Google Cloud project ID. If you don't set this field, the client library for Node.js 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.

Regardless of your infrastructure, for Node.js, when you don't explicitly set the Google Cloud project ID, the cloud-trace-nodejs library automatically determines if the environment variable GCLOUD_PROJECT is set, and if so, the library uses the value of GCLOUD_PROJECT as your Google Cloud project ID. For more information on the discovery file, go to cloud-trace-nodejs/src/index. To set the environment variable, do the following:

Linux or macOS

export GCLOUD_PROJECT=your-project-id

Windows

set GCLOUD_PROJECT=your-project-id

PowerShell:

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

Configuring your platform

You can use Trace on Google Cloud and when your application runs outside of Google Cloud.

Running on Google Cloud

When your application is running on Google Cloud, your application is automatically authenticated and you don't need to provide authentication credentials. However, you do need to ensure that your Google Cloud platform has the Stackdriver Trace API access scope enabled.

For the following configurations, the default settings for the access scopes have the Stackdriver Trace API enabled:

  • App Engine flexible environment
  • App Engine standard environment

  • Google Kubernetes Engine

  • Compute Engine

If you use custom access scopes, then you must ensure that Stackdriver Trace API access scope enabled. For gcloud users, specify access scopes using the --scopes flag and include the trace.append Stackdriver Trace API access scope. For example, to create a GKE cluster with only the Stackdriver 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

When your application is running outside of Google Cloud, 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"

Sample application

if (process.env.NODE_ENV === 'production') {
  require('@google-cloud/trace-agent').start();
}

const express = require('express');
const got = require('got');

const app = express();
const DISCOVERY_URL = 'https://www.googleapis.com/discovery/v1/apis';

// This incoming HTTP request should be captured by Trace
app.get('/', async (req, res) => {
  // This outgoing HTTP request should be captured by Trace
  try {
    const { body } = await got(DISCOVERY_URL, { json: true });
    const names = body.items.map((item) => item.name);
    res
      .status(200)
      .send(names.join('\n'))
      .end();
  }
  catch (err) {
    console.error(err);
    res
      .status(500)
      .end();
  }
});

// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

Viewing the traces

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

Go to the Trace Viewer page

Resources

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

Send feedback about...

Stackdriver Trace Documentation
Need help? Visit our support page.