https://github.com/awslabs/aws-embedded-metrics-node

Amazon CloudWatch Embedded Metric Format Client Library

https://github.com/awslabs/aws-embedded-metrics-node

Science Score: 13.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (11.8%) to scientific vocabulary

Keywords from Contributors

diagram labels interaction cloud-infrastructure infrastructure-as-code
Last synced: 11 months ago · JSON representation

Repository

Amazon CloudWatch Embedded Metric Format Client Library

Basic Info
Statistics
  • Stars: 256
  • Watchers: 7
  • Forks: 38
  • Open Issues: 25
  • Releases: 16
Created almost 7 years ago · Last pushed over 1 year ago
Metadata Files
Readme Contributing License Code of conduct

README.md

aws-embedded-metrics

Generate CloudWatch Metrics embedded within structured log events. The embedded metrics will be extracted so you can visualize and alarm on them for real-time incident detection. This allows you to monitor aggregated values while preserving the detailed event context that generated them.

Use Cases

  • Generate custom metrics across compute environments

    • Easily generate custom metrics from Lambda functions without requiring custom batching code, making blocking network requests or relying on 3rd party software.
    • Other compute environments (EC2, On-prem, ECS, EKS, and other container environments) are supported by installing the CloudWatch Agent.
    • Examples can be found in examples/README.md
  • Linking metrics to high cardinality context

Using the Embedded Metric Format, you will be able to visualize and alarm on custom metrics, but also retain the original, detailed and high-cardinality context which is queryable using CloudWatch Logs Insights. For example, the library automatically injects environment metadata such as Lambda Function version, EC2 instance and image ids into the structured log event data.

Installation

npm install aws-embedded-metrics

Important Versions 4.1.1+, 3.0.2+, 2.0.7+ are required for usage in Lambda with JSON log format. Using previous versions in such Lambda environments will lead to metric loss.

Usage

To get a metric logger, you can either decorate your function with a metricScope, or manually create and flush the logger.

Using the metricScope decorator without function parameters:

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

