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

High Resolution Metrics Support #142

Merged
merged 16 commits into from
Jan 23, 2023
27 changes: 19 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,13 @@ To get a metric logger, you can either decorate your function with a metricScope
Using the metricScope decorator without function parameters:

```js
const { metricScope, Unit } = require("aws-embedded-metrics");
const { metricScope, Unit, StorageResolution } = require("aws-embedded-metrics");

const myFunc = metricScope(metrics =>
async () => {
metrics.putDimensions({ Service: "Aggregator" });
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds);
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds, StorageResolution.Standard);
metrics.putMetric("Memory.HeapUsed", 1600424.0, Unit.Bytes, StorageResolution.High);
metrics.setProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8");
// ...
});
Expand All @@ -54,12 +55,13 @@ await myFunc();
Using the metricScope decorator with function parameters:

```js
const { metricScope, Unit } = require("aws-embedded-metrics");
const { metricScope, Unit, StorageResolution } = require("aws-embedded-metrics");

const myFunc = metricScope(metrics =>
async (param1: string, param2: number) => {
metrics.putDimensions({ Service: "Aggregator" });
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds);
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds, StorageResolution.Standard);
metrics.putMetric("Memory.HeapUsed", 1600424.0, Unit.Bytes, StorageResolution.High);
metrics.setProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8");
// ...
});
Expand All @@ -70,12 +72,13 @@ await myFunc('myParam', 0);
Manually constructing and flushing the logger:

```js
const { createMetricsLogger, Unit } = require("aws-embedded-metrics");
const { createMetricsLogger, Unit, StorageResolution } = require("aws-embedded-metrics");

const myFunc = async () => {
const metrics = createMetricsLogger();
metrics.putDimensions({ Service: "Aggregator" });
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds);
metrics.putMetric("ProcessingLatency", 100, Unit.Milliseconds, StorageResolution.Standard);
metrics.putMetric("Memory.HeapUsed", 1600424.0, Unit.Bytes, StorageResolution.High);
metrics.setProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8");
// ...
await metrics.flush();
Expand Down Expand Up @@ -105,20 +108,28 @@ exports.handler = myFunc;

The `MetricLogger` is the interface you will use to publish embedded metrics.

- **putMetric**(String name, Double value, Unit? unit)
- **putMetric**(String name, Double value, Unit? unit, StorageResolution? storageResolution)

Adds a new metric to the current logger context. Multiple metrics using the same key will be appended to an array of values. The Embedded Metric Format supports a maximum of 100 values per key. If more metric values are added than are supported by the format, the logger will be flushed to allow for new metric values to be captured.
Adds a new metric to the current logger context. Multiple metrics using the same key will be appended to an array of values. Multiple metrics cannot have same key and different storage resolution. The Embedded Metric Format supports a maximum of 100 values per key. If more metric values are added than are supported by the format, the logger will be flushed to allow for new metric values to be captured.

Requirements:
- Name Length 1-255 characters
- Name must be ASCII characters only
- Values must be in the range of 8.515920e-109 to 1.174271e+108. In addition, special values (for example, NaN, +Infinity, -Infinity) are not supported.
- Metrics must meet CloudWatch Metrics requirements, otherwise a `InvalidMetricError` will be thrown. See [MetricDatum](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html) for valid values.

##### Storage Resolution
An OPTIONAL value representing the storage resolution for the corresponding metric. Setting this to `High` specifies this metric as a high-resolution metric, so that CloudWatch stores the metric with sub-minute resolution down to one second. Setting this to `Standard` specifies this metric as a standard-resolution metric, which CloudWatch stores at 1-minute resolution. If a value is not provided, then a default value of `Standard` is assumed. See [Cloud Watch High-Resolution metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html#high-resolution-metrics)

Examples:

```js
// Standard Resolution example
putMetric("Latency", 200, Unit.Milliseconds)
putMetric("Latency", 201, Unit.Milliseconds, StorageResolution.Standard)

