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

Amazon CloudWatch Embedded Metric Format Client Library

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

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 (12.2%) to scientific vocabulary
Last synced: 11 months ago · JSON representation

Repository

Amazon CloudWatch Embedded Metric Format Client Library

Basic Info
Statistics
  • Stars: 217
  • Watchers: 9
  • Forks: 39
  • Open Issues: 31
  • Releases: 15
Created over 6 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

pip3 install aws-embedded-metrics

Usage

To get a metric logger, you can decorate your function with a metric_scope:

```py from awsembeddedmetrics import metricscope from awsembeddedmetrics.storageresolution import StorageResolution

@metricscope def myhandler(metrics): metrics.putdimensions({"Foo": "Bar"}) metrics.putmetric("ProcessingLatency", 100, "Milliseconds", StorageResolution.STANDARD) metrics.putmetric("Memory.HeapUsed", 1600424.0, "Bytes", StorageResolution.HIGH) metrics.setproperty("AccountId", "123456789012") metrics.setproperty("RequestId", "422b1569-16f6-4a03") metrics.setproperty("DeviceId", "61270781-c6ac-46f1")

return {"message": "Hello!"}

```

API

MetricsLogger

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

  • put_metric(key: str, value: float, unit: str = "None", storage_resolution: int = 60) -> MetricsLogger

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:

```py

Standard Resolution example

putmetric("Latency", 200, "Milliseconds") putmetric("Latency", 201, "Milliseconds", StorageResolution.STANDARD)

High Resolution example

put_metric("Memory.HeapUsed", 1600424.0, "Bytes", StorageResolution.HIGH) ```

  • set_property(key: str, value: Any) -> MetricsLogger

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:

py set_property("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8") set_property("InstanceId", "i-1234567890") set_property("Device", { "Id": "61270781-c6ac-46f1-baf7-22c808af8162", "Name": "Transducer", "Model": "PT-1234" })

  • put_dimensions(dimensions: Dict[str, str]) -> MetricsLogger

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:

py put_dimensions({ "Operation": "Aggregator" }) put_dimensions({ "Operation": "Aggregator", "DeviceType": "Actuator" })

  • set_dimensions(*dimensions: Dict[str, str], use_default: bool = False) -> MetricsLogger

Explicitly override all dimensions. By default, this will disable the default dimensions, but can be configured using the keyword-only parameter use_default.

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:

py set_dimensions( { "Operation": "Aggregator" }, { "Operation": "Aggregator", "DeviceType": "Actuator" } )

