Skip to content

Commit

Permalink
Log warning and do nothing on double binding to same registry
Browse files Browse the repository at this point in the history
  • Loading branch information
shakuzen committed Feb 5, 2025
1 parent cd4b6bf commit 66368f4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

import io.micrometer.common.lang.NonNullApi;
import io.micrometer.common.lang.NonNullFields;
import io.micrometer.common.util.internal.logging.InternalLogger;
import io.micrometer.common.util.internal.logging.InternalLoggerFactory;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
Expand Down Expand Up @@ -60,6 +62,8 @@ public class Log4j2Metrics implements MeterBinder, AutoCloseable {

private static final String METER_DESCRIPTION = "Number of log events";

private static final InternalLogger logger = InternalLoggerFactory.getInstance(Log4j2Metrics.class);

private final Iterable<Tag> tags;

private final LoggerContext loggerContext;
Expand All @@ -83,6 +87,10 @@ public Log4j2Metrics(Iterable<Tag> tags, LoggerContext loggerContext) {

@Override
public void bindTo(MeterRegistry registry) {
if (metricsFilters.containsKey(registry)) {
logger.warn("This Log4j2Metrics instance has already been bound to the registry {}", registry);
return;
}
Configuration configuration = loggerContext.getConfiguration();
registerMetricsFilter(configuration, registry);
loggerContext.updateLoggers(configuration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,4 +341,31 @@ void shouldNotRebindMetricsIfBinderIsClosed() {
assertThat(registry.get("log4j2.events").tags("level", "error").counter().count()).isEqualTo(1);
}

@Test
void bindingTwiceToSameRegistry_doesNotDoubleCount() {
LoggerContext context = new LoggerContext("test");
Logger logger = context.getLogger("com.test");

try (Log4j2Metrics metrics = new Log4j2Metrics(emptyList(), context)) {
// binding twice
metrics.bindTo(registry);
metrics.bindTo(registry);

logger.error("first");

assertThat(registry.get("log4j2.events").tags("level", "error").counter().count()).isEqualTo(1);

context.reconfigure();

logger.error("second");
assertThat(registry.get("log4j2.events").tags("level", "error").counter().count()).isEqualTo(2);
}

// no additional events should be counted now
context.reconfigure();

logger.error("third");
assertThat(registry.get("log4j2.events").tags("level", "error").counter().count()).isEqualTo(2);
}

}

0 comments on commit 66368f4

Please sign in to comment.