// High Resolution example
putMetric("Memory.HeapUsed", 1600424.0, Unit.Bytes, StorageResolution.High);
```

- **setProperty**(String key, Object value)
Expand Down
3 changes: 2 additions & 1 deletion examples/agent/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const { metricScope, Unit } = require('aws-embedded-metrics');
const { metricScope, Unit, StorageResolution } = require('aws-embedded-metrics');

const doWork = metricScope(metrics => async event => {
metrics.putDimensions({ Operation: 'Agent' });
metrics.putMetric('ExampleMetric', 100, Unit.Milliseconds);
metrics.putMetric('ExampleHighResolutionMetric', 10, Unit.Milliseconds, StorageResolution.High);
metrics.setProperty('RequestId', '422b1569-16f6-4a03-b8f0-fe3fd9b100f8');
});

Expand Down
3 changes: 2 additions & 1 deletion examples/ecs-firelens/app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const Koa = require('koa');
const app = new Koa();

const { metricScope, Unit } = require('aws-embedded-metrics');
const { metricScope, Unit, StorageResolution } = require('aws-embedded-metrics');

app.use(
metricScope(metrics => async (ctx, next) => {
Expand All @@ -14,6 +14,7 @@ app.use(
metrics.setProperty('Method', ctx.method);
metrics.setProperty('Url', ctx.url);
metrics.putMetric('ProcessingTime', Date.now() - start, Unit.Milliseconds);
metrics.putMetric('ProcessingLatency', 100, Unit.Milliseconds, StorageResolution.High);

// send application logs to stdout, FireLens will send this to a different LogGroup
console.log('Completed Request');
Expand Down
3 changes: 2 additions & 1 deletion examples/eks/app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const Koa = require('koa');
const app = new Koa();

const { metricScope, Configuration, Unit } = require('aws-embedded-metrics');
const { metricScope, Configuration, Unit, StorageResolution } = require('aws-embedded-metrics');

Configuration.serviceName = 'EKS-Demo';
Configuration.serviceType = 'AWS::EKS::Cluster';
Expand All @@ -18,6 +18,7 @@ app.use(
metrics.setProperty('Method', ctx.method);
metrics.setProperty('Url', ctx.url);
metrics.putMetric('ProcessingTime', Date.now() - start, Unit.Milliseconds);
metrics.putMetric('ProcessingLatency', 100, Unit.Milliseconds, StorageResolution.High);
}),
);

Expand Down
3 changes: 2 additions & 1 deletion examples/lambda/src/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
const { metricScope } = require('aws-embedded-metrics');
const { metricScope, StorageResolution } = require('aws-embedded-metrics');

const aggregator = metricScope(metrics => async event => {
console.log('received message');
metrics.putDimensions({ Service: 'Aggregator' });
metrics.putMetric('ProcessingLatency', 100, 'Milliseconds');
metrics.putMetric('CPU Utilization', 87, 'Percent', StorageResolution.High);
metrics.setProperty('AccountId', '123456789012');
metrics.setProperty('RequestId', '422b1569-16f6-4a03-b8f0-fe3fd9b100f8');
metrics.setProperty('DeviceId', '61270781-c6ac-46f1-baf7-22c808af8162');
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export { AgentSink } from './sinks/AgentSink';
export { metricScope } from './logger/MetricScope';
export { createMetricsLogger } from './logger/MetricsLoggerFactory';
export { Unit } from './logger/Unit';
export { StorageResolution } from './logger/StorageResolution';

import Configuration from './config/Configuration';
export { Configuration };
5 changes: 4 additions & 1 deletion src/logger/MetricValues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,17 @@
*/

import { Unit } from '..';
import { StorageResolution } from './StorageResolution';

export class MetricValues {
public values: number[];
public unit: string;
public storageResolution: number;

constructor(value: number, unit?: Unit | string) {
constructor(value: number, unit?: Unit | string, storageResolution?: StorageResolution | number) {
this.values = [value];
this.unit = unit || 'None';
this.storageResolution = storageResolution || StorageResolution.Standard;
}

/**
Expand Down
14 changes: 11 additions & 3 deletions src/logger/MetricsContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import Configuration from '../config/Configuration';
import { LOG } from '../utils/Logger';
import { validateNamespace, validateTimestamp, validateDimensionSet, validateMetric } from '../utils/Validator';
import { MetricValues } from './MetricValues';
import { StorageResolution } from './StorageResolution';
import { Unit } from './Unit';

interface IProperties {
Expand All @@ -41,6 +42,7 @@ export class MetricsContext {
private defaultDimensions: Record<string, string>;
private shouldUseDefaultDimensions = true;
private timestamp: Date | number | undefined;
private metricNameAndResolutionMap: Map<string, StorageResolution> = new Map<string, StorageResolution>();

/**
* Constructor used to create child instances.
Expand Down Expand Up @@ -180,15 +182,21 @@ export class MetricsContext {
});
}

public putMetric(key: string, value: number, unit?: Unit | string): void {
validateMetric(key, value, unit);
public putMetric(
key: string,
value: number,
unit?: Unit | string,
storageResolution?: StorageResolution | number,
): void {
validateMetric(key, value, unit, storageResolution, this.metricNameAndResolutionMap);

const currentMetric = this.metrics.get(key);
if (currentMetric) {
currentMetric.addValue(value);
} else {
this.metrics.set(key, new MetricValues(value, unit));
this.metrics.set(key, new MetricValues(value, unit, storageResolution));
meshwa19 marked this conversation as resolved.
Show resolved Hide resolved
}
this.metricNameAndResolutionMap?.set(key, storageResolution || StorageResolution.Standard);
}

/**
Expand Down
11 changes: 9 additions & 2 deletions src/logger/MetricsLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { EnvironmentProvider } from '../environment/EnvironmentDetector';
import { IEnvironment } from '../environment/IEnvironment';
import { MetricsContext } from './MetricsContext';
import { Unit } from './Unit';
import { StorageResolution } from './StorageResolution';

/**
* An async metrics logger.
Expand Down Expand Up @@ -124,9 +125,15 @@ export class MetricsLogger {
* @param key
* @param value
* @param unit
* @param storageResolution
*/
public putMetric(key: string, value: number, unit?: Unit | string): MetricsLogger {
this.context.putMetric(key, value, unit);
public putMetric(
key: string,
value: number,
unit?: Unit | string,
storageResolution?: StorageResolution | number,
): MetricsLogger {
this.context.putMetric(key, value, unit, storageResolution);
return this;
}

Expand Down
19 changes: 19 additions & 0 deletions src/logger/StorageResolution.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export enum StorageResolution {
High = 1,
Standard = 60,
}
Loading