Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@google-cloud/trace-agent

googleapis370.2kApache-2.08.0.0TypeScript support: included

Node.js Support for StackDriver Trace

google, tracing, profiling

readme

Google Cloud Platform logo

Cloud Trace: Node.js Client

release level npm version

Node.js Support for StackDriver Trace

A comprehensive list of changes in each version may be found in the CHANGELOG.

Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Table of contents:

Quickstart

Before you begin

  1. Select or create a Cloud Platform project.
  2. Enable the Cloud Trace API.
  3. Set up authentication with a service account so you can access the API from your local workstation.

Installing the client library

npm install @google-cloud/trace-agent

Warning

cloud-trace-nodejs is in maintenance mode. This means that we'll continue to fix bugs add add security patches. We'll consider merging new feature contributions (depending on the anticipated maintenance cost). But we won't develop new features ourselves.

In particular, we will not add support for new major versions of libraries.

We encourage users to migrate to OpenTelemetry JS Instrumentation instead.

This module provides automatic tracing for Node.js applications with Cloud Trace. Cloud Trace is a feature of Google Cloud Platform that collects latency data (traces) from your applications and displays it in near real-time in the Google Cloud Console.

Cloud Trace Overview

Usage

The Trace Agent supports Node 8+.

Note: Using the Trace Agent requires a Google Cloud Project with the Cloud Trace API enabled and associated credentials. These values are auto-detected if the application is running on Google Cloud Platform. If your application is not running on GCP, you will need to specify the project ID and credentials either through the configuration object, or with environment variables. See Setting Up Cloud Trace for Node.js for more details.

Note: The Trace Agent does not currently work out-of-the-box with Google Cloud Functions (or Firebase Cloud Functions). See #725 for a tracking issue and details on how to work around this.

Simply require and start the Trace Agent as the first module in your application:

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

If you want to use import, you will need to do the following to import all required types:

import * as TraceAgent from '@google-cloud/trace-agent';

Optionally, you can pass a configuration object to the start() function as follows:

require('@google-cloud/trace-agent').start({
  samplingRate: 5, // sample 5 traces per second, or at most 1 every 200 milliseconds.
  ignoreUrls: [ /^\/ignore-me/ ] // ignore the "/ignore-me" endpoint.
  ignoreMethods: [ 'options' ] // ignore requests with OPTIONS method (case-insensitive).
});
// ...

The object returned by start() may be used to create custom trace spans:

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

app.get('/', async () => {
  const customSpan = tracer.createChildSpan({name: 'my-custom-span'});
  await doSomething();
  customSpan.endSpan();
  // ...
});

What gets traced

The trace agent can do automatic tracing of the following web frameworks:

The agent will also automatically trace RPCs from the following modules:

  • Outbound HTTP requests through http, https, and http2 core modules
  • grpc client (version ^1.1)
  • mongodb-core (version 1 - 3)
  • mongoose (version 4 - 5)
  • mysql (version ^2.9)
  • mysql2 (version 1)
  • pg (versions 6 - 7)
  • redis (versions 0.12 - 2)

You can use the Custom Tracing API to trace other modules in your application.

To request automatic tracing support for a module not on this list, please file an issue. Alternatively, you can write a plugin yourself.

Tracing Additional Modules

To load an additional plugin, specify it in the agent's configuration:

require('@google-cloud/trace-agent').start({
  plugins: {
    // You may use a package name or absolute path to the file.
    'my-module': '@google-cloud/trace-agent-plugin-my-module',
    'another-module': path.join(__dirname, 'path/to/my-custom-plugins/plugin-another-module.js')
  }
});

This list of plugins will be merged with the list of built-in plugins, which will be loaded by the plugin loader. Each plugin is only loaded when the module that it patches is loaded; in other words, there is no computational overhead for listing plugins for unused modules.

Custom Tracing API

The custom tracing API can be used to create custom trace spans. A span is a particular unit of work within a trace, such as an RPC request. Spans may be nested; the outermost span is called a root span, even if there are no nested child spans. Root spans typically correspond to incoming requests, while child spans typically correspond to outgoing requests, or other work that is triggered in response to incoming requests. This means that root spans shouldn't be created in a context where a root span already exists; a child span is more suitable here. Instead, root spans should be created to track work that happens outside of the request lifecycle entirely, such as periodically scheduled work. To illustrate:

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

