Skip to content
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

[Dynatrace] Logging verbosity: Move metadata discrepancy logging to WarnThenDebug #4583

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -60,18 +60,18 @@ public final class DynatraceExporterV2 extends AbstractDynatraceExporter {

private static final Pattern IS_NULL_ERROR_RESPONSE = Pattern.compile("\"error\":\\s?null");

private static final WarnThenDebugLogger stackTraceWarnThenDebugLogger = new WarnThenDebugLogger(
DynatraceExporterV2.class);

private static final WarnThenDebugLogger nanGaugeWarnThenDebugLogger = new WarnThenDebugLogger(
DynatraceExporterV2.class);

private static final Map<String, String> staticDimensions = Collections.singletonMap("dt.metrics.source",
"micrometer");

// This should be non-static for MockLoggerFactory.injectLogger() in tests.
// Loggers must be non-static for MockLoggerFactory.injectLogger() in tests.
private final InternalLogger logger = InternalLoggerFactory.getInstance(DynatraceExporterV2.class);

private final WarnThenDebugLogger stackTraceLogger = new WarnThenDebugLoggers.StackTraceLogger();

private final WarnThenDebugLogger nanGaugeLogger = new WarnThenDebugLoggers.NanGaugeLogger();

private final WarnThenDebugLogger metadataDiscrepancyLogger = new WarnThenDebugLoggers.MetadataDiscrepancyLogger();

private MetricLinePreConfiguration preConfiguration;

private boolean skipExport = false;
Expand Down Expand Up @@ -219,7 +219,7 @@ private String createGaugeLine(Meter meter, Map<String, String> seenMetadata, Me
// NaN's are currently dropped on the Dynatrace side, so dropping them
// on the client side here will not change the metrics in Dynatrace.

nanGaugeWarnThenDebugLogger.log(() -> String.format(
nanGaugeLogger.log(() -> String.format(
"Meter '%s' returned a value of NaN, which will not be exported. This can be a deliberate value or because the weak reference to the backing object expired.",
meter.getId().getName()));
return null;
Expand Down Expand Up @@ -418,9 +418,11 @@ private void send(List<String> metricLines) {
response.code(), getTruncatedBody(response)));
}
catch (Throwable throwable) {
logger.warn("Failed metric ingestion: " + throwable);
stackTraceWarnThenDebugLogger.log("Stack trace for previous 'Failed metric ingestion' warning log: ",
throwable);
// the "general" logger logs the message, the WarnThenDebugLogger logs the
// stack trace.
logger.warn("Failed metric ingestion: {}", throwable.toString());
stackTraceLogger.log(String.format("Stack trace for previous 'Failed metric ingestion' warning log: %s",
throwable.getMessage()), throwable);
}
}

Expand Down Expand Up @@ -501,10 +503,10 @@ private void storeMetadata(MetricLineBuilder.MetadataStep metadataStep, Map<Stri
// set for this metric key.
if (!previousMetadataLine.equals(metadataLine)) {
seenMetadata.put(key, null);
logger.warn(
"Metadata discrepancy detected:\n" + "original metadata:\t{}\n" + "tried to set new:\t{}\n"
+ "Metadata for metric key {} will not be sent.",
previousMetadataLine, metadataLine, key);
metadataDiscrepancyLogger.log(() -> String.format(
"Metadata discrepancy detected:\n" + "original metadata:\t%s\n" + "tried to set new:\t%s\n"
+ "Metadata for metric key %s will not be sent.",
previousMetadataLine, metadataLine, key));
}
}
// else:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright 2024 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micrometer.dynatrace.v2;

import io.micrometer.common.util.internal.logging.WarnThenDebugLogger;

/**
* This internal class holds loggers that are used in {@link DynatraceExporterV2}. They
* are all just extending the default {@link WarnThenDebugLogger}. It is necessary to
* extend them, because the {@link WarnThenDebugLogger} does not allow creating a new
* logger with just a name (a class object has to be passed). If the WarnThenDebugLogger
* is created with the same class type multiple times, the same instance will be returned.
* This would mean that in a scenario with multiple loggers, only the first call would log
* the warning, and all subsequent calls will log at debug.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think that's accurate. The two instances will use the same logger but the level is still controlled by the instance flag in each.

I wrote the following test:

@Test
void twoInstancesSameLoggerClass() {
    WarnThenDebugLogger first = new WarnThenDebugLogger(WarnThenDebugLoggerTest.class);
    WarnThenDebugLogger second = new WarnThenDebugLogger(WarnThenDebugLoggerTest.class);

    first.log("hi");
    second.log("hello");
}

And the log output is:

16:19:03.684 [main] WARN io.micrometer.common.util.internal.logging.WarnThenDebugLoggerTest - hi Note that subsequent logs will be logged at debug level.
16:19:03.684 [main] WARN io.micrometer.common.util.internal.logging.WarnThenDebugLoggerTest - hello Note that subsequent logs will be logged at debug level.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you are right, the description is off. I wanted to assert on the different WarnThenDebugLoggers, to ensure that all warning messages are triggered. Initially, I was using three separate WarnThenDebugLoggers to do that (without the subclasses). There is only one constructor for WarnThenDebugLogger and it takes a Class parameter:

public WarnThenDebugLogger(Class<?> clazz) {
this.logger = InternalLoggerFactory.getInstance(clazz);
}

Since there is no obvious choice of which Class type to put there, I at first put WarnThenDebugLogger.class.
In the tests, we are using the MockLoggerFactory to get these Loggers. There, I have two choices of how to retrieve the Loggers:
public MockLogger getLogger(Class<?> clazz) {
return getLogger(clazz.getName());
}
and
public MockLogger getLogger(String name) {
return loggers.computeIfAbsent(name, MockLogger::new);
}

Since there is no way of creating the WarnThenDebugLogger with a name instead of the Class object, all three used the WarnThenDebugLogger.class to create, and then the same WarnThenDebugLogger.class to retrieve them from the MockLoggerFactory. But: the MockLoggerFactory cannot distinguish between these instances, since they all have the same name. Consequently, the tests were very flaky, because it is not clear which WarnThenDebugLogger was being returned by mockLoggerFactory.getLogger(WarnThenDebugLogger.class).
In order to work around this, I created the new classes that basically set a specific "name" (by using the Class type of the subclass) to the separate WarnThenDebugLoggers. This way, there will be three separate WarnThenDebugLoggers in the MockLoggerFactory (each with a different name), and I can pull the right one to assert on.

Do you think this is the wrong approach? Alternatively, I could add API surface to the WarnThenDebugLogger to allow creating one with a specific name. Happy to discuss other alternatives as well!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the description in f05701b

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Perhaps we can look at improving the usability of MockLoggerFactory or some other way to make testing this easier. /cc @jonatan-ivanov
The changes are mostly internal, though the class that will be logged is different with this change. I assume you're okay with that, and if so, I'm okay to merge the changes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, sounds good! Thank you!

*/
class WarnThenDebugLoggers {

static class StackTraceLogger extends WarnThenDebugLogger {

public StackTraceLogger() {
super(StackTraceLogger.class);
}

}

static class NanGaugeLogger extends WarnThenDebugLogger {

public NanGaugeLogger() {
super(NanGaugeLogger.class);
}

}

static class MetadataDiscrepancyLogger extends WarnThenDebugLogger {

public MetadataDiscrepancyLogger() {
super(MetadataDiscrepancyLogger.class);
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import io.micrometer.dynatrace.DynatraceApiVersion;
import io.micrometer.dynatrace.DynatraceConfig;
import io.micrometer.dynatrace.DynatraceMeterRegistry;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
Expand All @@ -45,7 +44,7 @@
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static io.micrometer.common.util.internal.logging.InternalLogLevel.ERROR;
import static io.micrometer.common.util.internal.logging.InternalLogLevel.*;
import static io.micrometer.core.instrument.MockClock.clock;
import static java.lang.Double.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
Expand All @@ -64,9 +63,9 @@
*/
class DynatraceExporterV2Test {

private static final MockLoggerFactory FACTORY = new MockLoggerFactory();
private MockLoggerFactory loggerFactory;

private static final MockLogger LOGGER = FACTORY.getLogger(DynatraceExporterV2.class);
private MockLogger logger;

private static final Map<String, String> SEEN_METADATA = new HashMap<>();

Expand All @@ -80,6 +79,8 @@ class DynatraceExporterV2Test {

private DynatraceExporterV2 exporter;

private static final String subsequentLogsAsDebug = "Note that subsequent logs will be logged at debug level.";

@BeforeEach
void setUp() {
this.config = createDefaultDynatraceConfig();
Expand All @@ -90,18 +91,19 @@ void setUp() {
// library will not
// complain.
this.httpClient = mock(HttpSender.class);
this.exporter = FACTORY.injectLogger(() -> createExporter(httpClient));

// ensures new MockLoggers are created for each test.
// Since there are some asserts on log lines, different test runs do not reuse the
// same loggers and thus do not interfere.
this.loggerFactory = new MockLoggerFactory();
this.exporter = loggerFactory.injectLogger(() -> createExporter(httpClient));
this.logger = loggerFactory.getLogger(DynatraceExporterV2.class);

this.meterRegistry = DynatraceMeterRegistry.builder(config).clock(clock).httpClient(httpClient).build();

SEEN_METADATA.clear();
}

@AfterEach
void tearDown() {
LOGGER.clear();
}

@Test
void toGaugeLine() {
meterRegistry.gauge("my.gauge", 1.23);
Expand All @@ -118,6 +120,27 @@ void toGaugeLineShouldDropNanValue() {
assertThat(exporter.toGaugeLine(gauge, SEEN_METADATA)).isEmpty();
}

@Test
void toGaugeLineShouldDropNanValue_testLogWarnThenDebug() {
MockLogger nanGaugeLogger = loggerFactory.getLogger(WarnThenDebugLoggers.NanGaugeLogger.class);

String expectedMessage = "Meter 'my.gauge' returned a value of NaN, which will not be exported. This can be a deliberate value or because the weak reference to the backing object expired.";

LogEvent warnEvent = new LogEvent(WARN, String.join(" ", expectedMessage, subsequentLogsAsDebug), null);
LogEvent debugEvent = new LogEvent(DEBUG, expectedMessage, null);

meterRegistry.gauge("my.gauge", NaN);
Gauge gauge = meterRegistry.find("my.gauge").gauge();

// first export; log at warn
assertThat(exporter.toGaugeLine(gauge, SEEN_METADATA)).isEmpty();
assertThat(nanGaugeLogger.getLogEvents()).hasSize(1).containsExactly(warnEvent);

// second export; log at debug
assertThat(exporter.toGaugeLine(gauge, SEEN_METADATA)).isEmpty();
assertThat(nanGaugeLogger.getLogEvents()).hasSize(2).containsExactly(warnEvent, debugEvent);
}

@Test
void toGaugeLineShouldDropInfiniteValues() {
meterRegistry.gauge("my.gauge", POSITIVE_INFINITY);
Expand Down Expand Up @@ -652,10 +675,67 @@ void failOnSendShouldHaveProperLogging() throws Throwable {
Gauge gauge = meterRegistry.find("my.gauge").gauge();
exporter.export(Collections.singletonList(gauge));

assertThat(LOGGER.getLogEvents())
assertThat(logger.getLogEvents())
.contains(new LogEvent(ERROR, "Failed metric ingestion: Error Code=500, Response Body=simulated", null));
}

@Test
void failOnSendWithExceptionShouldHaveProperLogging_warnThenDebug() {
MockLogger stackTraceLogger = loggerFactory.getLogger(WarnThenDebugLoggers.StackTraceLogger.class);

Throwable expectedException = new RuntimeException("test exception", new Throwable("root cause exception"));
when(httpClient.post(config.uri())).thenThrow(expectedException);

// the "general" logger just logs the message, the WarnThenDebugLogger contains
// the exception & stack trace.
String expectedWarnThenDebugMessage = "Stack trace for previous 'Failed metric ingestion' warning log:";
// these two will be logged by the WarnThenDebugLogger:
// the warning message is suffixed with "Note that subsequent logs will be logged
// at debug level.".
LogEvent warnThenDebugWarningLog = new LogEvent(WARN,
String.join(" ", expectedWarnThenDebugMessage, expectedException.getMessage(), subsequentLogsAsDebug),
expectedException);
LogEvent warnThenDebugDebugLog = new LogEvent(DEBUG,
String.join(" ", expectedWarnThenDebugMessage, expectedException.getMessage()), expectedException);

// this will be logged by the "general" logger in a single line (once per export)
LogEvent expectedExceptionLogMessage = new LogEvent(WARN,
"Failed metric ingestion: java.lang.RuntimeException: " + expectedException.getMessage(), null);

meterRegistry.gauge("my.gauge", 1d);
Gauge gauge = meterRegistry.find("my.gauge").gauge();

// first export
exporter.export(Collections.singletonList(gauge));

// after the first export, the general logger only has the WARN event, but not the
// debug event.
assertThat(logger.getLogEvents()).containsOnlyOnce(expectedExceptionLogMessage);

long countExceptionLogsFirstExport = logger.getLogEvents()
.stream()
.filter(event -> event.equals(expectedExceptionLogMessage))
.count();
assertThat(countExceptionLogsFirstExport).isEqualTo(1);

// the WarnThenDebugLogger only has one event so far.
assertThat(stackTraceLogger.getLogEvents()).hasSize(1).containsExactly(warnThenDebugWarningLog);

// second export
exporter.export(Collections.singletonList(gauge));

// after the second export, the general logger contains the warning log twice
long countExceptionLogsSecondExport = logger.getLogEvents()
.stream()
.filter(event -> event.equals(expectedExceptionLogMessage))
.count();
assertThat(countExceptionLogsSecondExport).isEqualTo(2);

// the WarnThenDebugLogger now has two logs.
assertThat(stackTraceLogger.getLogEvents()).hasSize(2)
.containsExactly(warnThenDebugWarningLog, warnThenDebugDebugLog);
}

@Test
void endpointPickedUpBetweenExportsAndChangedPropertiesFile() throws Throwable {
String randomUuid = UUID.randomUUID().toString();
Expand Down Expand Up @@ -942,6 +1022,48 @@ void conflictingMetadataIsIgnored() {
});
}

@Test
void conflictingMetadataIsIgnored_testLogWarnThenDebug() {
MockLogger metadataDiscrepancyLogger = loggerFactory
.getLogger(WarnThenDebugLoggers.MetadataDiscrepancyLogger.class);

String expectedLogMessage = "Metadata discrepancy detected:\n"
+ "original metadata:\t#my.count count dt.meta.description=count\\ 1\\ description,dt.meta.unit=Bytes\n"
+ "tried to set new:\t#my.count count dt.meta.description=count\\ description\n"
+ "Metadata for metric key my.count will not be sent.";
LogEvent warnEvent = new LogEvent(WARN, String.join(" ", expectedLogMessage, subsequentLogsAsDebug), null);
LogEvent debugEvent = new LogEvent(DEBUG, expectedLogMessage, null);

HttpSender.Request.Builder builder = mock(HttpSender.Request.Builder.class);
when(httpClient.post(anyString())).thenReturn(builder);

// the unit and description are different between counters, while the name stays
// the same.
Counter counter1 = Counter.builder("my.count")
.description("count 1 description")
.baseUnit("Bytes")
.tag("counter-number", "counter1")
.register(meterRegistry);
Counter counter2 = Counter.builder("my.count")
.description("count description")
.baseUnit("not Bytes")
.tag("counter-number", "counter2")
.register(meterRegistry);

counter1.increment(5.234);
counter2.increment(2.345);

// first export
exporter.export(meterRegistry.getMeters());

assertThat(metadataDiscrepancyLogger.getLogEvents()).hasSize(1).containsExactly(warnEvent);

// second export
exporter.export(meterRegistry.getMeters());
assertThat(metadataDiscrepancyLogger.getLogEvents()).hasSize(2).containsExactly(warnEvent, debugEvent);

}

@Test
void metadataIsNotExportedWhenTurnedOff() {
HttpSender.Request.Builder builder = spy(HttpSender.Request.build(config.uri(), httpClient));
Expand Down