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

feat: add metrics #102

Merged
merged 28 commits into from
Aug 11, 2021
Merged
Show file tree
Hide file tree
Changes from 17 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
18 changes: 9 additions & 9 deletions packages/logger/src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import { ConfigServiceInterface, EnvironmentVariablesService } from './config';
import {
Environment,
HandlerMethodDecorator,
PowertoolLogData,
LambdaFunctionContext,
LogAttributes,
ClassThatLogs,
LoggerOptions,
LogItemExtraInput,
LogItemMessage,
LogLevel,
LogLevelThresholds,
LambdaFunctionContext,
LogItemMessage,
LogItemExtraInput,
PowertoolLogData,
} from '../types';
import { LogFormatterInterface, PowertoolLogFormatter } from './formatter';

Expand All @@ -33,7 +33,7 @@ class Logger implements ClassThatLogs {
private logLevel?: LogLevel;

private readonly logLevelThresholds: LogLevelThresholds = {
'DEBUG' : 8,
'DEBUG': 8,
'INFO': 12,
'WARN': 16,
'ERROR': 20
Expand Down Expand Up @@ -99,7 +99,7 @@ class Logger implements ClassThatLogs {
}

public injectLambdaContext(): HandlerMethodDecorator {
return (target, propertyKey, descriptor ) => {
return (target, propertyKey, descriptor) => {
const originalMethod = descriptor.value;

descriptor.value = (event, context, callback) => {
Expand Down Expand Up @@ -166,7 +166,7 @@ class Logger implements ClassThatLogs {
const attributes = (item instanceof Error) ? { error: item } : item;
logItem.addAttributes(attributes);
});

return logItem;
}

Expand Down Expand Up @@ -228,7 +228,7 @@ class Logger implements ClassThatLogs {
}

private setCustomConfigService(customConfigService?: ConfigServiceInterface): void {
this.customConfigService = customConfigService? customConfigService : undefined;
this.customConfigService = customConfigService ? customConfigService : undefined;
}

private setEnvVarsService(): void {
Expand Down Expand Up @@ -298,7 +298,7 @@ class Logger implements ClassThatLogs {
sampleRateValue: this.getSampleRateValue(),
serviceName: serviceName || this.getCustomConfigService()?.getServiceName() || this.getEnvVarsService().getServiceName(),
xRayTraceId: this.getEnvVarsService().getXrayTraceId(),
}, persistentLogAttributes );
}, persistentLogAttributes);
}

private shouldPrint(logLevel: LogLevel): boolean {
Expand Down
189 changes: 189 additions & 0 deletions packages/metrics/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
# `Metrics`


## Usage

```bash
npm run test

npm run example:hello-world
saragerion marked this conversation as resolved.
Show resolved Hide resolved
npm run example:hello-world
alan-churley marked this conversation as resolved.
Show resolved Hide resolved
npm run example:manual-flushing
npm run example:dimensions
npm run example:default-dimensions
npm run example:empty-metrics
npm run example:single-metric
npm run example:cold-start
```

### Getting started

Metrics has two global settings that will be used across all metrics emitted:

|Setting|Description|Environment Variable|Constructor Parameter|
|---|---|---|---|
|Metric namespace|Logical container where all metrics will be placed e.g. ServerlessAirline|POWERTOOLS_METRICS_NAMESPACE|namespace|
|Service|Optionally, sets service metric dimension across all metrics e.g. payment|POWERTOOLS_SERVICE_NAME|service|

```typescript
// Import the library
import { Metrics, MetricUnits } from '../src';
// When going public, it will be something like: import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';

process.env.POWERTOOLS_METRICS_NAMESPACE = 'hello-world';
process.env.POWERTOOLS_SERVICE_NAME = 'hello-world-service';
alan-churley marked this conversation as resolved.
Show resolved Hide resolved

// Instantiate the Logger with default configuration
const metrics = new metrics();
alan-churley marked this conversation as resolved.
Show resolved Hide resolved

// Add an example Metric
metrics.addMetric('test-metric', MetricUnits.Count, 10);

//Print resulting data
const metricsObject = metrics.serializeMetrics();
metrics.clearMetrics();
console.log(JSON.stringify(metricsObject));

```

<details>
<summary>Click to expand and see the logs outputs</summary>

```bash

{
"_aws":{
"Timestamp":1625587915573,
"CloudWatchMetrics":
[
{
"Namespace":"hello-world",
"Dimensions":[["service"]],
"Metrics":
[
{
"Name":"test-metric",
"Unit":"Count"
}
]
}
]
},
"service":"hello-world-service",
"test-metric":10
}

```
</details>

With decorators:

```typescript

import { Metrics, MetricUnits } from '../src';

process.env.POWERTOOLS_METRICS_NAMESPACE = 'hello-world';
process.env.POWERTOOLS_SERVICE_NAME = 'hello-world-service';

// Instantiate the Logger with default configuration
const metrics = new metrics();

class Lambda implements LambdaInterface {

@metrics.logMetrics()
public handler<TEvent, TResult>(_event: TEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {
metrics.addDimension('OuterDimension', 'true');
metrics.addMetric('test-metric', MetricUnits.Count, 10);
}

}

```

### Capturing cold start

By default the cold start metric is not captured, it can however be enabled using a parameter passed to the logMetrics decorator



```typescript

import { Metrics, MetricUnits } from '../src';

process.env.POWERTOOLS_METRICS_NAMESPACE = 'hello-world';
process.env.POWERTOOLS_SERVICE_NAME = 'hello-world-service';

// Instantiate the Logger with default configuration
const metrics = new metrics();

class Lambda implements LambdaInterface {

@metrics.logMetrics({ captureColdStartMetric: true }))
public handler<TEvent, TResult>(_event: TEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {
metrics.addDimension('OuterDimension', 'true');
metrics.addMetric('test-metric', MetricUnits.Count, 10);
}

}

```
> Please note, we do not emit a 0 value for the ColdStart metric, for cost reasons
<details>
<summary>Click to expand and see the logs outputs</summary>

```bash

{
"_aws":{
"Timestamp":1625587915572,
"CloudWatchMetrics":
[
{
"Namespace":"hello-world",
"Dimensions":[[
"service","function_name"
]],
"Metrics":
[
{
"Name":"ColdStart",
"Unit":"Count"
}
]
}
]
},
"service":"hello-world-service",
"function_name":"foo-bar-function",
"ColdStart":1
}
{
"_aws":{
"Timestamp":1625587915573,
"CloudWatchMetrics":
[
{
"Namespace":"hello-world",
"Dimensions":[["service"]],
"Metrics":
[
{
"Name":"test-metric",
"Unit":"Count"
}
]
}
]
},
"service":"hello-world-service",
"test-metric":10
}

```
</details>
If it's a cold start invocation, this feature will:

- Create a separate EMF blob solely containing a metric named ColdStart
- Add function_name and service dimensions

This has the advantage of keeping cold start metric separate from your application metrics, where you might have unrelated dimensions.
26 changes: 26 additions & 0 deletions packages/metrics/examples/cold-start.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as dummyEvent from '../../../tests/resources/events/custom/hello-world.json';
import { context as dummyContext } from '../../../tests/resources/contexts/hello-world';
import { LambdaInterface } from './utils/lambda/LambdaInterface';
import { populateEnvironmentVariables } from '../tests/helpers';
import { Callback, Context } from 'aws-lambda/handler';
import { Metrics, MetricUnits } from '../src';

// Populate runtime
populateEnvironmentVariables();
// Additional runtime variables
process.env.POWERTOOLS_METRICS_NAMESPACE = 'hello-world';

const metrics = new Metrics();

class Lambda implements LambdaInterface {

@metrics.logMetrics({ captureColdStartMetric: true })
public handler<TEvent, TResult>(_event: TEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {
metrics.addDimension('OuterDimension', 'true');
metrics.addMetric('test-metric', MetricUnits.Count, 10);
}

}

new Lambda().handler(dummyEvent, dummyContext, () => console.log('Lambda invoked!'));
new Lambda().handler(dummyEvent, dummyContext, () => console.log('Lambda invoked again!'));
33 changes: 33 additions & 0 deletions packages/metrics/examples/default-dimensions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { populateEnvironmentVariables } from '../tests/helpers';

// Populate runtime
populateEnvironmentVariables();
// Additional runtime variables
process.env.POWERTOOLS_METRICS_NAMESPACE = 'hello-world';

import * as dummyEvent from '../../../tests/resources/events/custom/hello-world.json';
import { context as dummyContext } from '../../../tests/resources/contexts/hello-world';
import { LambdaInterface } from './utils/lambda/LambdaInterface';
import { Callback, Context } from 'aws-lambda/handler';
import { Metrics, MetricUnits } from '../src';

const metrics = new Metrics();
alan-churley marked this conversation as resolved.
Show resolved Hide resolved

class Lambda implements LambdaInterface {

@metrics.logMetrics({ defaultDimensions:{ 'application': 'hello-world' } })
public handler<TEvent, TResult>(_event: TEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {

metrics.addDimension('environment', 'dev');
metrics.addDimension('application', 'hello-world-dev');
saragerion marked this conversation as resolved.
Show resolved Hide resolved
metrics.addMetric('test-metric', MetricUnits.Count, 10);
const metricsObject = metrics.serializeMetrics();
metrics.clearMetrics();
metrics.clearDimensions();
metrics.addMetric('new-test-metric', MetricUnits.Count, 5);
console.log(JSON.stringify(metricsObject));
}

}

new Lambda().handler(dummyEvent, dummyContext, () => console.log('Lambda invoked!'));
28 changes: 28 additions & 0 deletions packages/metrics/examples/dimensions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { populateEnvironmentVariables } from '../tests/helpers';

// Populate runtime
populateEnvironmentVariables();
// Additional runtime variables
process.env.POWERTOOLS_METRICS_NAMESPACE = 'hello-world';

import * as dummyEvent from '../../../tests/resources/events/custom/hello-world.json';
import { context as dummyContext } from '../../../tests/resources/contexts/hello-world';
import { LambdaInterface } from './utils/lambda/LambdaInterface';
import { Callback, Context } from 'aws-lambda/handler';
import { Metrics, MetricUnits } from '../src';

const metrics = new Metrics();

class Lambda implements LambdaInterface {

@metrics.logMetrics()
public handler<TEvent, TResult>(_event: TEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {

metrics.addDimension('environment', 'dev');
metrics.addMetric('test-metric', MetricUnits.Count, 10);

}

}

new Lambda().handler(dummyEvent, dummyContext, () => console.log('Lambda invoked!'));
25 changes: 25 additions & 0 deletions packages/metrics/examples/empty-metrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { populateEnvironmentVariables } from '../tests/helpers';

// Populate runtime
populateEnvironmentVariables();
// Additional runtime variables
process.env.POWERTOOLS_METRICS_NAMESPACE = 'hello-world';

import * as dummyEvent from '../../../tests/resources/events/custom/hello-world.json';
import { context as dummyContext } from '../../../tests/resources/contexts/hello-world';
import { LambdaInterface } from './utils/lambda/LambdaInterface';
import { Callback, Context } from 'aws-lambda/handler';
import { Metrics } from '../src';

const metrics = new Metrics();

class Lambda implements LambdaInterface {

@metrics.logMetrics({ raiseOnEmptyMetrics: true })
saragerion marked this conversation as resolved.
Show resolved Hide resolved
public handler<TEvent, TResult>(_event: TEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {

}

}

new Lambda().handler(dummyEvent, dummyContext, () => console.log('Lambda invoked!'));
Loading