app.get('/', (req, res) => {
  // We are in an automatically created root span corresponding to a request's
  // lifecycle. Here, we can manually create and use a child span to track the
  // time it takes to open a file.
  const readFileSpan = tracer.createChildSpan({ name: 'fs.readFile' });
  fs.readFile('/some/file', 'utf8', (err, data) => {
    readFileSpan.endSpan();
    res.send(data);
  });
});

// For any significant work done _outside_ of the request lifecycle, use
// runInRootSpan.
tracer.runInRootSpan({ name: 'init' }, rootSpan => {
  // ...
  // Be sure to call rootSpan.endSpan().
});

For any of the web frameworks for which we provide built-in plugins, a root span is automatically started whenever an incoming request is received (in other words, all middleware already runs within a root span). If you wish to record a span outside of any of these frameworks, any traced code must run within a root span that you create yourself.

Accessing the API

Calling the start function returns an instance of Tracer, which provides an interface for tracing:

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

It can also be retrieved by subsequent calls to get elsewhere:

// after start() is called
const tracer = require('@google-cloud/trace-agent').get();

A Tracer object is guaranteed to be returned by both of these calls, even if the agent is disabled.

A fully detailed overview of the Tracer object is available here.

How does automatic tracing work?

The Trace Agent automatically patches well-known modules to insert calls to functions that start, label, and end spans to measure latency of RPCs (such as mysql, redis, etc.) and incoming requests (such as express, hapi, etc.). As each RPC is typically performed on behalf of an incoming request, we must make sure that this association is accurately reflected in span data. To provide a uniform, generalized way of keeping track of which RPC belongs to which incoming request, we rely on async_hooks to keep track of the "trace context" across asynchronous boundaries.

async_hooks works well in most cases. However, it does have some limitations that can prevent us from being able to properly propagate trace context:

  • It is possible that a module does its own queuing of callback functions – effectively merging asynchronous execution contexts. For example, one may write an http request buffering library that queues requests and then performs them in a batch in one shot. In such a case, when all the callbacks fire, they will execute in the context which flushed the queue instead of the context which added the callbacks to the queue. This problem is called the pooling problem or the user-space queuing problem, and is a fundamental limitation of JavaScript. If your application uses such code, you will notice that RPCs from many requests are showing up under a single trace, or that certain portions of your outbound RPCs do not get traced. In such cases we try to work around the problem through monkey patching, or by working with the library authors to fix the code to properly propagate context. However, finding problematic code is not always trivial.
  • The async_hooks API has issues tracking context around await-ed "thenables" (rather than real promises). Requests originating from the body of a then implementation in such a user-space "thenable" may not get traced. This is largely an unconventional case but is present in the knex module, which monkeypatches the Bluebird Promise's prototype to make database calls. If you are using knex (esp. the raw function), see #946 for more details on whether you are affected, as well as a suggested workaround.

Tracing bundled or webpacked server code.

unsupported

The Trace Agent does not support bundled server code, so bundlers like webpack or @zeit/ncc will not work.

Samples

Samples are in the samples/ directory. Each sample's README.md has instructions for running its sample.

Sample Source Code Try it
App source code Open in Cloud Shell
Snippets source code Open in Cloud Shell

The Cloud Trace Node.js Client API Reference documentation also contains samples.

Supported Node.js Versions

Our client libraries follow the Node.js release schedule. Libraries are compatible with all current active and maintenance versions of Node.js. If you are using an end-of-life version of Node.js, we recommend that you update as soon as possible to an actively supported LTS version.

Google's client libraries support legacy versions of Node.js runtimes on a best-efforts basis with the following warnings:

  • Legacy versions are not tested in continuous integration.
  • Some security patches and features cannot be backported.
  • Dependencies cannot be kept up-to-date.

Client libraries targeting some end-of-life versions of Node.js are available, and can be installed through npm dist-tags. The dist-tags follow the naming convention legacy-(version). For example, npm install @google-cloud/trace-agent@legacy-8 installs client libraries for versions compatible with Node.js 8.

Versioning

This library follows Semantic Versioning.

This library is considered to be in preview. This means it is still a work-in-progress and under active development. Any release is subject to backwards-incompatible changes at any time.

More Information: Google Cloud Platform Launch Stages

Contributing

Contributions welcome! See the Contributing Guide.

Please note that this README.md, the samples/README.md, and a variety of configuration files in this repository (including .nycrc and tsconfig.json) are generated from a central template. To edit one of these files, make an edit to its templates in directory.

License

Apache Version 2.0

See LICENSE

changelog

Changelog

8.0.0 (2024-02-07)

