Skip to content

Commit

Permalink
High Resolution Metrics Support (#129)
Browse files Browse the repository at this point in the history
  • Loading branch information
meshwa19 authored Jan 23, 2023
1 parent a8a9765 commit c404b63
Show file tree
Hide file tree
Showing 17 changed files with 376 additions and 20 deletions.
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ class Example {

try {
metrics.putDimensions(DimensionSet.of("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);
} catch (InvalidDimensionException | InvalidMetricException e) {
log.error(e);
}
Expand Down Expand Up @@ -87,10 +88,12 @@ environment.getSink().shutdown().orTimeout(10_000L, TimeUnit.MILLISECONDS);

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

- MetricsLogger **putMetric**(String key, double value, Unit unit, StorageResolution storageResolution)
- MetricsLogger **putMetric**(String key, double value, StorageResolution storageResolution)
- MetricsLogger **putMetric**(String key, double value, Unit unit)
- MetricsLogger **putMetric**(String key, double value)

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.
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 and different storage resolutions. The Embedded Metric Format supports a maximum of 100 values per key.

Requirements:

Expand All @@ -99,10 +102,18 @@ Requirements:
- 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 `InvalidMetricException` 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:

```java
// 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);
```

- MetricsLogger **putProperty**(String key, Object value )
Expand Down
3 changes: 2 additions & 1 deletion canarytests/agent/src/main/java/emf/canary/ECSRunnable.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import software.amazon.cloudwatchlogs.emf.exception.InvalidNamespaceException;
import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger;
import software.amazon.cloudwatchlogs.emf.model.DimensionSet;
import software.amazon.cloudwatchlogs.emf.model.StorageResolution;
import software.amazon.cloudwatchlogs.emf.model.Unit;

import java.lang.management.ManagementFactory;
Expand Down Expand Up @@ -46,7 +47,7 @@ public void run() {
try {
logger.putMetric("Invoke", 1, Unit.COUNT);
logger.putMetric("Memory.HeapTotal", heapTotal, Unit.COUNT);
logger.putMetric("Memory.HeapUsed", heapUsed, Unit.COUNT);
logger.putMetric("Memory.HeapUsed", heapUsed, Unit.COUNT, StorageResolution.HIGH);
logger.putMetric("Memory.JVMUsedTotal", heapUsed + nonHeapUsed, Unit.COUNT);
} catch (InvalidMetricException e) {
System.out.println(e);
Expand Down
2 changes: 2 additions & 0 deletions examples/agent/src/main/java/agent/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger;
import software.amazon.cloudwatchlogs.emf.model.DimensionSet;
import software.amazon.cloudwatchlogs.emf.model.Unit;
import software.amazon.cloudwatchlogs.emf.model.StorageResolution;

import java.util.concurrent.TimeUnit;

Expand All @@ -35,6 +36,7 @@ private static void emitMetric(Environment environment)
MetricsLogger logger = new MetricsLogger(environment);
logger.setDimensions(DimensionSet.of("Operation", "Agent"));
logger.putMetric("ExampleMetric", 100, Unit.MILLISECONDS);
logger.putMetric("ExampleHighResolutionMetric", 10, Unit.MILLISECONDS, StorageResolution.HIGH);
logger.putProperty("RequestId", "422b1569-16f6-4a03-b8f0-fe3fd9b100f8");
logger.flush();
}
Expand Down
2 changes: 2 additions & 0 deletions examples/ecs-firelens/src/main/java/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import software.amazon.cloudwatchlogs.emf.environment.EnvironmentProvider;
import software.amazon.cloudwatchlogs.emf.exception.InvalidMetricException;
import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger;
import software.amazon.cloudwatchlogs.emf.model.StorageResolution;
import software.amazon.cloudwatchlogs.emf.model.Unit;
import sun.misc.Signal;
import java.io.IOException;
Expand All @@ -39,6 +40,7 @@ public static void main(String[] args) throws Exception {
MetricsLogger logger = new MetricsLogger();
logger.setNamespace("FargateEMF");
logger.putMetric("Latency", 63, Unit.MILLISECONDS);
logger.putMetric("CPU Utilization", 87, Unit.PERCENT, StorageResolution.HIGH);
logger.flush();
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
int portNumber = 8000;
Expand Down
2 changes: 2 additions & 0 deletions examples/lambda/src/main/java/Handler.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import software.amazon.cloudwatchlogs.emf.exception.InvalidMetricException;
import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger;
import software.amazon.cloudwatchlogs.emf.model.DimensionSet;
import software.amazon.cloudwatchlogs.emf.model.StorageResolution;
import software.amazon.cloudwatchlogs.emf.model.Unit;

import java.util.HashMap;
Expand All @@ -20,6 +21,7 @@ public String handleRequest(Map<String, String> event, Context context) {
try {
logger.putDimensions(DimensionSet.of("Service", "Aggregator"));
logger.putMetric("ProcessingLatency", 100, Unit.MILLISECONDS);
logger.putMetric("CPU Utilization", 87, Unit.PERCENT, StorageResolution.HIGH);
} catch (InvalidDimensionException | InvalidMetricException | DimensionSetExceededException e) {
System.out.println(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import software.amazon.cloudwatchlogs.emf.exception.InvalidTimestampException;
import software.amazon.cloudwatchlogs.emf.model.DimensionSet;
import software.amazon.cloudwatchlogs.emf.model.MetricsContext;
import software.amazon.cloudwatchlogs.emf.model.StorageResolution;
import software.amazon.cloudwatchlogs.emf.model.Unit;
import software.amazon.cloudwatchlogs.emf.sinks.ISink;

Expand Down Expand Up @@ -98,7 +99,7 @@ public void flush() {
}

/**
* Set a property on the published metrics. This is stored in the emitted log data and you are
* Set a property on the published metrics. This is stored in the emitted log data, and you are
* not charged for this data by CloudWatch Metrics. These values can be values that are useful
* for searching on, but have too high cardinality to emit as dimensions to CloudWatch Metrics.
*
Expand Down Expand Up @@ -189,20 +190,62 @@ public MetricsLogger resetDimensions(boolean useDefault) {
* @param key is the name of the metric
* @param value is the value of the metric
* @param unit is the unit of the metric value
* @param storageResolution is the resolution of the metric
* @see <a
* href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html#high-resolution-metrics">CloudWatch
* High Resolution Metrics</a>
* @return the current logger
* @throws InvalidMetricException if the metric is invalid
*/
public MetricsLogger putMetric(String key, double value, Unit unit)
public MetricsLogger putMetric(
String key, double value, Unit unit, StorageResolution storageResolution)
throws InvalidMetricException {
rwl.readLock().lock();
try {
this.context.putMetric(key, value, unit);
this.context.putMetric(key, value, unit, storageResolution);
return this;
} finally {
rwl.readLock().unlock();
}
}

/**
* Put a metric value. This value will be emitted to CloudWatch Metrics asynchronously and does
* not contribute to your account TPS limits. The value will also be available in your
* CloudWatch Logs
*
* @param key is the name of the metric
* @param value is the value of the metric
* @param storageResolution is the resolution of the metric
* @see <a
* href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html#high-resolution-metrics">CloudWatch
* High Resolution Metrics</a>
* @return the current logger
* @throws InvalidMetricException if the metric is invalid
*/
public MetricsLogger putMetric(String key, double value, StorageResolution storageResolution)
throws InvalidMetricException {
this.putMetric(key, value, Unit.NONE, storageResolution);
return this;
}

/**
* Put a metric value. This value will be emitted to CloudWatch Metrics asynchronously and does
* not contribute to your account TPS limits. The value will also be available in your
* CloudWatch Logs
*
* @param key is the name of the metric
* @param value is the value of the metric
* @param unit is the unit of the metric value
* @return the current logger
* @throws InvalidMetricException if the metric is invalid
*/
public MetricsLogger putMetric(String key, double value, Unit unit)
throws InvalidMetricException {
this.putMetric(key, value, unit, StorageResolution.STANDARD);
return this;
}

/**
* Put a metric value. This value will be emitted to CloudWatch Metrics asynchronously and does
* not contribute to your account TPS limits. The value will also be available in your
Expand All @@ -214,7 +257,7 @@ public MetricsLogger putMetric(String key, double value, Unit unit)
* @throws InvalidMetricException if the metric is invalid
*/
public MetricsLogger putMetric(String key, double value) throws InvalidMetricException {
this.putMetric(key, value, Unit.NONE);
this.putMetric(key, value, Unit.NONE, StorageResolution.STANDARD);
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package software.amazon.cloudwatchlogs.emf.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
Expand All @@ -26,6 +27,9 @@
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import software.amazon.cloudwatchlogs.emf.serializers.StorageResolutionFilter;
import software.amazon.cloudwatchlogs.emf.serializers.StorageResolutionSerializer;
import software.amazon.cloudwatchlogs.emf.serializers.UnitDeserializer;
import software.amazon.cloudwatchlogs.emf.serializers.UnitSerializer;

Expand All @@ -43,18 +47,36 @@ class MetricDefinition {
@JsonDeserialize(using = UnitDeserializer.class)
private Unit unit;

@Getter
@Setter
@JsonProperty("StorageResolution")
@JsonInclude(
value = JsonInclude.Include.CUSTOM,
valueFilter =
StorageResolutionFilter.class) // Do not serialize when valueFilter is true
@JsonSerialize(using = StorageResolutionSerializer.class)
public StorageResolution storageResolution;

@JsonIgnore @NonNull @Getter private List<Double> values;

MetricDefinition(String name) {
this(name, Unit.NONE, new ArrayList<>());
this(name, Unit.NONE, StorageResolution.STANDARD, new ArrayList<>());
}

MetricDefinition(String name, double value) {
this(name, Unit.NONE, value);
this(name, Unit.NONE, StorageResolution.STANDARD, value);
}

MetricDefinition(String name, Unit unit, double value) {
this(name, unit, new ArrayList<>(Arrays.asList(value)));
this(name, unit, StorageResolution.STANDARD, new ArrayList<>(Arrays.asList(value)));
}

MetricDefinition(String name, StorageResolution storageResolution, double value) {
this(name, Unit.NONE, storageResolution, new ArrayList<>(Arrays.asList(value)));
}

MetricDefinition(String name, Unit unit, StorageResolution storageResolution, double value) {
this(name, unit, storageResolution, new ArrayList<>(Arrays.asList(value)));
}

void addValue(double value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,26 @@ void putDimensionSet(DimensionSet dimensionSet) {
dimensions.add(dimensionSet);
}

// Helper method for testing putMetric()
void putMetric(String key, double value) {
putMetric(key, value, Unit.NONE);
putMetric(key, value, Unit.NONE, StorageResolution.STANDARD);
}

// Helper method for testing putMetric()
void putMetric(String key, double value, Unit unit) {
putMetric(key, value, unit, StorageResolution.STANDARD);
}

// Helper method for testing serialization
void putMetric(String key, double value, StorageResolution storageResolution) {
putMetric(key, value, Unit.NONE, storageResolution);
}

void putMetric(String key, double value, Unit unit, StorageResolution storageResolution) {
metrics.compute(
key,
(k, v) -> {
if (v == null) return new MetricDefinition(key, unit, value);
if (v == null) return new MetricDefinition(key, unit, storageResolution, value);
else {
v.addValue(value);
return v;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public class MetricsContext {
@Getter private final RootNode rootNode;

private MetricDirective metricDirective;
private final Map<String, StorageResolution> metricNameAndResolutionMap = new HashMap<>();

public MetricsContext() {
this(new RootNode());
Expand Down Expand Up @@ -108,6 +109,44 @@ public boolean hasDefaultDimensions() {
* an array of scalar values.
*
* <pre>{@code
* metricContext.putMetric("Latency", 100, Unit.MILLISECONDS, StorageResolution.HIGH)
* }</pre>
*
* @param key Name of the metric
* @param value Value of the metric
* @param unit The unit of the metric
* @param storageResolution The resolution of the metric
* @throws InvalidMetricException if the metric is invalid
*/
public void putMetric(String key, double value, Unit unit, StorageResolution storageResolution)
throws InvalidMetricException {
Validator.validateMetric(key, value, unit, storageResolution, metricNameAndResolutionMap);
metricDirective.putMetric(key, value, unit, storageResolution);
metricNameAndResolutionMap.put(key, storageResolution);
}
/**
* Add a metric measurement to the context with a storage resolution but without a unit.
* Multiple calls using the same key will be stored as an array of scalar values.
*
* <pre>{@code
* metricContext.putMetric("Latency", 100, StorageResolution.HIGH)
* }</pre>
*
* @param key Name of the metric
* @param value Value of the metric
* @param storageResolution The resolution of the metric
* @throws InvalidMetricException if the metric is invalid
*/
public void putMetric(String key, double value, StorageResolution storageResolution)
throws InvalidMetricException {
putMetric(key, value, Unit.NONE, storageResolution);
}

/**
* Add a metric measurement to the context without a storage resolution. Multiple calls using
* the same key will be stored as an array of scalar values.
*
* <pre>{@code
* metricContext.putMetric("Latency", 100, Unit.MILLISECONDS)
* }</pre>
*
Expand All @@ -117,8 +156,7 @@ public boolean hasDefaultDimensions() {
* @throws InvalidMetricException if the metric is invalid
*/
public void putMetric(String key, double value, Unit unit) throws InvalidMetricException {
Validator.validateMetric(key, value, unit);
metricDirective.putMetric(key, value, unit);
putMetric(key, value, unit, StorageResolution.STANDARD);
}

/**
Expand All @@ -134,7 +172,7 @@ public void putMetric(String key, double value, Unit unit) throws InvalidMetricE
* @throws InvalidMetricException if the metric is invalid
*/
public void putMetric(String key, double value) throws InvalidMetricException {
putMetric(key, value, Unit.NONE);
putMetric(key, value, Unit.NONE, StorageResolution.STANDARD);
}

/**
Expand Down Expand Up @@ -297,12 +335,14 @@ public List<String> serialize() throws JsonProcessingException {
new MetricDefinition(
metric.getName(),
metric.getUnit(),
metric.getStorageResolution(),
metric.getValues()
.subList(0, Constants.MAX_DATAPOINTS_PER_METRIC)));
metricDefinitions.offer(
new MetricDefinition(
metric.getName(),
metric.getUnit(),
metric.getStorageResolution(),
metric.getValues()
.subList(
Constants.MAX_DATAPOINTS_PER_METRIC,
Expand Down
Loading

0 comments on commit c404b63

Please sign in to comment.