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

Amazon CloudWatch Embedded Metric Format Client Library

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

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
  • Academic email domains
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (11.4%) to scientific vocabulary
Last synced: 9 months ago · JSON representation

Repository

Amazon CloudWatch Embedded Metric Format Client Library

Basic Info
  • Host: GitHub
  • Owner: awslabs
  • License: apache-2.0
  • Language: C#
  • Default Branch: main
  • Homepage:
  • Size: 1.77 MB
Statistics
  • Stars: 24
  • Watchers: 6
  • Forks: 17
  • Open Issues: 14
  • Releases: 4
Created over 5 years ago · Last pushed over 1 year ago
Metadata Files
Readme Contributing License Code of conduct

README.md

aws-embedded-metrics-dotnet

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

  • Using the CLI:

sh dotnet add package Amazon.CloudWatch.EMF

Usage

To get a metric logger, you can instantiate it like so. MetricsLogger implements IDisposable. When the logger is disposed, it will write the metrics to the configured sink.

```c# using (var logger = new MetricsLogger()) { logger.SetNamespace("Canary"); var dimensionSet = new DimensionSet(); dimensionSet.AddDimension("Service", "aggregator"); logger.SetDimensions(dimensionSet); logger.PutMetric("ProcessingLatency", 100, Unit.MILLISECONDS,StorageResolution.STANDARD); logger.PutMetric("Memory.HeapUsed", "1600424.0", Unit.BYTES, StorageResolution.HIGH); logger.PutProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8");

} ```

Graceful Shutdown

In any environment, other than AWS Lambda, we recommend running an out-of-process agent (the CloudWatch Agent or FireLens / Fluent-Bit) to collect the EMF events. When using an out-of-process agent, this package will buffer the data asynchronously in process to handle any transient communication issues with the agent. This means that when the MetricsLogger gets flushed, data may not be safely persisted yet. To gracefully shutdown the environment, you can call shutdown on the environment's sink. This is an async call that should be awaited. A full example can be found in the examples directory.

```c# var configuration = new Configuration { ServiceName = "DemoApp", ServiceType = "ConsoleApp", LogGroupName = "DemoApp", EnvironmentOverride = Environments.EC2 };

var environment = new DefaultEnvironment(configuration);

using (var logger = new MetricsLogger()) { logger.SetNamespace("Canary"); var dimensionSet = new DimensionSet(); dimensionSet.AddDimension("Service", "aggregator"); logger.SetDimensions(dimensionSet); logger.PutMetric("ProcessingLatency", 100, Unit.MILLISECONDS); logger.PutMetric("Memory.HeapUsed", "1600424.0", Unit.BYTES, StorageResolution.HIGH); logger.PutProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8"); }

await environment.Sink.Shutdown(); ```

ASP.Net Core

We offer a helper package for ASP.Net Core applications that can be used to simplify the onboarding process and provide default metrics.

See the example in examples/Amazon.CloudWatch.EMF.Examples.Web to create a logger that is hooked into the dependency injection framework and provides default metrics for each request. By adding some code to your Startup.cs file, you can get default metrics like the following. And of course, you can also emit additional custom metrics from your Controllers.

  1. Add the configuration to your Startup file.

cs public void ConfigureServices(IServiceCollection services) { // Add the necessary services. After this is done, you will have the // IMetricsLogger available for dependency injection in your // controllers services.AddEmf(); }

  1. Add middleware to add default metrics and metadata to each request.

cs public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Add middleware which will set metric dimensions based on the request routing app.UseEmfMiddleware(); }

Example

sh ▶ cd examples/Amazon.CloudWatch.EMF.Web ▶ export AWS_EMF_ENVIRONMENT=Local ▶ dotnet run

sh ▶ curl http://localhost:5000

json {"TraceId":"0HM6EKOBA2CPJ:00000001","Path":"/","StatusCode":"404"}

sh ▶ curl http://localhost:5000/weatherForecast

json { "_aws": { "Timestamp": 1617649416374, "CloudWatchMetrics": [ { "Namespace": "WeatherApp", "Metrics": [ { "Name": "Temperature", "Unit": "None" }, { "Name": "Time", "Unit": "Milliseconds" } ], "Dimensions": [ [ "Controller", "Action" ], [ "Controller", "Action", "StatusCode" ] ] } ] }, "TraceId": "|f6eec800-4652f86aef0c7219.", "Path": "/WeatherForecast", "Controller": "WeatherForecast", "Action": "Get", "StatusCode": "200", "Temperature": -10, "Time": 189 }

API

