@loglayer/mixin-datadog-http-metrics 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Theo Gravity
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # Datadog Metrics (HTTP) mixin for LogLayer
2
+
3
+ [![NPM Version](https://img.shields.io/npm/v/%40loglayer%2Fmixin-datadog-http-metrics)](https://www.npmjs.com/package/@loglayer/mixin-datadog-http-metrics)
4
+ [![NPM Downloads](https://img.shields.io/npm/dm/%40loglayer%2Fmixin-datadog-http-metrics)](https://www.npmjs.com/package/@loglayer/mixin-datadog-http-metrics)
5
+ [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
6
+
7
+ Adds Datadog metrics functionality to the [LogLayer](https://loglayer.dev) logging library using [datadog-metrics](https://github.com/dbader/node-datadog-metrics).
8
+
9
+ The mixin provides a fluent builder API for sending metrics to Datadog via HTTP through a `ddStats` property on LogLayer instances. Unlike the [hot-shots mixin](https://www.npmjs.com/package/@loglayer/mixin-hot-shots) which sends metrics via StatsD/UDP, this mixin sends metrics directly to Datadog's HTTP API.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install loglayer @loglayer/mixin-datadog-http-metrics
15
+ ```
16
+
17
+ ```bash
18
+ yarn add loglayer @loglayer/mixin-datadog-http-metrics
19
+ ```
20
+
21
+ ```bash
22
+ pnpm add loglayer @loglayer/mixin-datadog-http-metrics
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ```typescript
28
+ import { LogLayer, useLogLayerMixin, ConsoleTransport } from 'loglayer';
29
+ import { datadogMetricsMixin } from '@loglayer/mixin-datadog-http-metrics';
30
+
31
+ // Register the mixin (must be called before creating LogLayer instances)
32
+ useLogLayerMixin(datadogMetricsMixin({
33
+ apiKey: process.env.DATADOG_API_KEY,
34
+ site: process.env.DATADOG_SITE, // e.g. 'us5.datadoghq.com'
35
+ prefix: 'myapp.',
36
+ defaultTags: ['env:production'],
37
+ }));
38
+
39
+ // Create LogLayer instance
40
+ const log = new LogLayer({
41
+ transport: new ConsoleTransport({
42
+ logger: console
43
+ })
44
+ });
45
+
46
+ // Use Datadog metrics through the ddStats property
47
+ log.ddStats.increment('request.count').send();
48
+ log.ddStats.gauge('queue.size', 42).send();
49
+ log.ddStats.histogram('response.time', 250).send();
50
+ log.ddStats.distribution('latency', 100).send();
51
+
52
+ // Use builder pattern for advanced configuration
53
+ log.ddStats.increment('request.count')
54
+ .withValue(5)
55
+ .withTags(['env:production', 'service:api'])
56
+ .withTimestamp(Date.now())
57
+ .send();
58
+ ```
59
+
60
+ ## Documentation
61
+
62
+ For more details, visit [https://loglayer.dev/mixins/datadog-http-metrics](https://loglayer.dev/mixins/datadog-http-metrics).
package/dist/index.cjs ADDED
@@ -0,0 +1,526 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+ let datadog_metrics = require("datadog-metrics");
29
+ datadog_metrics = __toESM(datadog_metrics);
30
+ let loglayer = require("loglayer");
31
+
32
+ //#region src/client.ts
33
+ let metricsClient = null;
34
+ /**
35
+ * Set the datadog-metrics client for the mixin.
36
+ * Called during mixin registration.
37
+ *
38
+ * @param client - The BufferedMetricsLogger instance
39
+ */
40
+ function setMetricsClient(client) {
41
+ metricsClient = client;
42
+ }
43
+ /**
44
+ * Check if the client is null (no-op mode)
45
+ *
46
+ * @returns True if the client is null, false otherwise
47
+ */
48
+ function isNoOpClient() {
49
+ return metricsClient === null;
50
+ }
51
+ /**
52
+ * Get the datadog-metrics client.
53
+ * Returns the configured client or null if not configured.
54
+ *
55
+ * @returns The BufferedMetricsLogger instance or null
56
+ */
57
+ function getMetricsClient() {
58
+ return metricsClient;
59
+ }
60
+
61
+ //#endregion
62
+ //#region src/CommonMetricsBuilder.ts
63
+ /**
64
+ * Base class for common metrics builder functionality.
65
+ * Provides shared methods for configuring tags and timestamp.
66
+ */
67
+ var CommonMetricsBuilder = class {
68
+ /** Tags to attach to the metric */
69
+ tags;
70
+ /** Timestamp in milliseconds since epoch */
71
+ timestamp;
72
+ /** The datadog-metrics client instance */
73
+ client;
74
+ /**
75
+ * Creates a new CommonMetricsBuilder instance.
76
+ *
77
+ * @param client - The datadog-metrics BufferedMetricsLogger instance
78
+ */
79
+ constructor(client) {
80
+ this.client = client;
81
+ }
82
+ /**
83
+ * Add tags to the metric.
84
+ *
85
+ * @param tags - Tags as an array of strings (e.g., ['env:prod', 'service:api'])
86
+ * @returns The builder instance for method chaining
87
+ */
88
+ withTags(tags) {
89
+ this.tags = tags;
90
+ return this;
91
+ }
92
+ /**
93
+ * Set the timestamp for the metric.
94
+ *
95
+ * @param timestamp - Timestamp in milliseconds since epoch
96
+ * @returns The builder instance for method chaining
97
+ */
98
+ withTimestamp(timestamp) {
99
+ this.timestamp = timestamp;
100
+ return this;
101
+ }
102
+ };
103
+
104
+ //#endregion
105
+ //#region src/builders/DistributionBuilder.ts
106
+ /**
107
+ * Builder for the distribution method.
108
+ * Supports chaining with withTags() and withTimestamp().
109
+ */
110
+ var DistributionBuilder = class extends CommonMetricsBuilder {
111
+ /** The metric key */
112
+ key;
113
+ /** The distribution value */
114
+ value;
115
+ /**
116
+ * Creates a new DistributionBuilder instance.
117
+ *
118
+ * @param client - The datadog-metrics BufferedMetricsLogger instance
119
+ * @param key - The metric key to record
120
+ * @param value - The distribution value to record
121
+ */
122
+ constructor(client, key, value) {
123
+ super(client);
124
+ this.key = key;
125
+ this.value = value;
126
+ }
127
+ /**
128
+ * Send the distribution metric with the configured options.
129
+ */
130
+ send() {
131
+ this.client.distribution(this.key, this.value, this.tags, this.timestamp);
132
+ }
133
+ };
134
+
135
+ //#endregion
136
+ //#region src/builders/GaugeBuilder.ts
137
+ /**
138
+ * Builder for the gauge method.
139
+ * Supports chaining with withTags() and withTimestamp().
140
+ */
141
+ var GaugeBuilder = class extends CommonMetricsBuilder {
142
+ /** The metric key */
143
+ key;
144
+ /** The gauge value */
145
+ value;
146
+ /**
147
+ * Creates a new GaugeBuilder instance.
148
+ *
149
+ * @param client - The datadog-metrics BufferedMetricsLogger instance
150
+ * @param key - The metric key to set
151
+ * @param value - The value to set the gauge to
152
+ */
153
+ constructor(client, key, value) {
154
+ super(client);
155
+ this.key = key;
156
+ this.value = value;
157
+ }
158
+ /**
159
+ * Send the gauge metric with the configured options.
160
+ */
161
+ send() {
162
+ this.client.gauge(this.key, this.value, this.tags, this.timestamp);
163
+ }
164
+ };
165
+
166
+ //#endregion
167
+ //#region src/builders/HistogramBuilder.ts
168
+ /**
169
+ * Builder for the histogram method.
170
+ * Supports chaining with withTags(), withTimestamp(), and withHistogramOptions().
171
+ */
172
+ var HistogramBuilder = class extends CommonMetricsBuilder {
173
+ /** The metric key */
174
+ key;
175
+ /** The histogram value */
176
+ value;
177
+ /** Optional histogram-specific options */
178
+ histogramOptions;
179
+ /**
180
+ * Creates a new HistogramBuilder instance.
181
+ *
182
+ * @param client - The datadog-metrics BufferedMetricsLogger instance
183
+ * @param key - The metric key to record
184
+ * @param value - The histogram value to record
185
+ */
186
+ constructor(client, key, value) {
187
+ super(client);
188
+ this.key = key;
189
+ this.value = value;
190
+ }
191
+ /**
192
+ * Set histogram-specific options for aggregation and percentiles.
193
+ *
194
+ * @param options - Histogram options with aggregates and/or percentiles
195
+ * @returns The builder instance for method chaining
196
+ */
197
+ withHistogramOptions(options) {
198
+ this.histogramOptions = options;
199
+ return this;
200
+ }
201
+ /**
202
+ * Send the histogram metric with the configured options.
203
+ */
204
+ send() {
205
+ this.client.histogram(this.key, this.value, this.tags, this.timestamp, this.histogramOptions);
206
+ }
207
+ };
208
+
209
+ //#endregion
210
+ //#region src/builders/IncrementBuilder.ts
211
+ /**
212
+ * Builder for the increment method.
213
+ * Supports chaining with withValue(), withTags(), and withTimestamp().
214
+ */
215
+ var IncrementBuilder = class extends CommonMetricsBuilder {
216
+ /** The metric key */
217
+ key;
218
+ /** The increment value (optional, defaults to 1) */
219
+ value;
220
+ /**
221
+ * Creates a new IncrementBuilder instance.
222
+ *
223
+ * @param client - The datadog-metrics BufferedMetricsLogger instance
224
+ * @param key - The metric key to increment
225
+ */
226
+ constructor(client, key) {
227
+ super(client);
228
+ this.key = key;
229
+ }
230
+ /**
231
+ * Set the increment value.
232
+ *
233
+ * @param value - The value to increment by (defaults to 1 if not specified)
234
+ * @returns The builder instance for method chaining
235
+ */
236
+ withValue(value) {
237
+ this.value = value;
238
+ return this;
239
+ }
240
+ /**
241
+ * Send the increment metric with the configured options.
242
+ */
243
+ send() {
244
+ this.client.increment(this.key, this.value, this.tags, this.timestamp);
245
+ }
246
+ };
247
+
248
+ //#endregion
249
+ //#region src/MetricsAPI.ts
250
+ /**
251
+ * Metrics API implementation that wraps datadog-metrics BufferedMetricsLogger.
252
+ * Provides a fluent interface for sending metrics to Datadog via HTTP.
253
+ */
254
+ var MetricsAPI = class {
255
+ /**
256
+ * Creates a new MetricsAPI instance.
257
+ *
258
+ * @param client - The datadog-metrics BufferedMetricsLogger instance
259
+ */
260
+ constructor(client) {
261
+ this.client = client;
262
+ }
263
+ /**
264
+ * Increment a counter metric.
265
+ * Returns a builder that supports chaining with withValue(), withTags(), and withTimestamp().
266
+ *
267
+ * @param key - The metric key to increment
268
+ * @returns A builder instance for chaining additional options
269
+ */
270
+ increment(key) {
271
+ return new IncrementBuilder(this.client, key);
272
+ }
273
+ /**
274
+ * Set a gauge metric to a specific value.
275
+ * Returns a builder that supports chaining with withTags() and withTimestamp().
276
+ *
277
+ * @param key - The metric key to set
278
+ * @param value - The value to set the gauge to
279
+ * @returns A builder instance for chaining additional options
280
+ */
281
+ gauge(key, value) {
282
+ return new GaugeBuilder(this.client, key, value);
283
+ }
284
+ /**
285
+ * Record a histogram value.
286
+ * Returns a builder that supports chaining with withTags(), withTimestamp(), and withHistogramOptions().
287
+ *
288
+ * @param key - The metric key to record
289
+ * @param value - The histogram value to record
290
+ * @returns A builder instance for chaining additional options
291
+ */
292
+ histogram(key, value) {
293
+ return new HistogramBuilder(this.client, key, value);
294
+ }
295
+ /**
296
+ * Record a distribution value (server-side calculated).
297
+ * Returns a builder that supports chaining with withTags() and withTimestamp().
298
+ *
299
+ * @param key - The metric key to record
300
+ * @param value - The distribution value to record
301
+ * @returns A builder instance for chaining additional options
302
+ */
303
+ distribution(key, value) {
304
+ return new DistributionBuilder(this.client, key, value);
305
+ }
306
+ /**
307
+ * Flush all buffered metrics to Datadog immediately.
308
+ *
309
+ * @returns A promise that resolves when the flush completes
310
+ */
311
+ flush() {
312
+ return this.client.flush();
313
+ }
314
+ /**
315
+ * Start auto-flushing metrics at the configured interval.
316
+ */
317
+ start() {
318
+ this.client.start();
319
+ }
320
+ /**
321
+ * Stop auto-flushing and optionally flush remaining metrics.
322
+ *
323
+ * @param options - Options for stopping. `flush` defaults to true.
324
+ * @returns A promise that resolves when stopping completes
325
+ */
326
+ stop(options) {
327
+ return this.client.stop(options);
328
+ }
329
+ /**
330
+ * Get the underlying BufferedMetricsLogger instance.
331
+ *
332
+ * @returns The BufferedMetricsLogger instance
333
+ */
334
+ getClient() {
335
+ return this.client;
336
+ }
337
+ };
338
+
339
+ //#endregion
340
+ //#region src/MockMetricsAPI.ts
341
+ /**
342
+ * Base class for mock metrics builders.
343
+ * Provides no-op implementations of common builder methods.
344
+ */
345
+ var MockCommonMetricsBuilder = class {
346
+ withTags(_tags) {
347
+ return this;
348
+ }
349
+ withTimestamp(_timestamp) {
350
+ return this;
351
+ }
352
+ send() {}
353
+ };
354
+ /**
355
+ * Mock implementation of IncrementBuilder.
356
+ * Does nothing when methods are called.
357
+ */
358
+ var MockIncrementBuilder = class extends MockCommonMetricsBuilder {
359
+ constructor(_key) {
360
+ super();
361
+ }
362
+ withValue(_value) {
363
+ return this;
364
+ }
365
+ };
366
+ /**
367
+ * Mock implementation of GaugeBuilder.
368
+ * Does nothing when methods are called.
369
+ */
370
+ var MockGaugeBuilder = class extends MockCommonMetricsBuilder {
371
+ constructor(_key, _value) {
372
+ super();
373
+ }
374
+ };
375
+ /**
376
+ * Mock implementation of HistogramBuilder.
377
+ * Does nothing when methods are called.
378
+ */
379
+ var MockHistogramBuilder = class extends MockCommonMetricsBuilder {
380
+ constructor(_key, _value) {
381
+ super();
382
+ }
383
+ withHistogramOptions(_options) {
384
+ return this;
385
+ }
386
+ };
387
+ /**
388
+ * Mock implementation of DistributionBuilder.
389
+ * Does nothing when methods are called.
390
+ */
391
+ var MockDistributionBuilder = class extends MockCommonMetricsBuilder {
392
+ constructor(_key, _value) {
393
+ super();
394
+ }
395
+ };
396
+ /**
397
+ * No-op implementation of IMetricsAPI.
398
+ * All methods return mock builder instances that do nothing when send() is called.
399
+ * This is used when datadogMetricsMixin(null) is called, allowing the metrics API
400
+ * to be used without actually sending any metrics.
401
+ */
402
+ var MockMetricsAPI = class {
403
+ increment(key) {
404
+ return new MockIncrementBuilder(key);
405
+ }
406
+ gauge(key, value) {
407
+ return new MockGaugeBuilder(key, value);
408
+ }
409
+ histogram(key, value) {
410
+ return new MockHistogramBuilder(key, value);
411
+ }
412
+ distribution(key, value) {
413
+ return new MockDistributionBuilder(key, value);
414
+ }
415
+ flush() {
416
+ return Promise.resolve();
417
+ }
418
+ start() {}
419
+ stop(_options) {
420
+ return Promise.resolve();
421
+ }
422
+ getClient() {
423
+ return {
424
+ gauge: () => {},
425
+ increment: () => {},
426
+ histogram: () => {},
427
+ distribution: () => {},
428
+ flush: () => Promise.resolve(),
429
+ start: () => {},
430
+ stop: () => Promise.resolve()
431
+ };
432
+ }
433
+ };
434
+
435
+ //#endregion
436
+ //#region src/LogLayer.augment.ts
437
+ /**
438
+ * LogLayer mixin that adds a `ddStats` property to LogLayer instances.
439
+ * Provides access to the MetricsAPI for sending metrics to Datadog via HTTP.
440
+ */
441
+ const logLayerDatadogMetricsMixin = {
442
+ augmentationType: loglayer.LogLayerMixinAugmentType.LogLayer,
443
+ augment: (prototype) => {
444
+ Object.defineProperty(prototype, "ddStats", {
445
+ get() {
446
+ if (!this._ddMetricsAPI) {
447
+ const client = getMetricsClient();
448
+ this._ddMetricsAPI = isNoOpClient() || !client ? new MockMetricsAPI() : new MetricsAPI(client);
449
+ }
450
+ return this._ddMetricsAPI;
451
+ },
452
+ enumerable: true,
453
+ configurable: true
454
+ });
455
+ },
456
+ augmentMock: (prototype) => {
457
+ Object.defineProperty(prototype, "ddStats", {
458
+ get() {
459
+ if (!this._ddMetricsAPI) {
460
+ const client = getMetricsClient();
461
+ this._ddMetricsAPI = isNoOpClient() || !client ? new MockMetricsAPI() : new MetricsAPI(client);
462
+ }
463
+ return this._ddMetricsAPI;
464
+ },
465
+ enumerable: true,
466
+ configurable: true
467
+ });
468
+ }
469
+ };
470
+
471
+ //#endregion
472
+ //#region src/index.ts
473
+ const BufferedMetricsLogger = datadog_metrics.default.BufferedMetricsLogger;
474
+ /**
475
+ * A reporter that discards all metrics. Useful for testing or temporarily
476
+ * disabling metric submission without using the `enabled` flag.
477
+ * Re-exported from the `datadog-metrics` library.
478
+ */
479
+ const NullReporter = datadog_metrics.default.reporters.NullReporter;
480
+ /**
481
+ * The default reporter that sends metrics to Datadog's HTTP API with automatic retries.
482
+ * Re-exported from the `datadog-metrics` library.
483
+ */
484
+ const DatadogReporter = datadog_metrics.default.reporters.DatadogReporter;
485
+ /**
486
+ * Register the datadog-metrics mixin with LogLayer.
487
+ * This adds a `ddStats` property to LogLayer instances,
488
+ * providing a fluent API for sending metrics to Datadog via HTTP.
489
+ *
490
+ * @param options - The BufferedMetricsLogger configuration options, or null for no-op mode.
491
+ * Set `enabled: false` to use no-op mode while still passing options.
492
+ * @returns A LogLayer mixin registration object
493
+ *
494
+ * @example
495
+ * ```typescript
496
+ * import { useLogLayerMixin } from 'loglayer';
497
+ * import { datadogMetricsMixin } from '@loglayer/mixin-datadog-http-metrics';
498
+ *
499
+ * useLogLayerMixin(datadogMetricsMixin({
500
+ * apiKey: 'your-api-key',
501
+ * prefix: 'myapp.',
502
+ * enabled: process.env.NODE_ENV === 'production',
503
+ * }));
504
+ * ```
505
+ */
506
+ function datadogMetricsMixin(options) {
507
+ if (options && options.enabled !== false) {
508
+ const { enabled: _, ...metricsOptions } = options;
509
+ setMetricsClient(new datadog_metrics.default.BufferedMetricsLogger({
510
+ flushIntervalSeconds: 5,
511
+ ...metricsOptions
512
+ }));
513
+ } else setMetricsClient(null);
514
+ return {
515
+ mixinsToAdd: [logLayerDatadogMetricsMixin],
516
+ pluginsToAdd: []
517
+ };
518
+ }
519
+
520
+ //#endregion
521
+ exports.BufferedMetricsLogger = BufferedMetricsLogger;
522
+ exports.DatadogReporter = DatadogReporter;
523
+ exports.MetricsAPI = MetricsAPI;
524
+ exports.MockMetricsAPI = MockMetricsAPI;
525
+ exports.NullReporter = NullReporter;
526
+ exports.datadogMetricsMixin = datadogMetricsMixin;