Gathering detailed insights and metrics for datadog-metrics
Gathering detailed insights and metrics for datadog-metrics
Gathering detailed insights and metrics for datadog-metrics
Gathering detailed insights and metrics for datadog-metrics
Buffered metrics reporting via the DataDog HTTP API
npm install datadog-metrics
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
142 Stars
214 Commits
58 Forks
6 Watching
3 Branches
17 Contributors
Updated on 28 Nov 2024
JavaScript (95.7%)
Shell (2.23%)
TypeScript (2.07%)
Cumulative downloads
Total Downloads
Last day
9.7%
370,006
Compared to previous day
Last week
6.5%
1,802,066
Compared to previous week
Last month
18.9%
7,183,077
Compared to previous month
Last year
45.2%
59,662,843
Compared to previous year
2
7
Buffered metrics reporting via the Datadog HTTP API.
Datadog-metrics lets you collect application metrics through Datadog's HTTP API. Using the HTTP API has the benefit that you don't need to install the Datadog Agent (StatsD). Just get an API key, install the module and you're ready to go.
The downside of using the HTTP API is that it can negatively affect your app's performance. Datadog-metrics solves this issue by buffering metrics locally and periodically flushing them to Datadog.
Datadog-metrics is compatible with Node.js v12 and later. You can install it with NPM:
1npm install datadog-metrics --save
Save the following into a file named example_app.js
:
1var metrics = require('datadog-metrics'); 2metrics.init({ host: 'myhost', prefix: 'myapp.' }); 3 4function collectMemoryStats() { 5 var memUsage = process.memoryUsage(); 6 metrics.gauge('memory.rss', memUsage.rss); 7 metrics.gauge('memory.heapTotal', memUsage.heapTotal); 8 metrics.gauge('memory.heapUsed', memUsage.heapUsed); 9}; 10 11setInterval(collectMemoryStats, 5000);
Run it:
1DATADOG_API_KEY=YOUR_KEY DEBUG=metrics node example_app.js
There's also a longer tutorial that walks you through setting up a monitoring dashboard on Datadog using datadog-metrics.
Make sure the DATADOG_API_KEY
environment variable is set to your Datadog
API key (you can also set it via the apiKey
option in code). You can find the API key under Integrations > APIs. Please note the API key is different from an application key. For more details, see Datadog’s “API and Application Keys” docs.
There are three ways to use this module to instrument an application. They differ in the level of control that they provide.
Just require datadog-metrics and you're ready to go. After that you can call
gauge
, increment
and histogram
to start reporting metrics.
1var metrics = require('datadog-metrics'); 2metrics.gauge('mygauge', 42);
If you want more control you can configure the module with a call to init
.
Make sure you call this before you use the gauge
, increment
and histogram
functions. See the documentation for init
below to learn more.
1var metrics = require('datadog-metrics'); 2metrics.init({ host: 'myhost', prefix: 'myapp.' }); 3metrics.gauge('mygauge', 42);
If you need even more control you can create one or more BufferedMetricsLogger
instances and manage them yourself:
1var metrics = require('datadog-metrics'); 2var metricsLogger = new metrics.BufferedMetricsLogger({ 3 site: 'datadoghq.eu', 4 apiKey: 'TESTKEY', 5 host: 'myhost', 6 prefix: 'myapp.', 7 flushIntervalSeconds: 15, 8 defaultTags: ['env:staging', 'region:us-east-1'], 9 onError (error) { 10 console.error('There was an error auto-flushing metrics:', error); 11 } 12}); 13metricsLogger.gauge('mygauge', 42);
metrics.init(options)
Where options
is an object and can contain the following:
host
: Sets the hostname reported with each metric. (optional)
prefix
: Sets a default prefix for all metrics. (optional)
flushIntervalSeconds
: How often to send metrics to Datadog. (optional)
flush()
manually.site
: Sets the Datadog "site", or server where metrics are sent. (optional)
datadoghq.com
.DATADOG_SITE
environment variable.apiKey
: Sets the Datadog API key. (optional)
DATADOG_API_KEY
by default.appKey
: Sets the Datadog application key. (optional)
DATADOG_APP_KEY
by default.defaultTags
: Default tags used for all metric reporting. (optional)
onError
: A function to call when there are asynchronous errors seding
buffered metrics to Datadog. It takes one argument (the error). (optional)
flush()
), the error will be
logged to stdout.histogram
: An object with default options for all histograms. This has the
same properties as the options object on the histogram()
method. Options
specified when calling the method are layered on top of this object.
(optional)reporter
: An object that actually sends the buffered metrics. (optional)
reporters.DatadogReporter
sends metrics to Datadog’s API, and is
the default.reporters.NullReporter
throws the metrics away. It’s useful for
tests or temporarily disabling your metrics.Example:
1metrics.init({ host: 'myhost', prefix: 'myapp.' });
Disabling metrics using NullReporter
:
1metrics.init({ host: 'myhost', reporter: metrics.NullReporter() });
Send metrics to a totally different service instead of Datadog:
1metrics.init({ 2 reporter: { 3 report(series, onSuccess, onError) { 4 // `series` is an array of metrics objects, formatted basically how the 5 // Datadog v1 metrics API and v1 distributions API want them. 6 fetch('https://my-datadog-like-api.com/series', { 7 method: 'POST', 8 body: JSON.stringify({ series }) 9 }) 10 .then(response => response.json()) 11 .then(() => onSuccess()) 12 .catch(onError); 13 } 14 } 15});
metrics.gauge(key, value[, tags[, timestamp]])
Record the current value of a metric. The most recent value in
a given flush interval will be recorded. Optionally, specify a set of
tags to associate with the metric. This should be used for sum values
such as total hard disk space, process uptime, total number of active
users, or number of rows in a database table. The optional timestamp
is in milliseconds since 1 Jan 1970 00:00:00 UTC, e.g. from Date.now()
.
Example:
1metrics.gauge('test.mem_free', 23);
metrics.increment(key[, value[, tags[, timestamp]]])
Increment the counter by the given value (or 1
by default). Optionally,
specify a list of tags to associate with the metric. This is useful for
counting things such as incrementing a counter each time a page is requested.
The optional timestamp is in milliseconds since 1 Jan 1970 00:00:00 UTC,
e.g. from Date.now()
.
Example:
1metrics.increment('test.requests_served'); 2metrics.increment('test.awesomeness_factor', 10);
metrics.histogram(key, value[, tags[, timestamp[, options]]])
Sample a histogram value. Histograms will produce metrics that
describe the distribution of the recorded values, namely the minimum,
maximum, average, median, count and the 75th, 85th, 95th and 99th percentiles.
Optionally, specify a list of tags to associate with the metric.
The optional timestamp is in milliseconds since 1 Jan 1970 00:00:00 UTC,
e.g. from Date.now()
.
Example:
1metrics.histogram('test.service_time', 0.248);
You can also specify an options object to adjust which aggregations and percentiles should be calculated. For example, to only calculate an average, count, and 99th percentile:
1metrics.histogram('test.service_time', 0.248, ['tag:value'], Date.now(), { 2 // Aggregates can include 'max', 'min', 'sum', 'avg', 'median', or 'count'. 3 aggregates: ['avg', 'count'], 4 // Percentiles can include any decimal between 0 and 1. 5 percentiles: [0.99] 6});
metrics.distribution(key, value[, tags[, timestamp]])
Send a distribution value. Distributions are similar to histograms (they create several metrics for count, average, percentiles, etc.), but they are calculated server-side on Datadog’s systems. This is much higher-overhead than histograms, and the individual calculations made from it have to be configured on the Datadog website instead of in the options for this package.
You should use this in environments where you have many instances of your
application running in parallel, or instances constantly starting and stopping
with different hostnames or identifiers and tagging each one separately is not
feasible. AWS Lambda or serverless functions are a great example of this. In
such environments, you also might want to use a distribution instead of
increment
or gauge
(if you have two instances of your app sending those
metrics at the same second, and they are not tagged differently or have
different host
names, one will overwrite the other — distributions will not).
Example:
1metrics.distribution('test.service_time', 0.248);
metrics.flush([onSuccess[, onError]])
Calling flush
sends any buffered metrics to Datadog. Unless you set
flushIntervalSeconds
to 0 it won't be necessary to call this function.
It can be useful to trigger a manual flush by calling if you want to make sure pending metrics have been sent before you quit the application process, for example.
Datadog-metrics uses the debug
library for logging at runtime. You can enable debug logging by setting
the DEBUG
environment variable when you run your app.
Example:
1DEBUG=metrics node app.js
Contributions are always welcome! For more info on how to contribute or develop locally, please see CONTRIBUTING.md
.
In Development:
Breaking Changes:
TBD
New Features:
TBD
Bug Fixes:
site
option via the DATADOG_SITE
environment variable. The apiHost
option was renamed to site
in v0.11.0, but the DATADOG_API_HOST
environment variable was accidentally left as-is. The old environment variable name is now deprecated, and will be removed at the same time as the apiHost
option is removed.Maintenance:
Map
instead of a plain object.0.11.4 (2024-11-10)
This release updates the TypeScript types for this project, and doesn’t include any changes to functionality. There are also no changes since v0.11.4-a.1.
Bug Fixes:
BufferedMetricsLogger
is now an actual class & type when you import it in TypeScript. That is, you can now do:
1import { BufferedMetricsLogger } from 'datadog-metrics'; 2 3function useLogger(logger: BufferedMetricsLogger) { 4 // ... 5}
Previously, you would have had to declare the type for logger
as typeof BufferedMetricsLogger.prototype
. (#120)
0.11.4-a.1 (2024-10-31)
This pre-release is meant for testing a fix for #119.
Bug Fixes:
BufferedMetricsLogger
is seen as an actual class & type when importing in TypeScript. (#120)0.11.3 (2024-10-31)
No changes in this release since v0.11.2. This fixes a publishing error with v0.11.3a1.
0.11.3a1 (2024-10-31)
Do not use this release.
0.11.2 (2024-06-25)
Fixes & Maintenance:
Fix types and documentation for the aggregates
option for histograms and the histogram.aggregates
option for the library as a whole. It was previously listed as aggregations
, which was incorrect. (Thanks to @Calyhre in #117.)
Improve documentation and add a more detailed error message about API keys vs. application keys. (#118)
0.11.1 (2023-09-28)
Fixes & Maintenance:
0.11.0 (2022-02-21)
New Features:
Built-in TypeScript definitions. If you use TypeScript, you no longer need to install separate type definitions from @types/datadog-metrics
— they’re now built-in. Please make sure to remove @types/datadog-metrics
from your dev dependencies.
Even if you’re writing regular JavaScript, you should now see better autocomplete suggestions and documentation in editors that support TypeScript definitions (e.g. VisualStudio Code, WebStorm).
Breaking Changes:
class
syntax internally. In most cases, you shouldn’t need to change anything. However, if you are calling BufferedMetricsLogger.apply(...)
or BufferedMetricsLogger.call(...)
, you’ll need to change your code to use new BufferedMetricsLogger(...)
instead.Deprecated Features:
The apiHost
option has been renamed to site
so that it matches up with Datadog docs and official packages. The old apiHost
name still works for now, but will be removed in the future.
The reporters.DataDogReporter
class has been renamed to reporters.DatadogReporter
(lower-case D in "dog") so that it correctly matches Datadog’s actual name. The old name still works, but will be removed in the future.
0.10.2 (2022-10-14)
This release includes several new features and bugfixes!
New Features:
Support for distribution metrics. You can now send distributions to Datadog by doing:
1const metrics = require('datadog-metrics'); 2metrics.distribution('my.metric.name', 3.8, ['tags:here']);
Distributions are similar to histograms (they create several metrics for count, average, percentiles, etc.), but they are calculated server-side on Datadog’s systems. For more details and guidance on when to use them, see:
(Thanks to @Mr0grog.)
Add an onError
option for handling asynchronous errors while flushing buffered metrics. You can use this to get details on an error or to send error info to a tracking service like Sentry.io:
1const metrics = require('datadog-metrics'); 2metrics.init({ 3 onError (error) { 4 console.error('There was an error sending to Datadog:', error); 5 } 6});
The built-in reporter classes are now available for you to use. If you need to disable the metrics library for some reason, you can now do so with:
1const metrics = require('datadog-metrics'); 2metrics.init({ 3 reporter: new metrics.reporters.NullReporter(), 4});
(Thanks to @Mr0grog.)
Add an option for setting histogram defaults. In v0.10.0, the histogram()
function gained the ability to set what aggregations and percentiles it generates with a final options
argument. You can now specify a histogram
option for init()
or BufferedMetricsLogger
in order to set default options for all calls to histogram()
. Any options you set in the actual histogram()
call will layer on top of the defaults:
1const metrics = require('datadog-metrics'); 2metrics.init({ 3 histogram: { 4 aggregates: ['sum', 'avg'], 5 percentiles: [0.99] 6 } 7}); 8 9// Acts as if the options had been set to: 10// { aggregates: ['sum', 'avg'], percentiles: [0.99] } 11metrics.histogram('my.metric.name', 3.8); 12 13// Acts as if the options had been set to: 14// { aggregates: ['sum', 'avg'], percentiles: [0.5, 0.95] } 15metrics.histogram('my.metric.name', 3.8, [], Date.now(), { 16 percentiles: [0.5, 0.95] 17});
(Thanks to @Mr0grog.)
Add a .median
aggregation for histograms. When you log a histogram metric, it ultimately creates several metrics that track the minimum value, average value, maximum value, etc. There is now one that tracks the median value. StatsD creates the same metric from histograms, so you may find this useful if transitioning from StatsD. (Thanks to @Mr0grog.)
This package no longer locks specific versions of its dependencies (instead, your package manager can choose any version that is compatible). This may help when deduplicating packages for faster installs or smaller bundles. (Thanks to @Mr0grog.)
Bug Fixes:
unref()
on timers in non-Node.js environments. This is a step towards browser compatibility, although we are not testing browser-based usage yet. (Thanks to @Mr0grog.)apiHost
option was broken in v0.10.0 and now works again. (Thanks to @Mr0grog and @npeters.)BufferedMetricsLogger
will not longer change the credentials used by previously created BufferedMetricsLogger
instances. (Thanks to @Mr0grog.)Internal Updates:
main
. (Thanks to @dbader.)0.10.1 (2022-09-11)
@datadog/datadog-api-client
was not used correctly. (Thanks to @gquinteros93)0.10.0 (2022-09-08)
Breaking change: we now use Datadog’s official @datadog/datadog-api-client
package to send metrics to Datadog. This makes datadog-metrics
usable with Webpack, but removes the agent
option. If you were using this option and the new library does not provide a way to meet your needs, please let us know by filing an issue! (Thanks to @thatguychrisw)
You can now customize what metrics are generated by a histogram. When logging a histogram metric, the 5th argument is an optional object with information about which aggregations and percentiles to create metrics for:
1const metrics = require('datadog-metrics'); 2metrics.histogram('my.metric.name', 3.8, [], Date.now(), { 3 // Aggregates can include 'max', 'min', 'sum', 'avg', or 'count'. 4 aggregates: ['max', 'min', 'sum', 'avg', 'count'], 5 // Percentiles can include any decimal between 0 and 1. 6 percentiles: [0.75, 0.85, 0.95, 0.99] 7});
(Thanks to @gquinteros93.)
INTERNAL: Clean up continuous integration on TravisCI. (Thanks to @ErikBoesen.)
0.9.3 (2021-03-22)
dogapi
and jshint
to their latest versions. (Thanks to @ErikBoesen.)0.9.2 (2021-03-14)
Expose new apiHost
option on init()
and BufferedMetricsLogger
constructor. This makes it possible to actually configure the Datadog site to submit metrics to. For example, you can now submit metrics to Datadog’s Europe servers with:
1const metrics = require('datadog-metrics'); 2metrics.init({ 3 apiHost: 'datadoghq.eu' 4});
(Thanks to @ErikBoesen.)
0.9.1 (2021-02-19)
0.9.0 (2021-02-10)
datadoghq.eu
for Europe). (Thanks to @fermelone.)0.8.2 (2020-11-16)
dogapi
version.onSuccess
callback in NullReporter
. (Thanks to @dkMorlok.)0.8.1
0.8.0
0.7.0
counter
to count
as counter
is deprecated by Datadog (Thanks to @dustingibbs)0.6.1
0.6.0
0.5.0
0.4.0
0.3.0
metrics.flush()
(Thanks @akrylysov!)0.2.1
0.2.0
setDefaultXYZ()
and added init()
0.1.1
increment
to be called with a default value of 10.1.0
counter
to increment
0.0.0
This module is heavily inspired by the Python dogapi module.
Daniel Bader – @dbader_org – mail@dbader.org
Distributed under the MIT license. See LICENSE
for more information.
Your contributions are always welcome! See CONTRIBUTING.md
for more.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
14 commit(s) and 6 issue activity found in the last 90 days -- score normalized to 10
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 5/27 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
Project has not signed or included provenance with any releases.
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More@types/datadog-metrics
TypeScript definitions for datadog-metrics
@datadog/native-metrics
Native metrics collector for libuv and v8
datadog-lambda-js
Lambda client library that supports hybrid tracing in node js
@joakimbeng/datadog-metrics
Buffered metrics reporting via the DataDog HTTP API