py set_dimensions( { "Operation": "Aggregator" }, use_default=True # default dimensions would be enabled )

  • reset_dimensions(use_default: bool) -> MetricsLogger

Explicitly clear all custom dimensions. The behavior of whether default dimensions should be used can be configured with the use_default parameter.

Examples:

py reset_dimensions(False) # this will clear all custom dimensions as well as disable default dimensions

  • set_namespace(value: str) -> MetricsLogger

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
  • Namespace must meet CloudWatch Namespace requirements, otherwise a InvalidNamespaceError will be thrown. See Namespaces for valid values.

Examples:

py set_namespace("MyApplication")

  • set_timestamp(timestamp: datetime) -> MetricsLogger

Sets the timestamp of the metrics. If not set, current time of the client will be used.

Timestamp must meet CloudWatch requirements, otherwise a InvalidTimestampError will be thrown. See Timestamps for valid values.

Examples:

py set_timestamp(datetime.datetime.now())

  • 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 not preserved by default, but this behavior can be changed by setting logger.flush_preserve_dimensions = True, so that custom dimensions would be preserved after each flushing thereafter.

Example:

py logger.flush() # only default dimensions will be preserved after each flush()

py logger.flush_preserve_dimensions = True logger.flush() # custom dimensions and default dimensions will be preserved after each flush()

py logger.reset_dimensions(False) logger.flush() # default dimensions are disabled; no dimensions will be preserved after each 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:

```py

in process

from awsembeddedmetrics.config import getconfig Config = getconfig() Config.service_name = "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:

```py

in process

from awsembeddedmetrics.config import getconfig Config = getconfig() Config.service_type = "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:

```py

in process

from awsembeddedmetrics.config import getconfig Config = getconfig() Config.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:

```py

in process

from awsembeddedmetrics.config import getconfig Config = getconfig() Config.logstreamname = "LogStreamName"

environment

AWSEMFLOGSTREAMNAME = LogStreamName ```

NameSpace: Overrides the CloudWatch namespace. If not set, a default value of aws-embedded-metrics will be used.

Requirements:

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

Example:

```py

in process

from awsembeddedmetrics.config import getconfig Config = getconfig() Config.namespace = "MyApplication"

environment

AWSEMFNAMESPACE = MyApplication ```

DISABLEMETRICEXTRACTION: Disables extraction of metrics by CloudWatch, by omitting EMF metadata from serialized log records.

Example:

```py

in process

from awsembeddedmetrics.config import getconfig Config = getconfig() Config.disablemetricextraction = True

environment

AWSEMFDISABLEMETRICEXTRACTION = true ```

Examples

Check out the examples directory to get started.

Development

  1. Install Test Dependencies

pip install tox

  1. Run tests

tox

  1. Integration tests. These tests require Docker to run the CloudWatch Agent and valid AWS credentials. Tests can be run by:

sh export AWS_ACCESS_KEY_ID= export AWS_SECRET_ACCESS_KEY= export AWS_REGION=us-west-2 ./bin/run-integ-tests.sh

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
  • Create event: 8
  • Issues event: 1
  • Release event: 3
  • Watch event: 8
  • Delete event: 1
  • Issue comment event: 30
  • Push event: 3
  • Pull request review comment event: 2
  • Pull request review event: 13
  • Pull request event: 15
  • Fork event: 4
Last Year
  • Create event: 8
  • Issues event: 1
  • Release event: 3
  • Watch event: 8
  • Delete event: 1
  • Issue comment event: 30
  • Push event: 3
  • Pull request review comment event: 2
  • Pull request review event: 13
  • Pull request event: 15
  • Fork event: 4

Committers

Last synced: about 2 years ago

All Time
  • Total Commits: 84
  • Total Committers: 22
  • Avg Commits per committer: 3.818
  • Development Distribution Score (DDS): 0.643
Past Year
  • Commits: 3
  • Committers: 3
  • Avg Commits per committer: 1.0
  • Development Distribution Score (DDS): 0.667
Top Committers
Name Email Commits
Jared Nance j****e@a****m 30
Jared Nance j****e@g****m 19
Mark Kuhn k****r@a****m 9
Himtanaya Bhadada h****a@g****m 4
Meshwa Savalia 3****9 2
Jenny 1****w 2
Xinyu Bao 7****o 2
Stefan Richter s****n@0****e 2
Amazon GitHub Automation 5****o 1
Amruth Rayabagi 1****i 1
Gordon Pham-Nguyen 4****n 1
Abdul Kader Maliyakkal a****l@g****m 1
Abdul Kader Maliyakkal a****l@g****m 1
Anton Grübel a****l@g****m 1
Ben Kehoe b****n@k****o 1
Ben Kehoe b****e@i****m 1
Daniel Roschka d****n@p****e 1
Mark Kuhn k****k@o****m 1
Pablo Aguiar s****s@g****m 1
Paul Ezvan p****l@e****r 1
Ramprasad G r****l@g****m 1
liquidpele r****b@g****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 11 months ago

All Time
  • Total issues: 55
  • Total pull requests: 75
  • Average time to close issues: 5 months
  • Average time to close pull requests: about 2 months
  • Total issue authors: 35
  • Total pull request authors: 25
  • Average comments per issue: 1.58
  • Average comments per pull request: 0.89
  • Merged pull requests: 53
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 1
  • Pull requests: 16
  • Average time to close issues: N/A
  • Average time to close pull requests: 3 days
  • Issue authors: 1
  • Pull request authors: 3
  • Average comments per issue: 0.0
  • Average comments per pull request: 0.06
  • Merged pull requests: 6
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • jaredcnance (8)
  • benkehoe (7)
  • Dunedan (7)
  • markkuhn (2)
  • stampcli (1)
  • MattWilliams89 (1)
  • jchangxu (1)
  • pbhasker (1)
  • tomaszdudek7 (1)
  • jhecking (1)
  • frediana (1)
  • Private-SO (1)
  • bobthemighty (1)
  • hakenmt (1)
  • ssoper-usgs (1)
Pull Request Authors
  • jaredcnance (20)
  • seoberha (11)
  • markkuhn (7)
  • Himtanaya (5)
  • gordonpn (3)
  • 02strich (3)
  • benkehoe (2)
  • meshwa19 (2)
  • ZahidMirza95 (2)
  • acradu (2)
  • ridha (2)
  • Stephen-Bao (2)
  • Boxuan996 (2)
  • ghost (1)
  • paulez (1)
Top Labels
Issue Labels
enhancement (25) bug (6) good first issue (6) question (4) documentation (3) in progress (3) chore (2)
Pull Request Labels
enhancement (4) chore (4) bug (2) documentation (1)

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 673,564 last-month
  • Total docker downloads: 233
  • Total dependent packages: 8
  • Total dependent repositories: 24
  • Total versions: 19
  • Total maintainers: 3
pypi.org: aws-embedded-metrics

AWS Embedded Metrics Package

  • Versions: 19
  • Dependent Packages: 8
  • Dependent Repositories: 24
  • Downloads: 673,564 Last month
  • Docker Downloads: 233
Rankings
Downloads: 0.7%
Dependent packages count: 1.4%
Dependent repos count: 3.0%
Average: 3.6%
Docker downloads count: 4.3%
Stargazers count: 5.2%
Forks count: 6.7%
Last synced: 11 months ago

Dependencies

setup.py pypi
  • aiohttp *
examples/ec2/metadata-endpoint/Dockerfile docker
  • node latest build
tests/canary/agent/Dockerfile docker
  • python 3.7 build
tests/integ/agent/Dockerfile docker
  • debian latest build