Registry / observability / datadog-metrics

datadog-metrics

JSON →
library0.0.0jsnpmunverified

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.

npm install datadog-metrics
INSTALL
IMPORT
SIG · DATADOG-METRICS
D
datadog-metrics
observabilityjavascriptv0.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

init
import { init } from 'datadog-metrics';
const init = require('datadog-metrics').init;
Initializes the global metrics object. For CommonJS, you'd typically `const metrics = require('datadog-metrics'); metrics.init(...)` then use `metrics.gauge` etc.
BufferedMetricsLogger
import { BufferedMetricsLogger } from 'datadog-metrics';
import BufferedMetricsLogger from 'datadog-metrics';
This is a named export for creating independent metric loggers. Correctly typed as a class since v0.11.4.
metrics global object
import * as metrics from 'datadog-metrics';
import metrics from 'datadog-metrics';
After calling `metrics.init()`, functions like `metrics.gauge()` and `metrics.increment()` are available directly on the imported `metrics` object.

Demonstrates initializing the global metrics reporter and sending various metric types (gauge, increment, histogram, distribution). Also shows how to create and use a separate BufferedMetricsLogger instance for isolated metric collection, and how to perform an explicit flush operation.

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); });
Debug
Known issues
breakingThe minimum required Node.js version has been bumped from v12.0.0 to v14.0.0.
fix
Ensure your Node.js environment is at least v14.0.0 before upgrading to v0.13.0 or later.
affects: >=0.13.0-pre.1
breakingThe `code` property on `AuthorizationError` instances has been changed to `DATADOG_METRICS_AUTHORIZATION_ERR`.
fix
Update any error handling logic that inspects the `code` property of `AuthorizationError` instances to use the new string literal.
affects: >=0.13.0-pre.1
gotchaSince 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.
fix
For critical metrics or specific exit scenarios, explicitly call `metrics.flush()` and await its completion before `process.exit()` or when `flushIntervalSeconds` is zero.
affects: >=0.12.1
breakingAsynchronous actions, such as `flush()`, now exclusively use Promises instead of callbacks. Callback arguments are no longer supported.
fix
Refactor any asynchronous operations to use Promise-based syntax (e.g., `async/await` or `.then/.catch`) instead of passing callback functions.
affects: >=0.12.0
breakingThe `DatadogReporter` constructor now requires an options object instead of positional arguments. This primarily affects users directly instantiating the reporter.
fix
If you are directly using `new DatadogReporter(...)`, update your constructor call to pass a single options object.
affects: >=0.12.0
deprecatedBuilt-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`.
fix
Remove `@types/datadog-metrics` from your `package.json` and `npm install` or `yarn install`.
affects: >=0.11.0
gotchaThe option for configuring histogram aggregates was previously misdocumented and typed as `aggregations`. It has been corrected to `aggregates`.
fix
Ensure you are using the `aggregates` option when configuring histogram behavior, not `aggregations`.
affects: <0.11.2
Errors
Common errors & fixes
Error: Datadog API key is not configured. Set the 'DD_API_KEY' environment variable or pass an 'apiKey' option.
The Datadog API key was not provided during initialization.
fix
Set 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)
Attempted to use metric reporting functions (e.g., `metrics.gauge()`) before `metrics.init()` has been called.
fix
Ensure `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.
The `metrics.init()` function was called multiple times, which is not allowed for the global metrics object.
fix
Ensure `metrics.init()` is called only once in your application's lifecycle. If you need multiple independent loggers, use `new BufferedMetricsLogger()` instead.
Upgrade
Version history
0.0.0latest on npm
Audit
Dependencies
datadog-api-clientrequiredUsed for interacting with the Datadog API in versions prior to 0.13.0. This dependency is slated for removal in v0.13.0 and newer to reduce package size.
Agent activity
18 hits · last 30 days
node
14
OpenAI (training)
2
Bingbot
1
Resources