⚠ BREAKING CHANGES

  • upgrade to Node 14 (#1517)

Features

Bug Fixes

Miscellaneous Chores

7.1.2 (2022-09-08)

Bug Fixes

7.1.1 (2022-08-29)

Bug Fixes

7.1.0 (2022-08-10)

Features

  • mysql: update MySQL wrapper to propagate fields. (#1412) (1b92362)

7.0.0 (2022-08-10)

⚠ BREAKING CHANGES

  • update library to use Node 12 (#1442)
  • drop support for node.js 8.x (#1239)
  • When initialized with clsMechanism: 'none', calling Tracer#createChildSpan will potentially result in a warning, as these spans are considered to be uncorrelated. To ensure that warnings do not occur, disable any plugins that patch modules that create outgoing RPCs (gRPC, HTTP client and database calls). (Use of the custom span API Tracer#createChildSpan is not recommended in this configuration -- use RootSpan#createChildSpan instead.)
  • This change modifies/removes APIs that assume a particular format for trace context headers; in other words, any place where the user would deal with a stringified trace context, they would now deal with a TraceContext object instead. This affects three APIs: getResponseTraceContext (input/output has changed from string to TraceContext), createRootSpan (input RootSpanOptions now accepts a TraceContext instead of a string in the traceContext field), and Span#getTraceContext (output has changed from string to TraceContext).
  • contextHeaderBehavior and ignoreContextHeader now act independently of one another. The former controls how a sampling decision is made based on incoming context header, and the latter controls whether trace context is propagated to the current request.
  • upgrade engines field to >=8.10.0 (#1011)
  • TraceAgent has been renamed to Tracer. In plugins, Patch has been renamed Monkeypatch, and Patch is now Monkeypatch|Intercept (this is a rename of Instrumentation). There are no user-visible JS changes.
  • The change in distributed trace context propagation across gRPC is not backwards-compatible. In other words, distributed tracing will not work between two Node instances communicating using gRPC with v2 and v3 of the Trace Agent, respectively.
  • This commit drops support for Node 4 and 9.

Features

  • add config.disableUntracedModulesWarn (#1070) (f688e33)
  • add contextHeaderBehavior option (#900) (199cb42)
  • add getProjectId and getCurrentRootSpan (#782) (f7ae770)
  • add ignoreMethods option (#920) (67ddb8f)
  • add options to set the cls mechanism to async-hooks or async-listener (#741) (f34aac5)
  • add rootSpan.createChildSpan and change none CLS semantics (#731) (d0009ff)
  • add rootSpanNameOverride option (#826) (a03e7b2)
  • add singular cls option (#748) (000643f)
  • allow "disabling" cls, and relax requirements for creating root spans (#728) (5d000e9)
  • allow timestamps to be passed to endSpan (#747) (319642a)
  • allow users to specify a trace policy impl (#1027) (b37aa3d)
  • downgrade soft/hard span limit logs to warn level (#1269) (3f55458)
  • emit an error log on potential memory leak scenario (#870) (0072e5f)
  • expand version range for pg to 7.x (#701) (c8c5bfc)
  • hapi 17 tracing support (#710) (028032f)
  • implement (de)serialization of binary trace context (#812) (f96c827)
  • move ts target to es2018 from es2016 (#1280) (b33df71)
  • rename TraceAgent/TraceApi to Tracer (#815) (dde86d3)
  • support @hapi/hapi (#1108) (d545e93)
  • support child spans with tail latencies (#913) (d1de959)
  • support context propagation in bluebird (#872) (29bb15c)
  • support knex 0.16 (#940) (0b404a1)
  • support mongodb-core@3 (#760) (d227b6d)
  • support restify 8 (#1250) (f52fa4d)
  • support restify@7 (#917) (4b74f5a)
  • support tracing for untranspiled async/await in Node 8+ (#775) (30d0529)
  • support user-specified context header propagation (#1029) (28ecb16)
  • use small HTTP dependency (#858) (210dc3f)
  • use source-map-support wrapCallSite to apply source maps to call stacks (#1015) (c558455)
  • use well-known format for propagating trace context thru grpc (#814) (63b13ca)

Bug Fixes

  • add build/src/cls in output files (#736) (49a900a)
  • add log level to logger prefix (#875) (c19850d)
  • add support for pg 7 changes (#702) (f070636)
  • adjust async_hooks cls behavior (#734) (79ab435)
  • allow non-objects for plugins to disable automatic tracing (#720) (068260c)
  • allow sampling rate to be less than 1 (#896) (5220f9b)
  • always assign a trace ID to each request (#1033) (6b427ab)
  • apache license URL (#468) (#1232) (ac7e886)
  • avoid memory leaks due to undisposed promise resources (#885) (8454389)
  • build: migrate to using main branch (#1373) (f065f97)
  • class-ify cls implementations (#708) (132db9b)
  • copy credentials in internal config (#1052) (8930df3)
  • delete cache as it is not working anyways (#864) (13f617a)
  • deps: TypeScript 3.7.0 causes breaking change in typings (#1163) (6448c94)
  • deps: update dependency @google-cloud/common to ^0.23.0 (#834) (ee350a2)
  • deps: update dependency @google-cloud/common to ^0.26.0 (#892) (8c6a614)
  • deps: update dependency @google-cloud/common to ^0.27.0 (#925) (10bb78b)
  • deps: update dependency @google-cloud/common to ^0.28.0 (#941) (96863e7)
  • deps: update dependency @google-cloud/common to ^0.29.0 (#947) (bc98aa3)
  • deps: update dependency @google-cloud/common to ^0.30.0 (#961) (2335934)
  • deps: update dependency @google-cloud/common to ^0.31.0 (#963) (7b84349)
  • deps: update dependency @google-cloud/common to ^0.32.0 (#993) (670ac64)
  • deps: update dependency @google-cloud/common to v1 (#1023) (244633e)
  • deps: update dependency @google-cloud/common to v2 (#1038) (23a990a)
  • deps: update dependency @google-cloud/common to v3 (#1225) (3609201)
  • deps: update dependency @google-cloud/common to v4 (#1448) (6f33c17)
  • deps: update dependency @google-cloud/datastore to v2 (#893) (a0a741d)
  • deps: update dependency @google-cloud/datastore to v3 (#951) (a821462)
  • deps: update dependency @google-cloud/datastore to v4 (#1028) (c63bb14)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.13 (#1030) (4c79b4f)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.14 (#1045) (08a1dd6)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.16 (#1079) (e48dc54)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.17 (#1112) (5636738)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.18 (#1140) (8d39dd2)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.19 (#1158) (76b2162)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.20 (#1199) (4752aec)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.21 (#1227) (4cd9088)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.22 (#1277) (82725a2)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.1.0 (#1368) (29a0fba)
  • deps: update dependency builtin-modules to v3 (#810) (1fbbbf9)
  • deps: update dependency gcp-metadata to ^0.7.0 (#807) (94b8e3b)
  • deps: update dependency gcp-metadata to ^0.9.0 (#897) (b56926a)
  • deps: update dependency gcp-metadata to v1 (#975) (ea9cb4b)
  • deps: update dependency gcp-metadata to v2 (#1022) (9d3b9e5)
  • deps: update dependency gcp-metadata to v3 (#1115) (94c6dae)
  • deps: update dependency gcp-metadata to v4 (#1219) (caf67be)
  • deps: update dependency gcp-metadata to v5 (#1446) (2f264d0)
  • deps: update dependency google-auth-library to v7 (#1335) (4fc7c7c)
  • deps: update dependency google-auto-auth to ^0.10.0 (#808) (93b7235)
  • deps: update dependency got to v10 (#1162) (432404d)
  • deps: update dependency got to v11 (#1248) (03ff0f4)
  • deps: update dependency got to v8 (#811) (fd138fc)
  • deps: update dependency hard-rejection to v2 (#985) (5900847)
  • deps: update dependency require-in-the-middle to v4 (#984) (8abf8c8)
  • deps: update dependency require-in-the-middle to v5 (#1099) (1d49cb6)
  • deps: update dependency semver to v6 (fae65bd)
  • deps: update dependency semver to v7 (#1168) (b5811b5)
  • deps: update dependency uuid to v7 (#1200) (129aead)
  • deps: update dependency uuid to v8 (#1255) (ad02efb)
  • deps: use the latest extend (#1096) (abc4b4e)
  • docs: add jsdoc-region-tag plugin (#1151) (ee19cb9)
  • docs: remove reference doc anchor (#1109) (801e495)
  • docs: standardize README and add repo metadata (#1095) (c24faa3)
  • don't let trace context injection throw (#989) (50421a5)
  • enable tracing on original client method names (#874) (497c760)
  • end child spans correctly in pg (#930) (1a20b7c)
  • fix https tracing breakage in node <9 and rewrite http tests (#717) (a3ea16d)
  • fix log messages and ignore falsey env vars (#724) (d0337fa)
  • fix tracing not working in mongoose 3.3+ (#1134) (fe7e925)
  • fixup for node 8.11.2 (#755) (807d4ad)
  • force http and https clients to be patched (#1084) (3ac0b90)
  • handle Node 10 style http requests (#1233) (511b21c)
  • handle pg 7.16.0+ undefined Result#fields (#1179) (21dbb0d)
  • improve logs from the trace writer (#800) (4ac6ded)
  • include more type definitions (#841) (eb98fa1)
  • inject context http headers early if expect header exists (#766) (bc877a5)
  • make no option flags behave the same as o=1 (#910) (67379f8)
  • output 'noPluginName' in trace-api log messages where pluginName is undefined (#958) (6793b09)
  • package: update @google-cloud/common to version 0.20.3 (#796) (fa8f4a4), closes #773
  • Prevent filtered traces from biasing the sample rate (#1018) (1832473)
  • restore context when a function run with a given context throws (#727) (edb8135)
  • sample app TypeError (#1257) (1ac424e)
  • support tracing awaited mongoose queries (#1007) (deb2a44)
  • swap log levels for two log points (#882) (e73af2b)
  • tests: Hex value assertion was used on decimal string (#1271) (5def451)
  • treat instanceId metadata as a number (#713) (1434d5d)
  • typeo in nodejs .gitattribute (#1290) (24deca8)
  • unpin @types/node and account for new http.request signatures (#1120) (bd9863b)
  • update @google-cloud/common dependency to 0.25.3 (#871) (23a0616)
  • Update README partials to mention how to use import (#1400) (da8741b)
  • update teeny-request dep (#928) (1d7c4dc)
  • update to @google-cloud/common@0.19 (#772) (3f3f667)
  • use req.ip in express and koa plugin (#944) (126bc75)
  • warn if tracing might not work instead of err (#1068) (8bdd946)
  • wrap gRPC server async handlers (#954) (8b8bd94)

Performance Improvements

Miscellaneous Chores

Build System

6.0.0 (2022-06-20)

⚠ BREAKING CHANGES

  • update library to use Node 12 (#1442)

Bug Fixes

  • deps: update dependency gcp-metadata to v5 (#1446) (2f264d0)

Build System

5.1.6 (2021-11-16)

Bug Fixes

  • Update README partials to mention how to use import (#1400) (da8741b)

5.1.5 (2021-08-19)

Bug Fixes

  • deps: update dependency @opencensus/propagation-stackdriver to v0.1.0 (#1368) (29a0fba)

5.1.4 (2021-08-19)

Bug Fixes

5.1.3 (2021-02-09)

Bug Fixes

  • deps: update dependency google-auth-library to v7 (#1335) (4fc7c7c)

5.1.2 (2021-02-04)

Performance Improvements

5.1.1 (2020-09-12)

Bug Fixes

5.1.0 (2020-06-11)

Features

Bug Fixes

  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.22 (#1277) (82725a2)

5.0.0 (2020-06-04)

⚠ BREAKING CHANGES

  • drop support for node.js 8.x (#1239)

Features

Bug Fixes

Build System

4.2.5 (2020-01-06)

Bug Fixes

4.2.4 (2019-12-06)

Bug Fixes

  • deps: TypeScript 3.7.0 causes breaking change in typings (#1163) (6448c94)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.19 (#1158) (76b2162)
  • deps: update dependency got to v10 (#1162) (432404d)
  • docs: add jsdoc-region-tag plugin (#1151) (ee19cb9)

4.2.3 (2019-11-11)

Bug Fixes

  • deps: update dependency source-map-support to v0.5.16 (#1148) (3947e5b)

4.2.2 (2019-10-10)

Bug Fixes

  • fix tracing not working in mongoose 3.3+ (#1134) (fe7e925)
  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.18 (#1140) (8d39dd2)

4.2.1 (2019-10-02)

Bug Fixes

  • deps: update dependency gcp-metadata to v3 (#1115) (94c6dae)
  • unpin @types/node and account for new http.request signatures (#1120) (bd9863b)

4.2.0 (2019-09-09)

Bug Fixes

  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.17 (#1112) (5636738)
  • deps: update dependency require-in-the-middle to v5 (#1099) (1d49cb6)
  • deps: use the latest extend (#1096) (abc4b4e)
  • docs: remove reference doc anchor (#1109) (801e495)

Features

4.1.1 (2019-08-05)

Bug Fixes

  • deps: update dependency @opencensus/propagation-stackdriver to v0.0.16 (#1079) (e48dc54)
  • docs: standardize README and add repo metadata (#1095) (c24faa3)
  • force http and https clients to be patched (#1084) (3ac0b90)