-
Notifications
You must be signed in to change notification settings - Fork 138
/
Metrics.ts
926 lines (870 loc) · 31 KB
/
Metrics.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
import { Console } from 'node:console';
import { Utility } from '@aws-lambda-powertools/commons';
import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { Callback, Context, Handler } from 'aws-lambda';
import { EnvironmentVariablesService } from './config/EnvironmentVariablesService.js';
import {
COLD_START_METRIC,
DEFAULT_NAMESPACE,
MAX_DIMENSION_COUNT,
MAX_METRICS_SIZE,
MAX_METRIC_VALUES_SIZE,
MetricResolution as MetricResolutions,
MetricUnit as MetricUnits,
} from './constants.js';
import type {
ConfigServiceInterface,
Dimensions,
EmfOutput,
ExtraOptions,
MetricDefinition,
MetricResolution,
MetricUnit,
MetricsInterface,
MetricsOptions,
StoredMetrics,
} from './types/index.js';
/**
* The Metrics utility creates custom metrics asynchronously by logging metrics to standard output following {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html | Amazon CloudWatch Embedded Metric Format (EMF)}.
*
* These metrics can be visualized through Amazon CloudWatch Console.
*
* **Key features**
* * Aggregating up to 100 metrics using a single CloudWatch EMF object (large JSON blob).
* * Validating your metrics against common metric definitions mistakes (for example, metric unit, values, max dimensions, max metrics).
* * Metrics are created asynchronously by the CloudWatch service. You do not need any custom stacks, and there is no impact to Lambda function latency.
* * Creating a one-off metric with different dimensions.
*
* After initializing the Metrics class, you can add metrics using the {@link Metrics.addMetric | `addMetric()`} method.
* The metrics are stored in a buffer and are flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
* Each metric can have dimensions and metadata added to it.
*
* @example
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* export const handler = async (event: { requestId: string }) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* If you don't want to manually flush the metrics, you can use the {@link Metrics.logMetrics | `logMetrics()`} decorator or
* the Middy.js middleware to automatically flush the metrics after the handler function returns or throws an error.
*
* In addition to this, the decorator and middleware can also be configured to capture a `ColdStart` metric and
* set default dimensions for all metrics.
*
* **Class method decorator**
*
* @example
*
* ```typescript
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* @metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }
* }
*
* const handlerClass = new Lambda();
* export const handler = handlerClass.handler.bind(handlerClass);
* ```
*
* Note that decorators are a Stage 3 proposal for JavaScript and are not yet part of the ECMAScript standard.
* The current implmementation in this library is based on the legacy TypeScript decorator syntax enabled by the [`experimentalDecorators` flag](https://www.typescriptlang.org/tsconfig/#experimentalDecorators)
* set to `true` in the `tsconfig.json` file.
*
* **Middy.js middleware**
*
* @example
*
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = middy(async () => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }).use(logMetrics(metrics, {
* captureColdStartMetric: true,
* throwOnEmptyMetrics: true,
* }));
* ```
*
* The `logMetrics()` middleware is compatible with `@middy/[email protected]` and above.
*
*/
class Metrics extends Utility implements MetricsInterface {
/**
* Console instance used to print logs.
*
* In AWS Lambda, we create a new instance of the Console class so that we can have
* full control over the output of the logs. In testing environments, we use the
* default console instance.
*
* This property is initialized in the constructor in setOptions().
*
* @private
*/
private console!: Console;
/**
* Custom configuration service for metrics
*/
private customConfigService?: ConfigServiceInterface;
/**
* Default dimensions to be added to all metrics
* @default {}
*/
private defaultDimensions: Dimensions = {};
/**
* Additional dimensions for the current metrics context
* @default {}
*/
private dimensions: Dimensions = {};
/**
* Service for accessing environment variables
*/
private envVarsService?: EnvironmentVariablesService;
/**
* Name of the Lambda function
*/
private functionName?: string;
/**
* Flag indicating if this is a single metric instance
* @default false
*/
private isSingleMetric = false;
/**
* Additional metadata to be included with metrics
* @default {}
*/
private metadata: Record<string, string> = {};
/**
* Namespace for the metrics
*/
private namespace?: string;
/**
* Flag to determine if an error should be thrown when no metrics are recorded
* @default false
*/
private shouldThrowOnEmptyMetrics = false;
/**
* Storage for metrics before they are published
* @default {}
*/
private storedMetrics: StoredMetrics = {};
public constructor(options: MetricsOptions = {}) {
super();
this.dimensions = {};
this.setOptions(options);
}
/**
* Add a dimension to metrics.
*
* A dimension is a key-value pair that is used to group metrics, and it is included in all metrics emitted after it is added.
*
* When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of
* dimension is useful when you want to add request-specific dimensions to your metrics. If you want to add dimensions that are
* included in all metrics, use the {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} method.
*
* @param name - The name of the dimension
* @param value - The value of the dimension
*/
public addDimension(name: string, value: string): void {
if (MAX_DIMENSION_COUNT <= this.getCurrentDimensionsCount()) {
throw new RangeError(
`The number of metric dimensions must be lower than ${MAX_DIMENSION_COUNT}`
);
}
this.dimensions[name] = value;
}
/**
* Add multiple dimensions to the metrics.
*
* This method is useful when you want to add multiple dimensions to the metrics at once.
*
* When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of
* dimension is useful when you want to add request-specific dimensions to your metrics. If you want to add dimensions that are
* included in all metrics, use the {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} method.
*
* @param dimensions - An object with key-value pairs of dimensions
*/
public addDimensions(dimensions: Dimensions): void {
const newDimensions = { ...this.dimensions };
for (const dimensionName of Object.keys(dimensions)) {
newDimensions[dimensionName] = dimensions[dimensionName];
}
if (Object.keys(newDimensions).length > MAX_DIMENSION_COUNT) {
throw new RangeError(
`Unable to add ${
Object.keys(dimensions).length
} dimensions: the number of metric dimensions must be lower than ${MAX_DIMENSION_COUNT}`
);
}
this.dimensions = newDimensions;
}
/**
* A metadata key-value pair to be included with metrics.
*
* You can use this method to add high-cardinality data as part of your metrics.
* This is useful when you want to search highly contextual information along with your metrics in your logs.
*
* Note that the metadata is not included in the Amazon CloudWatch UI, but it can be used to search and filter logs.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (event) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param key - The key of the metadata
* @param value - The value of the metadata
*/
public addMetadata(key: string, value: string): void {
this.metadata[key] = value;
}
/**
* Add a metric to the metrics buffer.
*
* By default, metrics are buffered and flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method,
* or at the end of the handler function when using the {@link Metrics.logMetrics | `logMetrics()`} decorator or the Middy.js middleware.
*
* Metrics are emitted to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* You can add a metric by specifying the metric name, unit, and value. For convenience,
* we provide a set of constants for the most common units in the {@link MetricUnits | MetricUnit} dictionary object.
*
* Optionally, you can specify a {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | resolution}, which can be either `High` or `Standard`, using the {@link MetricResolutions | MetricResolution} dictionary object.
* By default, metrics are published with a resolution of `Standard`.
*
* @example
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param name - The metric name
* @param unit - The metric unit, see {@link MetricUnits | MetricUnit}
* @param value - The metric value
* @param resolution - The metric resolution, see {@link MetricResolutions | MetricResolution}
*/
public addMetric(
name: string,
unit: MetricUnit,
value: number,
resolution: MetricResolution = MetricResolutions.Standard
): void {
this.storeMetric(name, unit, value, resolution);
if (this.isSingleMetric) this.publishStoredMetrics();
}
/**
* Immediately emit a `ColdStart` metric if this is a cold start invocation.
*
* A cold start is when AWS Lambda initializes a new instance of your function. To take advantage of this feature,
* you must instantiate the Metrics class outside of the handler function.
*
* By using this method, the metric will be emitted immediately without you having to call {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
*
* If you are using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, you can enable this
* feature by setting the `captureColdStartMetric` option to `true`.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.captureColdStartMetric();
* };
* ```
*/
public captureColdStartMetric(): void {
if (!this.isColdStart()) return;
const singleMetric = this.singleMetric();
if (this.defaultDimensions.service) {
singleMetric.setDefaultDimensions({
service: this.defaultDimensions.service,
});
}
if (this.functionName != null) {
singleMetric.addDimension('function_name', this.functionName);
}
singleMetric.addMetric(COLD_START_METRIC, MetricUnits.Count, 1);
}
/**
* Clear all previously set default dimensions.
*
* This will remove all default dimensions set by the {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} method
* or via the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* metrics.setDefaultDimensions({ region: 'us-west-2' });
*
* // both environment and region dimensions are removed
* metrics.clearDefaultDimensions();
* ```
*/
public clearDefaultDimensions(): void {
this.defaultDimensions = {};
}
/**
* Clear all the dimensions added to the Metrics instance via {@link Metrics.addDimension | `addDimension()`} or {@link Metrics.addDimensions | `addDimensions()`}.
*
* These dimensions are normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific dimensions that you no longer need at runtime.
*
* This method does not clear the default dimensions set via {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} or via
* the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addDimension('region', 'us-west-2');
*
* // ...
*
* metrics.clearDimensions(); // olnly the region dimension is removed
* };
* ```
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
public clearDimensions(): void {
this.dimensions = {};
}
/**
* Clear all the metadata added to the Metrics instance.
*
* Metadata is normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific metadata that you no longer need at runtime.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
public clearMetadata(): void {
this.metadata = {};
}
/**
* Clear all the metrics stored in the buffer.
*
* This is useful when you want to clear the metrics stored in the buffer without publishing them.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
public clearMetrics(): void {
this.storedMetrics = {};
}
/**
* A class method decorator to automatically log metrics after the method returns or throws an error.
*
* The decorator can be used with TypeScript classes and can be configured to optionally capture a `ColdStart` metric (see {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`}),
* throw an error if no metrics are emitted (see {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`}),
* and set default dimensions for all metrics (see {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`}).
*
* @example
*
* ```typescript
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* @metrics.logMetrics({ captureColdStartMetric: true })
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }
* }
*
* const handlerClass = new Lambda();
* export const handler = handlerClass.handler.bind(handlerClass);
* ```
*
* You can configure the decorator with the following options:
* - `captureColdStartMetric` - Whether to capture a `ColdStart` metric
* - `defaultDimensions` - Default dimensions to add to all metrics
* - `throwOnEmptyMetrics` - Whether to throw an error if no metrics are emitted
*
* @param options - Options to configure the behavior of the decorator, see {@link ExtraOptions}
*/
public logMetrics(options: ExtraOptions = {}): HandlerMethodDecorator {
const { throwOnEmptyMetrics, defaultDimensions, captureColdStartMetric } =
options;
if (throwOnEmptyMetrics) {
this.setThrowOnEmptyMetrics(throwOnEmptyMetrics);
}
if (defaultDimensions !== undefined) {
this.setDefaultDimensions(defaultDimensions);
}
return (_target, _propertyKey, descriptor) => {
// biome-ignore lint/style/noNonNullAssertion: The descriptor.value is the method this decorator decorates, it cannot be undefined.
const originalMethod = descriptor.value!;
const metricsRef = this;
// Use a function() {} instead of an () => {} arrow function so that we can
// access `myClass` as `this` in a decorated `myClass.myMethod()`.
descriptor.value = async function (
this: Handler,
event: unknown,
context: Context,
callback: Callback
): Promise<unknown> {
metricsRef.functionName = context.functionName;
if (captureColdStartMetric) metricsRef.captureColdStartMetric();
let result: unknown;
try {
result = await originalMethod.apply(this, [event, context, callback]);
} finally {
metricsRef.publishStoredMetrics();
}
return result;
};
return descriptor;
};
}
/**
* Flush the stored metrics to standard output.
*
* The method empties the metrics buffer and emits the metrics to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the metrics are automatically flushed after the handler function returns or throws an error.
*
* @example
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*/
public publishStoredMetrics(): void {
const hasMetrics = Object.keys(this.storedMetrics).length > 0;
if (!this.shouldThrowOnEmptyMetrics && !hasMetrics) {
console.warn(
'No application metrics to publish. The cold-start metric may be published if enabled. ' +
'If application metrics should never be empty, consider using `throwOnEmptyMetrics`'
);
}
const emfOutput = this.serializeMetrics();
hasMetrics && this.console.log(JSON.stringify(emfOutput));
this.clearMetrics();
this.clearDimensions();
this.clearMetadata();
}
/**
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* The EMF schema is a JSON object that contains the following properties:
* - `_aws`: An object containing the timestamp and the CloudWatch metrics.
* - `CloudWatchMetrics`: An array of CloudWatch metrics objects.
* - `Namespace`: The namespace of the metrics.
* - `Dimensions`: An array of dimensions for the metrics.
* - `Metrics`: An array of metric definitions.
*
* The object is then emitted to standard output, which in AWS Lambda is picked up by CloudWatch logs and processed asynchronously.
*/
public serializeMetrics(): EmfOutput {
// Storage resolution is included only for High resolution metrics
const metricDefinitions: MetricDefinition[] = Object.values(
this.storedMetrics
).map((metricDefinition) => ({
Name: metricDefinition.name,
Unit: metricDefinition.unit,
...(metricDefinition.resolution === MetricResolutions.High
? { StorageResolution: metricDefinition.resolution }
: {}),
}));
if (metricDefinitions.length === 0 && this.shouldThrowOnEmptyMetrics) {
throw new RangeError(
'The number of metrics recorded must be higher than zero'
);
}
if (!this.namespace)
console.warn('Namespace should be defined, default used');
// We reduce the stored metrics to a single object with the metric
// name as the key and the value as the value.
const metricValues = Object.values(this.storedMetrics).reduce(
(
result: Record<string, number | number[]>,
{ name, value }: { name: string; value: number | number[] }
) => {
result[name] = value;
return result;
},
{}
);
const dimensionNames = [
...new Set([
...Object.keys(this.defaultDimensions),
...Object.keys(this.dimensions),
]),
];
return {
_aws: {
Timestamp: new Date().getTime(),
CloudWatchMetrics: [
{
Namespace: this.namespace || DEFAULT_NAMESPACE,
Dimensions: [dimensionNames],
Metrics: metricDefinitions,
},
],
},
...this.defaultDimensions,
...this.dimensions,
...metricValues,
...this.metadata,
};
}
/**
* Set default dimensions that will be added to all metrics.
*
* This method will merge the provided dimensions with the existing default dimensions.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* // Default dimensions will contain both region and environment
* metrics.setDefaultDimensions({
* region: 'us-west-2',
* environment: 'prod',
* });
* ```
*
* @param dimensions - The dimensions to be added to the default dimensions object
*/
public setDefaultDimensions(dimensions: Dimensions | undefined): void {
const targetDimensions = {
...this.defaultDimensions,
...dimensions,
};
if (MAX_DIMENSION_COUNT <= Object.keys(targetDimensions).length) {
throw new Error('Max dimension count hit');
}
this.defaultDimensions = targetDimensions;
}
/**
* Set the function name to be added to each metric as a dimension.
*
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the function
* name is automatically inferred from the Lambda context.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.setFunctionName('my-function-name');
* ```
*
* @param name - The function name
*/
public setFunctionName(name: string): void {
this.functionName = name;
}
/**
* Set the flag to throw an error if no metrics are emitted.
*
* You can use this method to enable or disable this opt-in feature. This is useful if you want to ensure
* that at least one metric is emitted when flushing the metrics. This can be useful to catch bugs where
* metrics are not being emitted as expected.
*
* @param enabled - Whether to throw an error if no metrics are emitted
*/
public setThrowOnEmptyMetrics(enabled: boolean): void {
this.shouldThrowOnEmptyMetrics = enabled;
}
/**
* Create a new Metrics instance configured to immediately flush a single metric.
*
* CloudWatch EMF uses the same dimensions and timestamp across all your metrics, this is useful when you have a metric that should have different dimensions
* or when you want to emit a single metric without buffering it.
*
* This method is used internally by the {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`} method to emit the `ColdStart` metric immediately
* after the handler function is called.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* const singleMetric = metrics.singleMetric();
* // The single metric will be emitted immediately
* singleMetric.addMetric('ColdStart', MetricUnit.Count, 1);
*
* // These other metrics will be buffered and emitted when calling `publishStoredMetrics()`
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
*/
public singleMetric(): Metrics {
return new Metrics({
namespace: this.namespace,
serviceName: this.dimensions.service,
defaultDimensions: this.defaultDimensions,
singleMetric: true,
});
}
/**
* @deprecated Use {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`} instead.
*/
public throwOnEmptyMetrics(): void {
this.shouldThrowOnEmptyMetrics = true;
}
/**
* Gets the current number of dimensions count.
*/
private getCurrentDimensionsCount(): number {
return (
Object.keys(this.dimensions).length +
Object.keys(this.defaultDimensions).length
);
}
/**
* Get the custom config service if it exists.
*/
private getCustomConfigService(): ConfigServiceInterface | undefined {
return this.customConfigService;
}
/**
* Get the environment variables service.
*/
private getEnvVarsService(): EnvironmentVariablesService {
return this.envVarsService as EnvironmentVariablesService;
}
/**
* Check if a metric is new or not.
*
* A metric is considered new if there is no metric with the same name already stored.
*
* When a metric is not new, we also check if the unit is consistent with the stored metric with
* the same name. If the units are inconsistent, we throw an error as this is likely a bug or typo.
* This can happen if a metric is added without using the `MetricUnit` helper in JavaScript codebases.
*
* @param name - The name of the metric
* @param unit - The unit of the metric
*/
private isNewMetric(name: string, unit: MetricUnit): boolean {
if (this.storedMetrics[name]) {
if (this.storedMetrics[name].unit !== unit) {
const currentUnit = this.storedMetrics[name].unit;
throw new Error(
`Metric "${name}" has already been added with unit "${currentUnit}", but we received unit "${unit}". Did you mean to use metric unit "${currentUnit}"?`
);
}
return false;
}
return true;
}
/**
* Initialize the console property as an instance of the internal version of `Console()` class (PR #748)
* or as the global node console if the `POWERTOOLS_DEV' env variable is set and has truthy value.
*
* @private
*/
private setConsole(): void {
if (!this.getEnvVarsService().isDevMode()) {
this.console = new Console({
stdout: process.stdout,
stderr: process.stderr,
});
} else {
this.console = console;
}
}
/**
* Set the custom config service to be used.
*
* @param customConfigService The custom config service to be used
*/
private setCustomConfigService(
customConfigService?: ConfigServiceInterface
): void {
this.customConfigService = customConfigService
? customConfigService
: undefined;
}
/**
* Set the environment variables service to be used.
*/
private setEnvVarsService(): void {
this.envVarsService = new EnvironmentVariablesService();
}
/**
* Set the namespace to be used.
*
* @param namespace - The namespace to be used
*/
private setNamespace(namespace: string | undefined): void {
this.namespace = (namespace ||
this.getCustomConfigService()?.getNamespace() ||
this.getEnvVarsService().getNamespace()) as string;
}
/**
* Set the options to be used by the Metrics instance.
*
* This method is used during the initialization of the Metrics instance.
*
* @param options - The options to be used
*/
private setOptions(options: MetricsOptions): Metrics {
const {
customConfigService,
namespace,
serviceName,
singleMetric,
defaultDimensions,
} = options;
this.setEnvVarsService();
this.setConsole();
this.setCustomConfigService(customConfigService);
this.setNamespace(namespace);
this.setService(serviceName);
this.setDefaultDimensions(defaultDimensions);
this.isSingleMetric = singleMetric || false;
return this;
}
/**
* Set the service to be used.
*
* @param service - The service to be used
*/
private setService(service: string | undefined): void {
const targetService =
((service ||
this.getCustomConfigService()?.getServiceName() ||
this.getEnvVarsService().getServiceName()) as string) ||
this.getDefaultServiceName();
if (targetService.length > 0) {
this.setDefaultDimensions({ service: targetService });
}
}
/**
* Store a metric in the buffer.
*
* If the buffer is full, or the metric reaches the maximum number of values,
* the metrics are flushed to stdout.
*
* @param name - The name of the metric to store
* @param unit - The unit of the metric to store
* @param value - The value of the metric to store
* @param resolution - The resolution of the metric to store
*/
private storeMetric(
name: string,
unit: MetricUnit,
value: number,
resolution: MetricResolution
): void {
if (Object.keys(this.storedMetrics).length >= MAX_METRICS_SIZE) {
this.publishStoredMetrics();
}
if (this.isNewMetric(name, unit)) {
this.storedMetrics[name] = {
unit,
value,
name,
resolution,
};
} else {
const storedMetric = this.storedMetrics[name];
if (!Array.isArray(storedMetric.value)) {
storedMetric.value = [storedMetric.value];
}
storedMetric.value.push(value);
if (storedMetric.value.length === MAX_METRIC_VALUES_SIZE) {
this.publishStoredMetrics();
}
}
}
}
export { Metrics };