Skip to content

Support setting timestamp #79

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

Merged
merged 4 commits into from
May 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,16 @@ Examples:
setNamespace("MyApplication")
```

- MetricsLogger **setTimestamp**(Instant timestamp)

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

Examples:

```java
setTimestamp(Instant.now())
```

- **flush**()

Flushes the current MetricsContext to the configured sink and resets all properties, dimensions and metric values. The namespace and default dimensions will be preserved across flushes.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package software.amazon.cloudwatchlogs.emf.logger;

import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import lombok.extern.slf4j.Slf4j;
import software.amazon.cloudwatchlogs.emf.environment.Environment;
Expand Down Expand Up @@ -165,6 +166,17 @@ public MetricsLogger setNamespace(String namespace) {
return this;
}

/**
* Set the timestamp to be used for metrics.
*
* @param timestamp value of timestamp to be set
* @return the current logger
*/
public MetricsLogger setTimestamp(Instant timestamp) {
this.context.setTimestamp(timestamp);
return this;
}

private void configureContextForEnvironment(MetricsContext context, Environment environment) {
if (context.hasDefaultDimensions()) {
return;
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.core.JsonProcessingException;
import java.time.Instant;
import java.util.*;
import lombok.Getter;
import software.amazon.cloudwatchlogs.emf.Constants;
Expand Down Expand Up @@ -195,6 +196,20 @@ public void putMetadata(String key, Object value) {
rootNode.getAws().putCustomMetadata(key, value);
}

/** @return timestamp field from the metadata. */
public Instant getTimestamp() {
return rootNode.getAws().getTimestamp();
}

/**
* Update timestamp field in the metadata
*
* @param timestamp value of timestamp to be set
*/
public void setTimestamp(Instant timestamp) {
rootNode.getAws().setTimestamp(timestamp);
}

/** @return Creates an independently flushable context. */
public MetricsContext createCopyWithContext() {
return new MetricsContext(metricDirective.copyWithoutMetrics());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;

import java.time.Instant;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.junit.Assert;
Expand Down Expand Up @@ -118,6 +119,21 @@ public void testSetNamespace() {
Assert.assertEquals(sink.getContext().getNamespace(), namespace);
}

@Test
public void testFlushWithDefaultTimestamp() {
logger.flush();
Assert.assertNotNull(sink.getContext().getTimestamp());
}

@Test
public void testSetTimestamp() {
Instant now = Instant.now();
logger.setTimestamp(now);
logger.flush();

Assert.assertEquals(sink.getContext().getTimestamp(), now);
}

@Test
public void testFlushWithConfiguredServiceName() {
String serviceName = "TestServiceName";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.json.JsonMapper;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Expand Down Expand Up @@ -140,19 +141,37 @@ public void testSerializeZeroMetric() throws JsonProcessingException {
int expectedEventCount = 1;
assertEquals(expectedEventCount, events.size());

JsonMapper objectMapper = new JsonMapper();
Map<String, Object> metadata_map =
objectMapper.readValue(events.get(0), new TypeReference<Map<String, Object>>() {});
Map<String, Object> rootNode = parseRootNode(events.get(0));
// If there's no metric added, the _aws would be filtered out from the log event
assertFalse(metadata_map.containsKey("_aws"));
assertFalse(rootNode.containsKey("_aws"));
}

@Test
@SuppressWarnings("unchecked")
public void testSetTimestamp() throws JsonProcessingException {
MetricsContext mc = new MetricsContext();
mc.putMetric("Metric", 0);

Instant now = Instant.now();
mc.setTimestamp(now);

List<String> events = mc.serialize();

int expectedEventCount = 1;
assertEquals(expectedEventCount, events.size());
Map<String, Object> rootNode = parseRootNode(events.get(0));

assertTrue(rootNode.containsKey("_aws"));
Map<String, Object> metadata = (Map<String, Object>) rootNode.get("_aws");

assertTrue(metadata.containsKey("Timestamp"));
assertEquals(metadata.get("Timestamp"), now.toEpochMilli());
}

@SuppressWarnings("unchecked")
private ArrayList<MetricDefinition> parseMetrics(String event) throws JsonProcessingException {
JsonMapper objectMapper = new JsonMapper();
Map<String, Object> metadata_map =
objectMapper.readValue(event, new TypeReference<Map<String, Object>>() {});
Map<String, Object> metadata = (Map<String, Object>) metadata_map.get("_aws");
Map<String, Object> rootNode = parseRootNode(event);
Map<String, Object> metadata = (Map<String, Object>) rootNode.get("_aws");
ArrayList<Map<String, Object>> metricDirectives =
(ArrayList<Map<String, Object>>) metadata.get("CloudWatchMetrics");
ArrayList<Map<String, String>> metrics =
Expand All @@ -162,7 +181,7 @@ private ArrayList<MetricDefinition> parseMetrics(String event) throws JsonProces
for (Map<String, String> metric : metrics) {
String name = metric.get("Name");
Unit unit = Unit.fromValue(metric.get("Unit"));
Object value = metadata_map.get(name);
Object value = rootNode.get(name);
if (value instanceof ArrayList) {
metricDefinitions.add(new MetricDefinition(name, unit, (ArrayList) value));
} else {
Expand All @@ -171,4 +190,8 @@ private ArrayList<MetricDefinition> parseMetrics(String event) throws JsonProces
}
return metricDefinitions;
}

private Map<String, Object> parseRootNode(String event) throws JsonProcessingException {
return new JsonMapper().readValue(event, new TypeReference<Map<String, Object>>() {});
}
}