const myFunc = metricScope(metrics => async () => { metrics.putDimensions({ Service: "Aggregator" }); 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 myFunc(); ```

Using the metricScope decorator with function parameters:

```js 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, StorageResolution.Standard); metrics.putMetric("Memory.HeapUsed", 1600424.0, Unit.Bytes, StorageResolution.High); metrics.setProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8"); // ... });

await myFunc('myParam', 0); ```

Manually constructing and flushing the logger:

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

const myFunc = async () => { const metrics = createMetricsLogger(); metrics.putDimensions({ Service: "Aggregator" }); 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(); };

await myFunc(); ```

Lambda

If you are running on Lambda, export your function like so:

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

const myFunc = metricScope(metrics => async () => { // ... });

exports.handler = myFunc; ```

API

MetricLogger

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

  • 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. 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 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

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)

Adds or updates the value for a given property on this context. This value is not submitted to CloudWatch Metrics but is searchable by CloudWatch Logs Insights. This is useful for contextual and potentially high-cardinality data that is not appropriate for CloudWatch Metrics dimensions.

Requirements: - Length 1-255 characters

Examples: js setProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8") setProperty("InstanceId", "i-1234567890") setProperty("Device", { Id: "61270781-c6ac-46f1-baf7-22c808af8162", Name: "Transducer", Model: "PT-1234" }); - putDimensions(Record dimensions)

Adds a new set of dimensions that will be associated to all metric values.

WARNING: Every distinct value will result in a new CloudWatch Metric. If the cardinality of a particular value is expected to be high, you should consider using setProperty instead.

Requirements: - Length 1-255 characters - ASCII characters only - Dimensions must meet CloudWatch Dimensions requirements, otherwise a InvalidDimensionError or DimensionSetExceededError will be thrown. See Dimensions for valid values.

Examples: js putDimensions({ Operation: "Aggregator" }) putDimensions({ Operation: "Aggregator", DeviceType: "Actuator" })

  • setDimensions(Record | Record[] dimensions, boolean useDefault)

Explicitly override all dimensions. This will remove the default dimensions unless the useDefault parameter is set to true (defaults to false).

WARNING: Every distinct value will result in a new CloudWatch Metric. If the cardinality of a particular value is expected to be high, you should consider using setProperty instead.

Requirements: - Length 1-255 characters - ASCII characters only - Dimensions must meet CloudWatch Dimensions requirements, otherwise a InvalidDimensionError or DimensionSetExceededError will be thrown. See Dimensions for valid values.

Examples:

js // Overwrites custom dimensions - keeps default dimensions setDimensions({Operation: "Aggregator"}, true)

js // Overwrites custom dimensions - removes default dimensions setDimensions([ { Operation: "Aggregator" }, { Operation: "Aggregator", DeviceType: "Actuator" } ])

  • resetDimensions(boolean useDefault)

Explicitly clear all custom dimensions. Set useDefault to true to keep the default dimensions.

Example:

js resetDimensions(false) // this will clear all custom dimensions as well as disable default dimensions

  • setNamespace(String value)

Sets the CloudWatch namespace that extracted metrics should be published to. If not set, a default value of aws-embedded-metrics will be used.

Requirements:

  • Name Length 1-255 characters
  • Name must be ASCII characters only
  • Namespaces must meet CloudWatch Namespace requirements, otherwise a InvalidNamespaceError will be thrown. See Namespace for valid values.

Example:

js setNamespace("MyApplication");

  • setTimestamp(Date | number timestamp)

Sets the CloudWatch timestamp that extracted metrics are associated with. If not set a default value of new Date() will be used.

If set for a given MetricsLogger, timestamp will be preserved across calls to flush().

Requirements: * Date or Unix epoch millis, up to two weeks in the past and up to two hours in the future, as enforced by CloudWatch. If the timestamp is outside of this range, a InvalidTimestampError will be thrown.

Examples:

js setTimestamp(new Date()) setTimestamp(new Date().getTime())

  • flush()

Flushes the current MetricsContext to the configured sink and resets all properties and metric values. The namespace and default dimensions will be preserved across flushes. Custom dimensions are preserved by default, but this behavior can be changed by setting logger.flushPreserveDimensions = false. Timestamp will be preserved if set explicitly via setTimestamp().

Examples:

js logger.flush() // custom and default dimensions will be preserved after each flush

js logger.flushPreserveDimensions = false logger.flush() // only default dimensions will be preserved after flush()

js logger.flushPreserveDimensions = false logger.resetDimensions(false) logger.flush() // default dimensions are disabled - no dimensions will be preserved after flush()

Configuration

All configuration values can be set using environment variables with the prefix (AWS_EMF_). Configuration should be performed as close to application start up as possible.

ServiceName: Overrides the name of the service. For services where the name cannot be inferred (e.g. Java process running on EC2), a default value of Unknown will be used if not explicitly set.

Requirements:

  • Name Length 1-255 characters
  • Name must be ASCII characters only

Example:

```js // in process const { Configuration } = require("aws-embedded-metrics"); Configuration.serviceName = "MyApp";

// environment AWSEMFSERVICE_NAME=MyApp ```

ServiceType: Overrides the type of the service. For services where the type cannot be inferred (e.g. Java process running on EC2), a default value of Unknown will be used if not explicitly set.

Requirements:

  • Name Length 1-255 characters
  • Name must be ASCII characters only

Example:

```js // in process const { Configuration } = require("aws-embedded-metrics"); Configuration.serviceType = "NodeJSWebApp";

// environment AWSEMFSERVICE_TYPE=NodeJSWebApp ```

LogGroupName: For agent-based platforms, you may optionally configure the destination log group that metrics should be delivered to. This value will be passed from the library to the agent in the Embedded Metric payload. If a LogGroup is not provided, the default value will be derived from the service name: -metrics

Requirements: - Name Length 1-512 characters - Log group names consist of the following characters: a-z, A-Z, 0-9, '_' (underscore), '-' (hyphen), '/' (forward slash), and '.' (period). Pattern: [.-_/#A-Za-z0-9]+

Example:

```js // in process const { Configuration } = require("aws-embedded-metrics"); Configuration.logGroupName = "LogGroupName";

// environment AWSEMFLOGGROUPNAME=LogGroupName ```

LogStreamName: For agent-based platforms, you may optionally configure the destination log stream that metrics should be delivered to. This value will be passed from the library to the agent in the Embedded Metric payload. If a LogGroup is not provided, the default value will be derived by the agent (this will likely be the hostname).

Requirements:

  • Name Length 1-512 characters
  • The ':' (colon) and '*' (asterisk) characters are not allowed. Pattern: [^:]*

Example:

```js // in process const { Configuration } = require("aws-embedded-metrics"); Configuration.logStreamName = "LogStreamName";

// environment AWSEMFLOGSTREAMNAME=LogStreamName ```

AgentEndpoint: For agent-based platforms, you may optionally configure the endpoint to reach the agent on.

Example:

```js // in process const { Configuration } = require("aws-embedded-metrics"); Configuration.agentEndpoint = "udp://127.0.0.1:1000";

// environment AWSEMFAGENT_ENDPOINT="udp://127.0.0.1:1000" ```

EnvironmentOverride: Short circuit auto-environment detection by explicitly defining how events should be sent. This is not supported through programatic access due to #43.

Valid values include:

  • Local: no decoration and sends over stdout
  • Lambda: decorates logs with Lambda metadata and sends over stdout
  • Agent: no decoration and sends over TCP
  • EC2: decorates logs with EC2 metadata and sends over TCP
  • ECS: decorates logs with ECS metadata and enables support for Firelens

Example:

js AWS_EMF_ENVIRONMENT=Local

EnableDebugLogging: Enable debug logging for the library. If the library is not behaving as expected, you can set this to true to log to console.

Example:

```js // in process const { Configuration } = require("aws-embedded-metrics"); Configuration.debuggingLoggingEnabled = true;

// environment AWSEMFENABLEDEBUGLOGGING=true ```

Namespace: Sets the CloudWatch namespace that extracted metrics should be published to. If not set, a default value of aws-embedded-metrics will be used.

Requirements:

  • Name Length 1-255 characters
  • Name must be ASCII characters only

Example:

```js // in process const { Configuration } = require("aws-embedded-metrics"); Configuration.namespace = "Namespace";

// environment AWSEMFNAMESPACE=Namespace ```

Examples

Check out the examples directory to get started.

Testing Examples

Check out the unit test examples directory to get started. Here we provide a few examples to help you write tests against code that depends on this package.

Development

Building

This project uses Volta to pin the currently supported version of node.

npm i && npm run build

Running Locally

If you are running the CW agent locally, you can test the workflow:

npm i && npm link cd examples/agent && npm link aws-embedded-metrics

After linking you'll need to rebuild any changes:

npm run build

Testing

We have 2 different types of tests: 1. Unit tests which can be run using the following commands: sh npm test # or npm run watch 2. Integration tests. These tests require Docker to run the CloudWatch Agent and valid AWS credentials. Tests can be run by: export AWS_ACCESS_KEY_ID= export AWS_SECRET_ACCESS_KEY= export AWS_REGION=us-west-2 npm run integ

Formatting

We use Prettier for auto-formatting. You should install the plugin for your editor-of-choice and enabled format-on-save.

License

This project is licensed under the Apache-2.0 License.

Owner

  • Name: Amazon Web Services - Labs
  • Login: awslabs
  • Kind: organization
  • Location: Seattle, WA

AWS Labs

GitHub Events

Total
  • Issues event: 5
  • Watch event: 6
  • Issue comment event: 2
  • Push event: 2
  • Pull request review comment event: 2
  • Pull request review event: 5
  • Pull request event: 8
  • Fork event: 3
Last Year
  • Issues event: 5
  • Watch event: 6
  • Issue comment event: 2
  • Push event: 2
  • Pull request review comment event: 2
  • Pull request review event: 5
  • Pull request event: 8
  • Fork event: 3

Committers

Last synced: about 3 years ago

All Time
  • Total Commits: 106
  • Total Committers: 23
  • Avg Commits per committer: 4.609
  • Development Distribution Score (DDS): 0.623
Past Year
  • Commits: 25
  • Committers: 8
  • Avg Commits per committer: 3.125
  • Development Distribution Score (DDS): 0.6
Top Committers
Name Email Commits
Jared Nance j****e@g****m 40
Jared Nance j****e@a****m 14
dependabot[bot] 4****]@u****m 12
Mark Kuhn k****r@a****m 10
Mark Kuhn k****k@o****m 4
Reed Hermes 4****2@u****m 4
Grundlefleck g****k@g****m 3
Meshwa Savalia 3****9@u****m 3
Himtanaya Bhadada h****a@g****m 2
Aaron Lamb a****3@g****m 1
Akshay Gupta D****c@u****m 1
Amazon GitHub Automation 5****o@u****m 1
Dane Springmeyer d****e@m****m 1
David Clark d****k@g****m 1
Isaac Levy i****y@g****m 1
Glen Thomas 4****g@u****m 1
Uldis Sturms u****s@g****m 1
Denis Salamanca 3****S@u****m 1
Khang Ly k****y@y****m 1
Michael Hart m****u@g****m 1
Michael Wolfenden m****n@u****m 1
Himtanaya Bhadada h****y@a****m 1
jeroenmeulendijks j****s@g****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 11 months ago

All Time
  • Total issues: 38
  • Total pull requests: 92
  • Average time to close issues: 5 months
  • Average time to close pull requests: about 1 month
  • Total issue authors: 30
  • Total pull request authors: 27
  • Average comments per issue: 2.47
  • Average comments per pull request: 0.7
  • Merged pull requests: 66
  • Bot issues: 0
  • Bot pull requests: 31
Past Year
  • Issues: 3
  • Pull requests: 12
  • Average time to close issues: N/A
  • Average time to close pull requests: 15 days
  • Issue authors: 3
  • Pull request authors: 6
  • Average comments per issue: 0.0
  • Average comments per pull request: 0.17
  • Merged pull requests: 6
  • Bot issues: 0
  • Bot pull requests: 3
Top Authors
Issue Authors
  • kaihendry (3)
  • jaredcnance (3)
  • simonespa (3)
  • davidtheclark (2)
  • PascalPflaum (2)
  • trivikr (1)
  • davidweimapbox (1)
  • rnewman (1)
  • madsbrunn (1)
  • pclohar (1)
  • andybalham (1)
  • ajpower (1)
  • carlbergman (1)
  • brettswift (1)
  • mtwilliams5 (1)
Pull Request Authors
  • dependabot[bot] (35)
  • jaredcnance (14)
  • markkuhn (13)
  • seoberha (4)
  • Himtanaya (4)
  • meshwa19 (3)
  • gordonpn (3)
  • kdybicz (2)
  • grisanu (2)
  • modern-dev-dude (2)
  • trivikr (2)
  • Boxuan996 (2)
  • ZahidMirza95 (2)
  • khangly (1)
  • Dolvic (1)
Top Labels
Issue Labels
enhancement (11) question (9) bug (8) duplicate (2) good first issue (2) needs-investigation (2) dependencies (1) in progress (1)
Pull Request Labels
dependencies (35) bug (5) enhancement (5) documentation (2) chore (2) javascript (1)

Packages

  • Total packages: 1
  • Total downloads:
    • npm 613,559 last-month
  • Total dependent packages: 16
  • Total dependent repositories: 134
  • Total versions: 29
  • Total maintainers: 2
npmjs.org: aws-embedded-metrics

AWS Embedded Metrics Client Library

  • Versions: 29
  • Dependent Packages: 16
  • Dependent Repositories: 134
  • Downloads: 613,559 Last month
Rankings
Downloads: 0.5%
Dependent repos count: 1.3%
Dependent packages count: 1.7%
Average: 2.3%
Stargazers count: 3.8%
Forks count: 4.3%
Maintainers (2)
Last synced: 12 months ago

Dependencies

examples/agent/package-lock.json npm
  • aws-embedded-metrics 0.1.0-beta.1572886364
examples/agent/package.json npm
  • aws-embedded-metrics 0.1.0-beta.1572886364
examples/ecs-firelens/package-lock.json npm
  • accepts 1.3.7
  • any-promise 1.3.0
  • aws-embedded-metrics 1.1.0-rc1
  • cache-content-type 1.0.1
  • co 4.6.0
  • content-disposition 0.5.3
  • content-type 1.0.4
  • cookies 0.8.0
  • debug 3.1.0
  • deep-equal 1.0.1
  • delegates 1.0.0
  • depd 2.0.0
  • depd 1.1.2
  • destroy 1.0.4
  • ee-first 1.1.1
  • encodeurl 1.0.2
  • error-inject 1.0.0
  • escape-html 1.0.3
  • fresh 0.5.2
  • http-assert 1.4.1
  • http-errors 1.7.3
  • inherits 2.0.4
  • is-generator-function 1.0.7
  • keygrip 1.1.0
  • koa 2.11.0
  • koa-compose 4.1.0
  • koa-compose 3.2.1
  • koa-convert 1.2.0
  • media-typer 0.3.0
  • mime-db 1.43.0
  • mime-types 2.1.26
  • ms 2.0.0
  • negotiator 0.6.2
  • on-finished 2.3.0
  • only 0.0.2
  • parseurl 1.3.3
  • safe-buffer 5.1.2
  • setprototypeof 1.1.1
  • statuses 1.5.0
  • toidentifier 1.0.0
  • tsscmp 1.0.6
  • type-is 1.6.18
  • vary 1.1.2
  • ylru 1.2.1
examples/ecs-firelens/package.json npm
  • aws-embedded-metrics ^1.1.0-rc1
  • koa ^2.11.0
examples/eks/package-lock.json npm
  • accepts 1.3.7
  • any-promise 1.3.0
  • aws-embedded-metrics 1.1.1
  • cache-content-type 1.0.1
  • co 4.6.0
  • content-disposition 0.5.3
  • content-type 1.0.4
  • cookies 0.8.0
  • debug 3.1.0
  • deep-equal 1.0.1
  • delegates 1.0.0
  • depd 2.0.0
  • depd 1.1.2
  • destroy 1.0.4
  • ee-first 1.1.1
  • encodeurl 1.0.2
  • escape-html 1.0.3
  • fresh 0.5.2
  • http-assert 1.4.1
  • http-errors 1.7.3
  • inherits 2.0.4
  • is-generator-function 1.0.7
  • keygrip 1.1.0
  • koa 2.12.0
  • koa-compose 4.1.0
  • koa-compose 3.2.1
  • koa-convert 1.2.0
  • media-typer 0.3.0
  • mime-db 1.44.0
  • mime-types 2.1.27
  • ms 2.0.0
  • negotiator 0.6.2
  • on-finished 2.3.0
  • only 0.0.2
  • parseurl 1.3.3
  • safe-buffer 5.1.2
  • setprototypeof 1.1.1
  • statuses 1.5.0
  • toidentifier 1.0.0
  • tsscmp 1.0.6
  • type-is 1.6.18
  • vary 1.1.2
  • ylru 1.2.1
examples/eks/package.json npm
  • aws-embedded-metrics ^1.1.1
  • koa ^2.11.0
examples/lambda/src/package.json npm
  • aws-embedded-metrics 1.0.0
examples/testing/package-lock.json npm
  • 477 dependencies
examples/testing/package.json npm
  • jest ^25.1.0 development
  • node-notifier >=8.0.1 development
  • aws-embedded-metrics ^1.1.0-rc1
package-lock.json npm
  • 653 dependencies
package.json npm
  • @types/faker ^4.1.5 development
  • @types/jest ^26.0.22 development
  • @types/node ^12.0.8 development
  • @typescript-eslint/eslint-plugin ^2.23.0 development
  • @typescript-eslint/parser ^2.23.0 development
  • aws-sdk ^2.551.0 development
  • eslint ^6.8.0 development
  • eslint-config-prettier ^6.10.0 development
  • eslint-plugin-prettier ^3.1.2 development
  • faker ^4.1.0 development
  • jest ^26.6.3 development
  • node-notifier >=8.0.1 development
  • npm-pack-zip ^1.2.7 development
  • prettier ^1.19.1 development
  • ts-jest ^26.5.4 development
  • typescript ^3.8.0 development
  • y18n >=4.0.1 development
  • @datastructures-js/heap ^4.0.2
.github/workflows/codeql-analysis.yml actions
  • actions/checkout v2 composite
  • github/codeql-action/analyze v1 composite
  • github/codeql-action/autobuild v1 composite
  • github/codeql-action/init v1 composite
examples/ecs-firelens/Dockerfile docker
  • node 10.16.0-alpine build
examples/eks/Dockerfile docker
  • node 10.16.0-alpine build
test/canary/agent/Dockerfile docker
  • node 16.17.0-alpine build
test/integ/agent/Dockerfile docker
  • public.ecr.aws/lts/ubuntu 20.04 build
examples/lambda/src/package-lock.json npm
  • @datastructures-js/heap 4.1.0
  • aws-embedded-metrics 3.0.0
test/canary/agent/package.json npm