Skip to content

Commit 5956e8d

Browse files
committed
chore(metrics): clean up MetricsInterface & API links
1 parent 404b302 commit 5956e8d

File tree

9 files changed

+849
-315
lines changed

9 files changed

+849
-315
lines changed

packages/metrics/README.md

Lines changed: 36 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
1-
# Powertools for AWS Lambda (TypeScript) <!-- omit in toc -->
1+
# Powertools for AWS Lambda (TypeScript)
22

33
Powertools for AWS Lambda (TypeScript) is a developer toolkit to implement Serverless [best practices and increase developer velocity](https://docs.powertools.aws.dev/lambda/typescript/latest/#features).
44

55
You can use the library in both TypeScript and JavaScript code bases.
66

7-
- [Intro](#intro)
87
- [Usage](#usage)
9-
- [Basic usage](#basic-usage)
108
- [Flushing metrics](#flushing-metrics)
119
- [Capturing cold start as a metric](#capturing-cold-start-as-a-metric)
12-
- [Adding metadata](#adding-metadata)
10+
- [Class method decorator](#class-method-decorator)
11+
- [Middy.js middleware](#middyjs-middleware)
1312
- [Contribute](#contribute)
1413
- [Roadmap](#roadmap)
1514
- [Connect](#connect)
@@ -19,134 +18,80 @@ You can use the library in both TypeScript and JavaScript code bases.
1918
- [Using Lambda Layer](#using-lambda-layer)
2019
- [License](#license)
2120

22-
## Intro
23-
2421
## Usage
2522

23+
The library provides a utility function to emit metrics to CloudWatch using [Embedded Metric Format (EMF)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html).
24+
2625
To get started, install the library by running:
2726

2827
```sh
2928
npm i @aws-lambda-powertools/metrics
3029
```
3130

32-
### Basic usage
33-
34-
The library provides a utility function to emit metrics to CloudWatch using [Embedded Metric Format (EMF)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html).
31+
After initializing the Metrics class, you can add metrics using the [Metrics.addMetric](`addMetric()`) method. The metrics are stored in a buffer and are flushed when calling [Metrics.publishStoredMetrics](`publishStoredMetrics()`). Each metric can have dimensions and metadata added to it.
3532

3633
```ts
37-
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
34+
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
3835

3936
const metrics = new Metrics({
4037
namespace: 'serverlessAirline',
4138
serviceName: 'orders',
39+
defaultDimensions: { environment: process.env.ENVIRONMENT },
4240
});
4341

44-
export const handler = async (
45-
_event: unknown,
46-
_context: unknown
47-
): Promise<void> => {
42+
export const handler = async (event: { requestId: string }) => {
43+
metrics.addMetadata('request_id', event.requestId);
4844
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
45+
metrics.publishStoredMetrics();
4946
};
5047
```
5148

5249
### Flushing metrics
5350

54-
As you finish adding all your metrics, you need to serialize and "flush them" by calling publishStoredMetrics(). This will print the metrics to standard output.
55-
56-
You can flush metrics automatically using one of the following methods:
57-
58-
- manually by calling `publishStoredMetrics()` at the end of your Lambda function
59-
60-
```ts
61-
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
62-
63-
const metrics = new Metrics({
64-
namespace: 'serverlessAirline',
65-
serviceName: 'orders',
66-
});
67-
68-
export const handler = async (
69-
_event: unknown,
70-
_context: unknown
71-
): Promise<void> => {
72-
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
73-
metrics.publishStoredMetrics();
74-
};
75-
```
76-
77-
- middy compatible middleware `logMetrics()`
51+
As you finish adding all your metrics, you need to serialize and "flush them" by calling [publishStoredMetrics()](`publishStoredMetrics()`), which will emit the metrics to stdout in the Embedded Metric Format (EMF). The metrics are then picked up by the Lambda runtime and sent to CloudWatch.
7852

79-
```ts
80-
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
81-
import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
82-
import middy from '@middy/core';
53+
When you
8354

84-
const metrics = new Metrics({
85-
namespace: 'serverlessAirline',
86-
serviceName: 'orders',
87-
});
55+
### Capturing cold start as a metric
8856

89-
const lambdaHandler = async (
90-
_event: unknown,
91-
_context: unknown
92-
): Promise<void> => {
93-
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
94-
};
57+
You can flush metrics automatically using one of the following methods:
9558

96-
export const handler = middy(lambdaHandler).use(logMetrics(metrics));
97-
```
59+
### Class method decorator
9860

99-
- using decorator `@logMetrics()`
61+
If you are using TypeScript and are comfortable with writing classes, you can use the `@logMetrics()` decorator to automatically flush metrics at the end of your Lambda function as well as configure additional options such as throwing an error if no metrics are added, capturing cold start as a metric, and more.
10062

10163
```ts
64+
import type { Context } from 'aws-lambda';
10265
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
103-
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
66+
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
10467

10568
const metrics = new Metrics({
10669
namespace: 'serverlessAirline',
10770
serviceName: 'orders',
10871
});
10972

11073
class Lambda implements LambdaInterface {
111-
@metrics.logMetrics()
112-
public async handler(_event: unknown, _context: unknown): Promise<void> {
74+
⁣@metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
75+
public async handler(event: { requestId: string }, _: Context) {
76+
metrics.addMetadata('request_id', event.requestId);
11377
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
11478
}
11579
}
11680

11781
const handlerClass = new Lambda();
118-
export const handler = handlerClass.handler.bind(handlerClass);
82+
export const handler = handlerClass.handler.bind(handlerClass);
11983
```
12084

121-
Using the Middy middleware or decorator will automatically validate, serialize, and flush all your metrics.
122-
123-
### Capturing cold start as a metric
124-
125-
You can optionally capture cold start metrics with the logMetrics middleware or decorator via the captureColdStartMetric param.
126-
127-
```ts
128-
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
129-
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
130-
131-
const metrics = new Metrics({
132-
namespace: 'serverlessAirline',
133-
serviceName: 'orders',
134-
});
85+
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.
13586

136-
export class MyFunction implements LambdaInterface {
137-
@metrics.logMetrics({ captureColdStartMetric: true })
138-
public async handler(_event: unknown, _context: unknown): Promise<void> {
139-
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
140-
}
141-
}
142-
```
87+
### Middy.js middleware
14388

144-
### Adding metadata
89+
If instead you are using [Middy.js](http://middy.js.org) and prefer to use middleware, you can use the `@logMetrics()` middleware to do the same as the class method decorator.
14590

146-
You can add high-cardinality data as part of your Metrics log with the `addMetadata` method. This is useful when you want to search highly contextual information along with your metrics in your logs.
91+
The `@logMetrics()` middleware can be used with Middy.js to automatically flush metrics at the end of your Lambda function as well as configure additional options such as throwing an error if no metrics are added, capturing cold start as a metric, and set default dimensions.
14792

14893
```ts
149-
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
94+
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
15095
import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
15196
import middy from '@middy/core';
15297

@@ -155,17 +100,17 @@ const metrics = new Metrics({
155100
serviceName: 'orders',
156101
});
157102

158-
const lambdaHandler = async (
159-
_event: unknown,
160-
_context: unknown
161-
): Promise<void> => {
103+
export const handler = middy(async (event) => {
104+
metrics.addMetadata('request_id', event.requestId);
162105
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
163-
metrics.addMetadata('bookingId', '7051cd10-6283-11ec-90d6-0242ac120003');
164-
};
165-
166-
export const handler = middy(lambdaHandler).use(logMetrics(metrics));
106+
}).use(logMetrics(metrics, {
107+
captureColdStartMetric: true,
108+
throwOnEmptyMetrics: true,
109+
}));
167110
```
168111

112+
The `logMetrics()` middleware is compatible with `@middy/[email protected]` and above.
113+
169114
## Contribute
170115

171116
If you are interested in contributing to this project, please refer to our [Contributing Guidelines](https://github.com/aws-powertools/powertools-lambda-typescript/blob/main/CONTRIBUTING.md).

0 commit comments

Comments
 (0)