Skip to content

Commit 8a040ac

Browse files
authored
fix(metrics): Do not flush when no metrics were added to avoid printing root-level _aws dict (#1891)
* fix(metrics): Do not flush when no metrics were added to avoid printing root-level _aws dict. * Fix pmd linting failures.
1 parent cc1b3b1 commit 8a040ac

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

powertools-metrics/src/main/java/software/amazon/lambda/powertools/metrics/internal/EmfMetricsLogger.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,8 +164,9 @@ public void flush() {
164164
} else {
165165
LOGGER.warn("No metrics were emitted");
166166
}
167+
} else {
168+
emfLogger.flush();
167169
}
168-
emfLogger.flush();
169170
}
170171

171172
@Override

powertools-metrics/src/test/java/software/amazon/lambda/powertools/metrics/internal/EmfMetricsLoggerTest.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class EmfMetricsLoggerTest {
5151

5252
private Metrics metrics;
5353
private final ObjectMapper objectMapper = new ObjectMapper();
54-
private final PrintStream standardOut = System.out;
54+
private static final PrintStream standardOut = System.out;
5555
private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
5656

5757
@BeforeEach
@@ -180,7 +180,7 @@ void shouldAddDimension() throws Exception {
180180
JsonNode dimensions = rootNode.get("_aws").get("CloudWatchMetrics").get(0).get("Dimensions").get(0);
181181
boolean hasDimension = false;
182182
for (JsonNode dimension : dimensions) {
183-
if (dimension.asText().equals("CustomDimension")) {
183+
if ("CustomDimension".equals(dimension.asText())) {
184184
hasDimension = true;
185185
break;
186186
}
@@ -233,9 +233,9 @@ void shouldAddDimensionSet() throws Exception {
233233
boolean hasDim2 = false;
234234
for (JsonNode dimension : dimensions) {
235235
String dimName = dimension.asText();
236-
if (dimName.equals("Dim1")) {
236+
if ("Dim1".equals(dimName)) {
237237
hasDim1 = true;
238-
} else if (dimName.equals("Dim2")) {
238+
} else if ("Dim2".equals(dimName)) {
239239
hasDim2 = true;
240240
}
241241
}
@@ -348,6 +348,8 @@ void shouldLogWarningOnEmptyMetrics() throws Exception {
348348
// Read the log file and check for the warning
349349
String logContent = new String(Files.readAllBytes(logFile.toPath()), StandardCharsets.UTF_8);
350350
assertThat(logContent).contains("No metrics were emitted");
351+
// No EMF output should be generated
352+
assertThat(outputStreamCaptor.toString().trim()).isEmpty();
351353
}
352354

353355
@Test

0 commit comments

Comments
 (0)