MetricsLogger

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

  • MetricsLogger PutMetric(string key, double value)
  • MetricsLogger PutMetric(string key, double value, Unit unit)
  • MetricsLogger PutMetric(string key, double value, StorageResolution storageResolution)
  • MetricsLogger PutMetric(string key, 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 the same key but different storage resolutions. Same metric cannot have different storage resolutions otherwise a InvalidMetricException will be thrown. The Embedded Metric Format supports a maxumum of 100 metrics per key.

Metrics must meet CloudWatch Metrics requirements, otherwise a InvalidMetricException 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

Example:

```c# // Standard Resolution Example logger.PutMetric("ProcessingLatency", 101, Unit.MILLISECONDS);

// High Resolution Example logger.PutMetric("Memory.HeapUsed", "1600424.0", Unit.BYTES, StorageResolution.HIGH); ```

  • MetricsLogger PutProperty(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.

Example: ```c# logger.PutProperty("AccountId", "123456789"); logger.PutProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8");

Dictionary payLoad = new Dictionary { { "sampleTime", 123456789 }, { "temperature", 273.0 }, { "pressure", 101.3 } }; logger.PutProperty("Payload", payLoad); ```

  • MetricsLogger PutDimensions(DimensionSet dimensions)

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

WARNING: Each dimension set will result in a new CloudWatch metric (even dimension sets with the same values). If the cardinality of a particular value is expected to be high, you should consider using setProperty instead.

Dimensions must meet CloudWatch Dimensions requirements, otherwise a InvalidDimensionException will be thrown. See Dimensions for valid values.

Example:

c# DimensionSet dimensionSet = new DimensionSet(); dimensionSet.AddDimension("Service", "Aggregator"); dimensionSet.AddDimension("Region", "us-west-2"); logger.PutDimensions(dimensionSet);

  • MetricsLogger SetDimensions(params DimensionSet[] dimensionSets)
  • MetricsLogger SetDimensions(bool useDefault, params DimensionSet[] dimensionSets)

Explicitly override all dimensions. This will remove the default dimensions unless useDefault is set to true.

WARNING:Each dimension set will result in a new CloudWatch metric (even dimension sets with the same values). If the cardinality of a particular value is expected to be high, you should consider using setProperty instead.

Dimensions must meet CloudWatch Dimensions requirements, otherwise a InvalidDimensionException will be thrown. See Dimensions for valid values.

Examples:

c# DimensionSet dimensionSet = new DimensionSet(); dimensionSet.AddDimension("Service", "Aggregator"); dimensionSet.AddDimension("Region", "us-west-2"); logger.SetDimensions(true, dimensionSet); // Will preserve default dimensions

c# DimensionSet dimensionSet = new DimensionSet(); dimensionSet.AddDimension("Service", "Aggregator"); dimensionSet.AddDimension("Region", "us-west-2"); logger.SetDimensions(dimensionSet); // Will remove default dimensions

  • MetricsLogger ResetDimensions(bool useDefault)

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

  • MetricsLogger SetNamespace(string logNamespace)

Sets the CloudWatch namespace that extracted metrics should be published to. If not set, a default value of aws-embedded-metrics will be used. Namespaces must meet CloudWatch Namespace requirements, otherwise a InvalidNamespaceException will be thrown. See Namespace for valid values.

Example:

c# logger.SetNamespace("MyApplication")

  • MetricsLogger SetTimestamp(DateTime dateTime)

Sets the timestamp of the metrics. If not set, the current time of the client will be used. Timestamp must meet CloudWatch requirements, otherwise a InvalidTimestampException will be thrown. See Timestamps for valid values.

Example: c# logger.SetTimestamp(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 preserved by default, but this behavior can be changed by setting FlushPreserveDimensions = false on the metrics logger.

Examples:

c# flush(); // default dimensions and custom dimensions will be preserved after each flush()

c# logger.FlushPreserveDimensions = false; flush(); // only default dimensions will be preserved after each flush()

c# logger.FlushPreserveDimensions = false; logger.ResetDimensions(false); // default dimensions are disabled; no dimensions will be preserved after each flush() logger.Flush();

Owner

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

AWS Labs

GitHub Events

Total
  • Watch event: 1
  • Push event: 2
  • Pull request review event: 4
  • Pull request event: 4
  • Fork event: 2
Last Year
  • Watch event: 1
  • Push event: 2
  • Pull request review event: 4
  • Pull request event: 4
  • Fork event: 2

Issues and Pull Requests

Last synced: 10 months ago

All Time
  • Total issues: 27
  • Total pull requests: 33
  • Average time to close issues: 4 months
  • Average time to close pull requests: 27 days
  • Total issue authors: 14
  • Total pull request authors: 12
  • Average comments per issue: 0.56
  • Average comments per pull request: 0.48
  • Merged pull requests: 26
  • Bot issues: 0
  • Bot pull requests: 3
Past Year
  • Issues: 0
  • Pull requests: 2
  • Average time to close issues: N/A
  • Average time to close pull requests: 2 days
  • Issue authors: 0
  • Pull request authors: 2
  • Average comments per issue: 0
  • Average comments per pull request: 0.0
  • Merged pull requests: 2
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • jaredcnance (7)
  • hakenmt (4)
  • markkuhn (3)
  • zhuliice (2)
  • Glen-Moonpig (2)
  • udlose (1)
  • phalvesr (1)
  • frozenberg (1)
  • chrischappell-rgare (1)
  • Stephen-Bao (1)
  • Caramel-Uzi (1)
  • gordonpn (1)
  • cliedeman (1)
  • Dave-EMIS (1)
  • SamuelCox (1)
Pull Request Authors
  • meshwa19 (6)
  • markkuhn (6)
  • jaredcnance (5)
  • Himtanaya (3)
  • gordonpn (3)
  • dependabot[bot] (3)
  • rayabagi (2)
  • ZahidMirza95 (1)
  • chrisoverzero (1)
  • David-Ferreira (1)
  • Glen-Moonpig (1)
  • phalvesr (1)
  • Boxuan996 (1)
Top Labels
Issue Labels
question (4) enhancement (4) bug (3) good first issue (2)
Pull Request Labels
enhancement (4) bug (4) dependencies (3) documentation (1) chore (1)

Packages

  • Total packages: 2
  • Total downloads:
    • nuget 1,228,330 total
  • Total dependent packages: 2
    (may contain duplicates)
  • Total dependent repositories: 0
    (may contain duplicates)
  • Total versions: 16
  • Total maintainers: 1
nuget.org: amazon.cloudwatch.emf.web

Amazon CloudWatch Embedded Metric Format Client Library for ASP.Net Core Applications

  • License: Apache-2.0
  • Latest release: 1.0.0
    published almost 4 years ago
  • Versions: 2
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 81,291 Total
Rankings
Downloads: 10.1%
Dependent repos count: 10.2%
Average: 11.4%
Dependent packages count: 13.9%
Maintainers (1)
Last synced: 10 months ago
nuget.org: amazon.cloudwatch.emf

Amazon CloudWatch Embedded Metric Format Client Library

  • License: Apache-2.0
  • Latest release: 2.2.0
    published over 2 years ago
  • Versions: 14
  • Dependent Packages: 2
  • Dependent Repositories: 0
  • Downloads: 1,147,039 Total
Rankings
Downloads: 2.1%
Average: 11.6%
Dependent repos count: 13.8%
Dependent packages count: 18.8%
Maintainers (1)
Last synced: 10 months ago

Dependencies

examples/Amazon.CloudWatch.EMF.Examples.ConsoleApp/Amazon.CloudWatch.EMF.Examples.ConsoleApp.csproj nuget
  • Microsoft.Extensions.Logging 5.0.0
  • Microsoft.Extensions.Logging.Console 5.0.0
examples/Amazon.CloudWatch.EMF.Examples.Lambda/Amazon.CloudWatch.EMF.Examples.Lambda.csproj nuget
  • Amazon.Lambda.Core 1.1.0
  • Amazon.Lambda.Serialization.SystemTextJson 2.0.0
src/Amazon.CloudWatch.EMF/Amazon.CloudWatch.EMF.csproj nuget
  • Microsoft.Extensions.Logging.Abstractions 3.1.8
  • Newtonsoft.Json 12.0.3
  • StyleCop.Analyzers 1.1.118
tests/Amazon.CloudWatch.EMF.Canary/Amazon.CloudWatch.EMF.Canary.csproj nuget
  • Microsoft.Extensions.Logging 5.0.0
  • Microsoft.Extensions.Logging.Console 5.0.0
tests/Amazon.CloudWatch.EMF.IntegrationTests/Amazon.CloudWatch.EMF.IntegrationTests.csproj nuget
  • AWSSDK.CloudWatch 3.5.0.22
  • Microsoft.NET.Test.Sdk 16.7.1
  • NFluent 2.7.0
  • coverlet.collector 1.3.0
  • xunit 2.4.1
  • xunit.runner.visualstudio 2.4.3
tests/Amazon.CloudWatch.EMF.Tests/Amazon.CloudWatch.EMF.Tests.csproj nuget
  • AutoFixture 4.14.0
  • AutoFixture.AutoNSubstitute 4.14.0
  • Microsoft.NET.Test.Sdk 16.7.1
  • coverlet.collector 1.3.0
  • xunit 2.4.1
  • xunit.runner.visualstudio 2.4.3
.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
scripts/cwagent/Dockerfile docker
  • debian latest build
tests/Amazon.CloudWatch.EMF.Canary/Dockerfile docker
  • mcr.microsoft.com/dotnet/aspnet 6.0 build
examples/Amazon.CloudWatch.EMF.Examples.Web/Amazon.CloudWatch.EMF.Examples.Web.csproj nuget
src/Amazon.CloudWatch.EMF.Web/Amazon.CloudWatch.EMF.Web.csproj nuget