Datadog Metrics Reporter
datadog-metrics is a Node.js library designed for buffering and reporting application metrics to Datadog via its HTTP API. It supports common metric types including gauges, increments, histograms, and distributions. The current stable version is 0.12.1, with a pre-release (0.13.0-pre.1) indicating a future focus on reducing the bundle size and resource footprint by decoupling from heavier official Datadog clients. The library features automatic metric flushing before process exit (since v0.12.1), automatic retries for failed submissions (since v0.12.0), and includes built-in TypeScript definitions (since v0.11.0). Its release cadence is moderate, with significant feature updates often accompanied by breaking changes.
Common errors
-
Error: Datadog API key is not configured. Set the 'DD_API_KEY' environment variable or pass an 'apiKey' option.
cause The Datadog API key was not provided during initialization.fixSet the `DD_API_KEY` environment variable or explicitly pass an `apiKey` string in the options object to `metrics.init()` or `new BufferedMetricsLogger()`. -
TypeError: metrics.gauge is not a function (or increment/histogram/distribution)
cause Attempted to use metric reporting functions (e.g., `metrics.gauge()`) before `metrics.init()` has been called.fixEnsure `metrics.init()` is called and completes successfully before any other metric reporting functions are invoked on the global `metrics` object. -
Error: The 'metrics' object has already been initialized.
cause The `metrics.init()` function was called multiple times, which is not allowed for the global metrics object.fixEnsure `metrics.init()` is called only once in your application's lifecycle. If you need multiple independent loggers, use `new BufferedMetricsLogger()` instead.
Warnings
- breaking The minimum required Node.js version has been bumped from v12.0.0 to v14.0.0.
- breaking The `code` property on `AuthorizationError` instances has been changed to `DATADOG_METRICS_AUTHORIZATION_ERR`.
- gotcha Since v0.12.1, metrics are automatically flushed before the process exits. However, if `flushIntervalSeconds` is set to `0` or `process.exit()` is called, manual flushing via `metrics.flush()` is still required to guarantee all metrics are sent.
- breaking Asynchronous actions, such as `flush()`, now exclusively use Promises instead of callbacks. Callback arguments are no longer supported.
- breaking The `DatadogReporter` constructor now requires an options object instead of positional arguments. This primarily affects users directly instantiating the reporter.
- deprecated Built-in TypeScript definitions were introduced in v0.11.0. The separate `@types/datadog-metrics` package is no longer needed and should be removed from your `devDependencies`.
- gotcha The option for configuring histogram aggregates was previously misdocumented and typed as `aggregations`. It has been corrected to `aggregates`.
Install
-
npm install datadog-metrics -
yarn add datadog-metrics -
pnpm add datadog-metrics
Imports
- init
const init = require('datadog-metrics').init;import { init } from 'datadog-metrics'; - BufferedMetricsLogger
import BufferedMetricsLogger from 'datadog-metrics';
import { BufferedMetricsLogger } from 'datadog-metrics'; - metrics global object
import metrics from 'datadog-metrics';
import * as metrics from 'datadog-metrics';
Quickstart
import { init, BufferedMetricsLogger } from 'datadog-metrics';
// Initialize the global metrics object
init({
apiKey: process.env.DD_API_KEY ?? '',
appKey: process.env.DD_APP_KEY ?? '', // Optional, for advanced features/error details
host: 'my-app-server',
prefix: 'my_app.',
tags: ['env:production', 'region:us-east-1'],
flushIntervalSeconds: 15,
// Optional: configure to use custom logger for more control
// logger: console,
});
// Send some metrics using the global instance
metrics.gauge('user_sessions', 1234, ['browser:chrome']);
metrics.increment('request_count', 1, ['status:200']);
metrics.histogram('api_response_time', 150.5, ['endpoint:/data']);
metrics.distribution('task_duration_ms', 55.2, ['task_name:process_batch']);
console.log('Metrics sent via global instance.');
// Create and use a separate buffered logger instance
const customLogger = new BufferedMetricsLogger({
apiKey: process.env.DD_API_KEY ?? '',
host: 'custom-worker',
prefix: 'worker_process.',
tags: ['worker_id:42', 'queue:high_prio'],
});
customLogger.gauge('queue_depth', 5);
customLogger.increment('job_processed');
console.log('Metrics sent via custom logger instance.');
// Manual flush (optional, auto-flush on exit since v0.12.1)
// In a real application, you might want to wait for these promises
Promise.all([
metrics.flush(),
customLogger.flush()
]).then(() => {
console.log('All metrics manually flushed.');
}).catch(err => {
console.error('Error flushing metrics:', err);
});