Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(metrics): rename option property from raiseOnEmptyMetrics to throwOnEmptyMetrics #416

Merged
merged 4 commits into from
Jan 7, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions docs/core/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,12 +274,12 @@ You can flush metrics automatically using one of the following methods:
* [Middy-compatible](https://github.com/middyjs/middy){target=_blank} middleware
* class decorator

Using the Middy middleware or decorator will **automatically validate, serialize, and flush** all your metrics. During metrics validation, if no metrics are provided then a warning will be logged, but no exception will be raised.
Using the Middy middleware or decorator will **automatically validate, serialize, and flush** all your metrics. During metrics validation, if no metrics are provided then a warning will be logged, but no exception will be thrown.
If you do not use the middleware or decorator, you have to flush your metrics manually.


!!! warning "Metric validation"
If metrics are provided, and any of the following criteria are not met, a **`RangeError`** exception will be raised:
If metrics are provided, and any of the following criteria are not met, a **`RangeError`** exception will be thrown:

* Maximum of 9 dimensions
* Namespace is set only once (or none)
Expand Down Expand Up @@ -433,7 +433,7 @@ The `logMetrics` decorator of the metrics utility can be used when your Lambda h

dreamorosi marked this conversation as resolved.
Show resolved Hide resolved
#### Throwing a RangeError when no metrics are emitted

If you want to ensure that at least one metric is emitted before you flush them, you can use the `raiseOnEmptyMetrics` parameter and pass it to the middleware or decorator:
If you want to ensure that at least one metric is emitted before you flush them, you can use the `throwOnEmptyMetrics` parameter and pass it to the middleware or decorator:

```typescript hl_lines="11"
import { Metrics, MetricUnits, logMetrics } from '@aws-lambda-powertools/metrics';
Expand All @@ -446,7 +446,7 @@ If you want to ensure that at least one metric is emitted before you flush them,
}

export const handler = middy(lambdaHandler)
.use(logMetrics(metrics, { raiseOnEmptyMetrics: true }));
.use(logMetrics(metrics, { throwOnEmptyMetrics: true }));
```

### Capturing a cold start invocation as metric
Expand Down
4 changes: 2 additions & 2 deletions packages/metrics/examples/decorator/empty-metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ const metrics = new Metrics();
class Lambda implements LambdaInterface {

// Be default, we will not throw any error if there is no metrics. Use this property to override and throw an exception
@metrics.logMetrics({ raiseOnEmptyMetrics: true })
@metrics.logMetrics({ throwOnEmptyMetrics: true })
public handler<TEvent, TResult>(_event: TEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {
// Notice that no metrics are added
// Since the raiseOnEmptyMetrics parameter is set to true, the Powertool throw an Error
// Since the throwOnEmptyMetrics parameter is set to true, the Powertool throws an Error
}

}
Expand Down
4 changes: 2 additions & 2 deletions packages/metrics/examples/empty-metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ const metrics = new Metrics();

const lambdaHandler = async (): Promise<void> => {
// Notice that no metrics are added
// Since the raiseOnEmptyMetrics parameter is set to true, the Powertool throw an Error
// Since the throwOnEmptyMetrics parameter is set to true, the Powertool throws an Error
};

const handlerWithMiddleware = middy(lambdaHandler)
.use(logMetrics(metrics, { raiseOnEmptyMetrics: true }));
.use(logMetrics(metrics, { throwOnEmptyMetrics: true }));

handlerWithMiddleware(dummyEvent, dummyContext, () => console.log('Lambda invoked!'));
22 changes: 11 additions & 11 deletions packages/metrics/src/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const DEFAULT_NAMESPACE = 'default_namespace';
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the [@metrics.logMetrics()](./_aws_lambda_powertools_metrics.Metrics.html#logMetrics) decorator to automatically:
* * create cold start metric
* * flush buffered metrics
* * raise on empty metrics
* * throw on empty metrics
*
* @example
*
Expand All @@ -49,7 +49,7 @@ const DEFAULT_NAMESPACE = 'default_namespace';
*
dreamorosi marked this conversation as resolved.
Show resolved Hide resolved
* // FYI: Decorator might not render properly in VSCode mouse over due to https://github.com/microsoft/TypeScript/issues/39371 and might show as *@metrics* instead of `@metrics.logMetrics`
*
* @metrics.logMetrics({captureColdStartMetric: true, raiseOnEmptyMetrics: true, })
* @metrics.logMetrics({captureColdStartMetric: true, throwOnEmptyMetrics: true, })
* public handler(_event: any, _context: Context, _callback: Callback<any>): void | Promise<any> {
* // ...
* metrics.addMetric('test-metric', MetricUnits.Count, 10);
Expand Down Expand Up @@ -89,7 +89,7 @@ class Metrics implements MetricsInterface {
private isSingleMetric: boolean = false;
private metadata: { [key: string]: string } = {};
private namespace?: string;
private shouldRaiseOnEmptyMetrics: boolean = false;
private shouldThrowOnEmptyMetrics: boolean = false;
private storedMetrics: StoredMetrics = {};

public constructor(options: MetricsOptions = {}) {
Expand Down Expand Up @@ -202,7 +202,7 @@ class Metrics implements MetricsInterface {
}

/**
* A decorator automating coldstart capture, raise on empty metrics and publishing metrics on handler exit.
* A decorator automating coldstart capture, throw on empty metrics and publishing metrics on handler exit.
*
* @example
*
Expand All @@ -227,9 +227,9 @@ class Metrics implements MetricsInterface {
* @decorator Class
*/
public logMetrics(options: ExtraOptions = {}): HandlerMethodDecorator {
dreamorosi marked this conversation as resolved.
Show resolved Hide resolved
const { raiseOnEmptyMetrics, defaultDimensions, captureColdStartMetric } = options;
if (raiseOnEmptyMetrics) {
this.raiseOnEmptyMetrics();
const { throwOnEmptyMetrics, defaultDimensions, captureColdStartMetric } = options;
if (throwOnEmptyMetrics) {
this.throwOnEmptyMetrics();
}
if (defaultDimensions !== undefined) {
this.setDefaultDimensions(defaultDimensions);
Expand Down Expand Up @@ -293,13 +293,13 @@ class Metrics implements MetricsInterface {
* const metrics = new Metrics({namespace:"serverlessAirline", serviceName:"orders"});
*
* export const handler = async (event: any, context: Context) => {
* metrics.raiseOnEmptyMetrics();
* metrics.throwOnEmptyMetrics();
* metrics.publishStoredMetrics(); // will throw since no metrics added.
* }
* ```
*/
public raiseOnEmptyMetrics(): void {
this.shouldRaiseOnEmptyMetrics = true;
public throwOnEmptyMetrics(): void {
this.shouldThrowOnEmptyMetrics = true;
}

/**
Expand All @@ -312,7 +312,7 @@ class Metrics implements MetricsInterface {
Name: metricDefinition.name,
Unit: metricDefinition.unit,
}));
if (metricDefinitions.length === 0 && this.shouldRaiseOnEmptyMetrics) {
if (metricDefinitions.length === 0 && this.shouldThrowOnEmptyMetrics) {
throw new RangeError('The number of metrics recorded must be higher than zero');
}

Expand Down
6 changes: 3 additions & 3 deletions packages/metrics/src/middleware/middy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ const logMetrics = (target: Metrics | Metrics[], options: ExtraOptions = {}): mi
const logMetricsBefore = async (request: middy.Request): Promise<void> => {
metricsInstances.forEach((metrics: Metrics) => {
metrics.setFunctionName(request.context.functionName);
const { raiseOnEmptyMetrics, defaultDimensions, captureColdStartMetric } = options;
if (raiseOnEmptyMetrics !== undefined) {
metrics.raiseOnEmptyMetrics();
const { throwOnEmptyMetrics, defaultDimensions, captureColdStartMetric } = options;
if (throwOnEmptyMetrics !== undefined) {
metrics.throwOnEmptyMetrics();
}
if (defaultDimensions !== undefined) {
metrics.setDefaultDimensions(defaultDimensions);
Expand Down
4 changes: 2 additions & 2 deletions packages/metrics/src/types/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type HandlerMethodDecorator = (
* ```typescript
*
* const metricsOptions: MetricsOptions = {
* raiseOnEmptyMetrics: true,
* throwOnEmptyMetrics: true,
* defaultDimensions: {'environment': 'dev'},
* captureColdStartMetric: true,
* }
Expand All @@ -51,7 +51,7 @@ type HandlerMethodDecorator = (
* ```
*/
type ExtraOptions = {
raiseOnEmptyMetrics?: boolean
throwOnEmptyMetrics?: boolean
defaultDimensions?: Dimensions
captureColdStartMetric?: boolean
};
Expand Down
2 changes: 1 addition & 1 deletion packages/metrics/tests/e2e/decorator.test.MyFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const metrics = new Metrics({ namespace: namespace, service: serviceName });

class Lambda implements LambdaInterface {

@metrics.logMetrics({ captureColdStartMetric: true, defaultDimensions: JSON.parse(defaultDimensions), raiseOnEmptyMetrics: true })
@metrics.logMetrics({ captureColdStartMetric: true, defaultDimensions: JSON.parse(defaultDimensions), throwOnEmptyMetrics: true })
public async handler(_event: unknown, _context: Context): Promise<void> {
metrics.addMetric(metricName, metricUnit, parseInt(metricValue));
metrics.addDimension(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const metrics = new Metrics({ namespace: namespace, serviceName: serviceName });

export const handler = async (_event: unknown, _context: Context): Promise<void> => {
metrics.captureColdStartMetric();
metrics.raiseOnEmptyMetrics();
metrics.throwOnEmptyMetrics();
metrics.setDefaultDimensions(JSON.parse(defaultDimensions));
metrics.addMetric(metricName, metricUnit, parseInt(metricValue));
metrics.addDimension(
Expand Down
10 changes: 5 additions & 5 deletions packages/metrics/tests/unit/Metrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,13 +346,13 @@ describe('Class: Metrics', () => {
});
});

describe('Feature: raiseOnEmptyMetrics', () => {
test('Error should be thrown on empty metrics when raiseOnEmptyMetrics is passed', async () => {
describe('Feature: throwOnEmptyMetrics', () => {
test('Error should be thrown on empty metrics when throwOnEmptyMetrics is passed', async () => {
expect.assertions(1);

const metrics = new Metrics({ namespace: 'test' });
class LambdaFunction implements LambdaInterface {
@metrics.logMetrics({ raiseOnEmptyMetrics: true })
@metrics.logMetrics({ throwOnEmptyMetrics: true })
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
public handler<TEvent, TResult>(
Expand All @@ -371,12 +371,12 @@ describe('Class: Metrics', () => {
}
});

test('Error should be thrown on empty metrics when raiseOnEmptyMetrics() is callse', async () => {
test('Error should be thrown on empty metrics when throwOnEmptyMetrics() is callse', async () => {
expect.assertions(1);

const metrics = new Metrics({ namespace: 'test' });
const handler = async (_event: DummyEvent, _context: Context): Promise<void> => {
metrics.raiseOnEmptyMetrics();
metrics.throwOnEmptyMetrics();
// Logic goes here
metrics.publishStoredMetrics();
};
Expand Down
4 changes: 2 additions & 2 deletions packages/metrics/tests/unit/middleware/middy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ describe('Middy middleware', () => {
metrics.addMetric('successfulBooking', MetricUnits.Count, 1);
};
const metricsOptions: ExtraOptions = {
raiseOnEmptyMetrics: true,
throwOnEmptyMetrics: true,
defaultDimensions: { environment : 'prod', aws_region: 'eu-central-1' },
captureColdStartMetric: true
};
Expand Down Expand Up @@ -173,7 +173,7 @@ describe('Middy middleware', () => {
metrics.addMetric('successfulBooking', MetricUnits.Count, 1);
};
const metricsOptions: ExtraOptions = {
raiseOnEmptyMetrics: true
throwOnEmptyMetrics: true
};
const handler = middy(lambdaHandler).use(logMetrics([metrics], metricsOptions));

Expand Down