diff --git a/benchmarks/benchmarks-core/src/jmh/java/io/micrometer/benchmark/compare/CompareCountersWithOtherLibraries.java b/benchmarks/benchmarks-core/src/jmh/java/io/micrometer/benchmark/compare/CompareCountersWithOtherLibraries.java index c89daeea2f..5553be9547 100644 --- a/benchmarks/benchmarks-core/src/jmh/java/io/micrometer/benchmark/compare/CompareCountersWithOtherLibraries.java +++ b/benchmarks/benchmarks-core/src/jmh/java/io/micrometer/benchmark/compare/CompareCountersWithOtherLibraries.java @@ -123,8 +123,11 @@ public static class PrometheusState { @Setup(Level.Trial) public void setup() { counter = io.prometheus.client.Counter.build().name("counter").help("A counter").create(); - counterWithTags = io.prometheus.client.Counter.build().name("counter") - .help("Counter with two tags declared").labelNames("key1", "key2").register(); + counterWithTags = io.prometheus.client.Counter.build() + .name("counter") + .help("Counter with two tags declared") + .labelNames("key1", "key2") + .register(); } } @@ -174,7 +177,8 @@ public void prometheusCounterWithTags(PrometheusState state) { public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder().include(CompareCountersWithOtherLibraries.class.getSimpleName()) - .addProfiler(GCProfiler.class).build(); + .addProfiler(GCProfiler.class) + .build(); new Runner(opt).run(); } diff --git a/benchmarks/benchmarks-core/src/jmh/java/io/micrometer/benchmark/compare/CompareHistogramsWithOtherLibraries.java b/benchmarks/benchmarks-core/src/jmh/java/io/micrometer/benchmark/compare/CompareHistogramsWithOtherLibraries.java index 39148ab5c2..e36f0f27cc 100644 --- a/benchmarks/benchmarks-core/src/jmh/java/io/micrometer/benchmark/compare/CompareHistogramsWithOtherLibraries.java +++ b/benchmarks/benchmarks-core/src/jmh/java/io/micrometer/benchmark/compare/CompareHistogramsWithOtherLibraries.java @@ -64,7 +64,8 @@ public static class Data { public void setup() { final Random r = new Random(1234567891L); dataIterator = Iterators.cycle(Stream.generate(() -> Math.round(Math.exp(2.0 + r.nextGaussian()))) - .limit(1048576).collect(Collectors.toList())); + .limit(1048576) + .collect(Collectors.toList())); } } @@ -145,11 +146,15 @@ public static class PrometheusState { @Setup(Level.Trial) public void setup() { - double[] micrometerBuckets = Doubles.toArray( - PercentileHistogramBuckets.buckets(DistributionStatisticConfig.builder().minimumExpectedValue(0.0) - .maximumExpectedValue(Double.POSITIVE_INFINITY).percentilesHistogram(true).build())); - histogram = io.prometheus.client.Histogram.build("histogram", "A histogram").buckets(micrometerBuckets) - .create(); + double[] micrometerBuckets = Doubles + .toArray(PercentileHistogramBuckets.buckets(DistributionStatisticConfig.builder() + .minimumExpectedValue(0.0) + .maximumExpectedValue(Double.POSITIVE_INFINITY) + .percentilesHistogram(true) + .build())); + histogram = io.prometheus.client.Histogram.build("histogram", "A histogram") + .buckets(micrometerBuckets) + .create(); } @TearDown(Level.Iteration) diff --git a/build.gradle b/build.gradle index cc2f86b3a8..2dcf8bbe78 100644 --- a/build.gradle +++ b/build.gradle @@ -17,7 +17,7 @@ buildscript { classpath 'io.github.gradle-nexus:publish-plugin:1.1.0' classpath 'me.champeau.gradle:japicmp-gradle-plugin:0.4.1' classpath 'de.undercouch:gradle-download-task:5.2.1' - classpath 'io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.35' + classpath 'io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.36' constraints { classpath('org.ow2.asm:asm:7.3.1') { diff --git a/buildscript-gradle.lockfile b/buildscript-gradle.lockfile index 867ea6d99e..d8648462c1 100644 --- a/buildscript-gradle.lockfile +++ b/buildscript-gradle.lockfile @@ -49,8 +49,8 @@ de.undercouch:gradle-download-task:5.2.1=classpath gradle.plugin.com.hierynomus.gradle.plugins:license-gradle-plugin:0.16.1=classpath info.picocli:picocli:4.3.1=classpath io.github.gradle-nexus:publish-plugin:1.1.0=classpath -io.spring.javaformat:spring-javaformat-formatter-shaded:0.0.35=classpath -io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.35=classpath +io.spring.javaformat:spring-javaformat-formatter-shaded:0.0.36=classpath +io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.36=classpath io.spring.nohttp:nohttp-checkstyle:0.0.11=classpath io.spring.nohttp:nohttp-gradle:0.0.11=classpath io.spring.nohttp:nohttp:0.0.11=classpath diff --git a/implementations/micrometer-registry-appoptics/src/main/java/io/micrometer/appoptics/AppOpticsMeterRegistry.java b/implementations/micrometer-registry-appoptics/src/main/java/io/micrometer/appoptics/AppOpticsMeterRegistry.java index 4133cb0cda..ed7c8d8bc9 100644 --- a/implementations/micrometer-registry-appoptics/src/main/java/io/micrometer/appoptics/AppOpticsMeterRegistry.java +++ b/implementations/micrometer-registry-appoptics/src/main/java/io/micrometer/appoptics/AppOpticsMeterRegistry.java @@ -174,8 +174,8 @@ Optional writeMeter(Meter meter) { } StringJoiner joiner = new StringJoiner(","); for (int i = 0; i < statistics.size(); i++) { - joiner.add( - write(meter.getId().withTag(statistics.get(i)), null, Fields.Value.tag(), decimal(values.get(i)))); + joiner + .add(write(meter.getId().withTag(statistics.get(i)), null, Fields.Value.tag(), decimal(values.get(i)))); } return Optional.of(joiner.toString()); } @@ -240,9 +240,9 @@ private Optional writeTimer(Timer timer) { private Optional writeSummary(DistributionSummary summary) { HistogramSnapshot snapshot = summary.takeSnapshot(); if (snapshot.count() > 0) { - return Optional.of(write(summary.getId(), "distributionSummary", Fields.Count.tag(), - decimal(summary.count()), Fields.Sum.tag(), decimal(summary.totalAmount()), Fields.Max.tag(), - decimal(summary.max()))); + return Optional + .of(write(summary.getId(), "distributionSummary", Fields.Count.tag(), decimal(summary.count()), + Fields.Sum.tag(), decimal(summary.totalAmount()), Fields.Max.tag(), decimal(summary.max()))); } return Optional.empty(); } @@ -258,8 +258,10 @@ private Optional writeLongTaskTimer(LongTaskTimer timer) { private String write(Meter.Id id, @Nullable String type, String... statistics) { StringBuilder sb = new StringBuilder(); - sb.append("{\"name\":\"").append(escapeJson(getConventionName(id))).append("\",\"period\":") - .append(config.step().getSeconds()); + sb.append("{\"name\":\"") + .append(escapeJson(getConventionName(id))) + .append("\",\"period\":") + .append(config.step().getSeconds()); if (!Fields.Value.tag().equals(statistics[0])) { sb.append(",\"attributes\":{\"aggregate\":false}"); diff --git a/implementations/micrometer-registry-appoptics/src/test/java/io/micrometer/appoptics/AppOpticsConfigTest.java b/implementations/micrometer-registry-appoptics/src/test/java/io/micrometer/appoptics/AppOpticsConfigTest.java index f5a852c5d4..8bc7170e30 100644 --- a/implementations/micrometer-registry-appoptics/src/test/java/io/micrometer/appoptics/AppOpticsConfigTest.java +++ b/implementations/micrometer-registry-appoptics/src/test/java/io/micrometer/appoptics/AppOpticsConfigTest.java @@ -35,7 +35,7 @@ void invalid() { props.put("appoptics.batchSize", Integer.toString(AppOpticsConfig.MAX_BATCH_SIZE * 2)); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactlyInAnyOrder("must be a valid URL", "is required"); + .containsExactlyInAnyOrder("must be a valid URL", "is required"); } @Test @@ -65,7 +65,7 @@ public String get(String key) { }.validate(); assertThat(validate.failures().stream().map(Validated.Invalid::getMessage)) - .containsOnly("cannot be greater than " + AppOpticsConfig.MAX_BATCH_SIZE); + .containsOnly("cannot be greater than " + AppOpticsConfig.MAX_BATCH_SIZE); } } diff --git a/implementations/micrometer-registry-appoptics/src/test/java/io/micrometer/appoptics/AppOpticsMeterRegistryTest.java b/implementations/micrometer-registry-appoptics/src/test/java/io/micrometer/appoptics/AppOpticsMeterRegistryTest.java index bfb8147c55..e31d63c228 100644 --- a/implementations/micrometer-registry-appoptics/src/test/java/io/micrometer/appoptics/AppOpticsMeterRegistryTest.java +++ b/implementations/micrometer-registry-appoptics/src/test/java/io/micrometer/appoptics/AppOpticsMeterRegistryTest.java @@ -142,12 +142,12 @@ void writeFunctionCounter() { @Test void writeFunctionCounterShouldDropInfiniteValues() { FunctionCounter counter = FunctionCounter.builder("myCounter", Double.POSITIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter).isPresent()).isFalse(); counter = FunctionCounter.builder("myCounter", Double.NEGATIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter).isPresent()).isFalse(); } @@ -188,7 +188,7 @@ void defaultValueDoesNoFlooring() { clock.add(Duration.ofSeconds(63)); assertThat(meterRegistry.getBodyMeasurementsPrefix()) - .isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 63)); + .isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 63)); } @Test @@ -198,17 +198,17 @@ void flooringRoundsToNearestStep() { clock.add(Duration.ofSeconds(63)); assertThat(meterRegistry.getBodyMeasurementsPrefix()) - .isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60)); + .isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60)); clock.addSeconds(56); // 119 assertThat(meterRegistry.getBodyMeasurementsPrefix()) - .isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60)); + .isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60)); clock.addSeconds(1); // 120 assertThat(meterRegistry.getBodyMeasurementsPrefix()) - .isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 120)); + .isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 120)); } } diff --git a/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/AtlasMeterRegistry.java b/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/AtlasMeterRegistry.java index db843e50fe..d7272e497e 100644 --- a/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/AtlasMeterRegistry.java +++ b/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/AtlasMeterRegistry.java @@ -159,7 +159,8 @@ private void registerHistogramGauges(HistogramSupport histogramSupport, Meter.Id private Id spectatorId(Meter.Id id) { List tags = getConventionTags(id).stream() - .map(t -> new BasicTag(t.getKey(), t.getValue())).collect(toList()); + .map(t -> new BasicTag(t.getKey(), t.getValue())) + .collect(toList()); return registry.createId(getConventionName(id), tags); } @@ -175,8 +176,9 @@ protected io.micrometer.core.instrument.Gauge newGauge(Meter.Id id, @Nullabl @Override protected FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction countFunction) { FunctionCounter fc = new StepFunctionCounter<>(id, clock, atlasConfig.step().toMillis(), obj, countFunction); - PolledMeter.using(registry).withId(spectatorId(id)).monitorMonotonicCounter(obj, - obj2 -> (long) countFunction.applyAsDouble(obj2)); + PolledMeter.using(registry) + .withId(spectatorId(id)) + .monitorMonotonicCounter(obj, obj2 -> (long) countFunction.applyAsDouble(obj2)); return fc; } @@ -231,8 +233,10 @@ protected TimeUnit getBaseTimeUnit() { @Override protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.builder().expiry(atlasConfig.step()).build() - .merge(DistributionStatisticConfig.DEFAULT); + return DistributionStatisticConfig.builder() + .expiry(atlasConfig.step()) + .build() + .merge(DistributionStatisticConfig.DEFAULT); } } diff --git a/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorDistributionSummary.java b/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorDistributionSummary.java index ea29c02e80..bfff2be05c 100644 --- a/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorDistributionSummary.java +++ b/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorDistributionSummary.java @@ -57,7 +57,7 @@ public double totalAmount() { public double max() { for (Measurement measurement : summary.measure()) { if (stream(measurement.id().tags().spliterator(), false) - .anyMatch(tag -> tag.key().equals("statistic") && tag.value().equals(Statistic.max.toString()))) { + .anyMatch(tag -> tag.key().equals("statistic") && tag.value().equals(Statistic.max.toString()))) { return measurement.value(); } } diff --git a/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorTimer.java b/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorTimer.java index 047e00c7c3..f722a89791 100644 --- a/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorTimer.java +++ b/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorTimer.java @@ -58,7 +58,7 @@ public double totalTime(TimeUnit unit) { public double max(TimeUnit unit) { for (Measurement measurement : timer.measure()) { if (stream(measurement.id().tags().spliterator(), false) - .anyMatch(tag -> tag.key().equals("statistic") && tag.value().equals(Statistic.max.toString()))) { + .anyMatch(tag -> tag.key().equals("statistic") && tag.value().equals(Statistic.max.toString()))) { return TimeUtils.secondsToUnit(measurement.value(), unit); } } diff --git a/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorToDoubleGauge.java b/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorToDoubleGauge.java index 04ea54eec8..b4f3063885 100644 --- a/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorToDoubleGauge.java +++ b/implementations/micrometer-registry-atlas/src/main/java/io/micrometer/atlas/SpectatorToDoubleGauge.java @@ -26,7 +26,7 @@ * identical to com.netflix.spectator.api.ObjectGauge which is not accessible in * Spectator. */ -class SpectatorToDoubleGauge extends AbstractMeter implements Gauge { +class SpectatorToDoubleGaugeextends AbstractMeter implements Gauge { private final ToDoubleFunction f; diff --git a/implementations/micrometer-registry-atlas/src/test/java/io/micrometer/atlas/AtlasMeterRegistryTest.java b/implementations/micrometer-registry-atlas/src/test/java/io/micrometer/atlas/AtlasMeterRegistryTest.java index a0285d38d0..875ef1dc7c 100644 --- a/implementations/micrometer-registry-atlas/src/test/java/io/micrometer/atlas/AtlasMeterRegistryTest.java +++ b/implementations/micrometer-registry-atlas/src/test/java/io/micrometer/atlas/AtlasMeterRegistryTest.java @@ -89,8 +89,11 @@ public Duration lwcStep() { AtlasRegistry r = (AtlasRegistry) registry.getSpectatorRegistry(); PolledMeter.update(r); clock.add(Duration.ofMinutes(1)); - return r.measurements().filter(m -> m.id().name().equals("test")).findFirst().map(Measurement::value) - .orElse(Double.NaN); + return r.measurements() + .filter(m -> m.id().name().equals("test")) + .findFirst() + .map(Measurement::value) + .orElse(Double.NaN); }; count.addAndGet(60); diff --git a/implementations/micrometer-registry-azure-monitor/src/main/java/io/micrometer/azuremonitor/AzureMonitorMeterRegistry.java b/implementations/micrometer-registry-azure-monitor/src/main/java/io/micrometer/azuremonitor/AzureMonitorMeterRegistry.java index 81c6ceb572..17e0784bae 100644 --- a/implementations/micrometer-registry-azure-monitor/src/main/java/io/micrometer/azuremonitor/AzureMonitorMeterRegistry.java +++ b/implementations/micrometer-registry-azure-monitor/src/main/java/io/micrometer/azuremonitor/AzureMonitorMeterRegistry.java @@ -194,8 +194,8 @@ private MetricTelemetry createMetricTelemetry(Meter meter, @Nullable String suff MetricTelemetry mt = new MetricTelemetry(); Meter.Id id = meter.getId(); - mt.setName(config().namingConvention().name(id.getName() + (suffix == null ? "" : "." + suffix), id.getType(), - id.getBaseUnit())); + mt.setName(config().namingConvention() + .name(id.getName() + (suffix == null ? "" : "." + suffix), id.getType(), id.getBaseUnit())); for (Tag tag : getConventionTags(meter.getId())) { mt.getContext().getProperties().putIfAbsent(tag.getKey(), tag.getValue()); diff --git a/implementations/micrometer-registry-azure-monitor/src/test/java/io/micrometer/azuremonitor/AzureMonitorMeterRegistryTest.java b/implementations/micrometer-registry-azure-monitor/src/test/java/io/micrometer/azuremonitor/AzureMonitorMeterRegistryTest.java index 0e8883a67e..31679238d1 100644 --- a/implementations/micrometer-registry-azure-monitor/src/test/java/io/micrometer/azuremonitor/AzureMonitorMeterRegistryTest.java +++ b/implementations/micrometer-registry-azure-monitor/src/test/java/io/micrometer/azuremonitor/AzureMonitorMeterRegistryTest.java @@ -64,8 +64,10 @@ void useTelemetryConfigInstrumentationKeyWhenSet() { @Test void failWhenTelemetryConfigInstrumentationKeyIsUnsetAndConfigInstrumentationKeyIsNull() { TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.createDefault(); - assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> AzureMonitorMeterRegistry - .builder(key -> null).telemetryConfiguration(telemetryConfiguration).build()); + assertThatExceptionOfType(ValidationException.class) + .isThrownBy(() -> AzureMonitorMeterRegistry.builder(key -> null) + .telemetryConfiguration(telemetryConfiguration) + .build()); } @Test @@ -86,8 +88,8 @@ void trackTimerWhenCountIsZeroShouldReturnEmpty() { @Test void trackFunctionTimer() { FunctionTimer functionTimer = FunctionTimer - .builder("my.function.timer", 1d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) - .register(registry); + .builder("my.function.timer", 1d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) + .register(registry); clock.add(config.step()); assertThat(registry.trackFunctionTimer(functionTimer)).hasSize(1); } @@ -95,8 +97,8 @@ void trackFunctionTimer() { @Test void trackFunctionTimerWhenCountIsZeroShouldReturnEmpty() { FunctionTimer functionTimer = FunctionTimer - .builder("my.function.timer", 0d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) - .register(registry); + .builder("my.function.timer", 0d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) + .register(registry); clock.add(config.step()); assertThat(registry.trackFunctionTimer(functionTimer)).isEmpty(); } @@ -104,7 +106,7 @@ void trackFunctionTimerWhenCountIsZeroShouldReturnEmpty() { @Test void trackDistributionSummary() { DistributionSummary distributionSummary = DistributionSummary.builder("my.distribution.summary") - .register(registry); + .register(registry); distributionSummary.record(1d); clock.add(config.step()); assertThat(registry.trackDistributionSummary(distributionSummary)).hasSize(1); @@ -113,7 +115,7 @@ void trackDistributionSummary() { @Test void trackDistributionSummaryWhenCountIsZeroShouldReturnEmpty() { DistributionSummary distributionSummary = DistributionSummary.builder("my.distribution.summary") - .register(registry); + .register(registry); clock.add(config.step()); assertThat(registry.trackDistributionSummary(distributionSummary)).isEmpty(); } diff --git a/implementations/micrometer-registry-cloudwatch/src/main/java/io/micrometer/cloudwatch/CloudWatchMeterRegistry.java b/implementations/micrometer-registry-cloudwatch/src/main/java/io/micrometer/cloudwatch/CloudWatchMeterRegistry.java index d9fc8c0c5d..310b7d5aad 100644 --- a/implementations/micrometer-registry-cloudwatch/src/main/java/io/micrometer/cloudwatch/CloudWatchMeterRegistry.java +++ b/implementations/micrometer-registry-cloudwatch/src/main/java/io/micrometer/cloudwatch/CloudWatchMeterRegistry.java @@ -112,7 +112,7 @@ protected void publish() { // VisibleForTesting void sendMetricData(List metricData) throws InterruptedException { PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest().withNamespace(config.namespace()) - .withMetricData(metricData); + .withMetricData(metricData); CountDownLatch latch = new CountDownLatch(1); amazonCloudWatchAsync.putMetricDataAsync(putMetricDataRequest, new AsyncHandler() { @@ -182,8 +182,8 @@ private Stream counterData(Counter counter) { // VisibleForTesting Stream timerData(Timer timer) { Stream.Builder metrics = Stream.builder(); - metrics.add( - metricDatum(timer.getId(), "sum", getBaseTimeUnit().name(), timer.totalTime(getBaseTimeUnit()))); + metrics + .add(metricDatum(timer.getId(), "sum", getBaseTimeUnit().name(), timer.totalTime(getBaseTimeUnit()))); long count = timer.count(); metrics.add(metricDatum(timer.getId(), "count", StandardUnit.Count, count)); if (count > 0) { @@ -250,8 +250,8 @@ Stream functionTimerData(FunctionTimer timer) { // VisibleForTesting Stream metricData(Meter m) { return stream(m.measure().spliterator(), false) - .map(ms -> metricDatum(m.getId().withTag(ms.getStatistic()), ms.getValue())) - .filter(Objects::nonNull); + .map(ms -> metricDatum(m.getId().withTag(ms.getStatistic()), ms.getValue())) + .filter(Objects::nonNull); } @Nullable @@ -276,8 +276,11 @@ private MetricDatum metricDatum(Meter.Id id, @Nullable String suffix, StandardUn } List tags = id.getConventionTags(config().namingConvention()); - return new MetricDatum().withMetricName(getMetricName(id, suffix)).withDimensions(toDimensions(tags)) - .withTimestamp(timestamp).withValue(CloudWatchUtils.clampMetricValue(value)).withUnit(standardUnit); + return new MetricDatum().withMetricName(getMetricName(id, suffix)) + .withDimensions(toDimensions(tags)) + .withTimestamp(timestamp) + .withValue(CloudWatchUtils.clampMetricValue(value)) + .withUnit(standardUnit); } // VisibleForTesting @@ -295,14 +298,16 @@ private StandardUnit toStandardUnit(@Nullable String unit) { } private List toDimensions(List tags) { - return tags.stream().filter(this::isAcceptableTag) - .map(tag -> new Dimension().withName(tag.getKey()).withValue(tag.getValue())).collect(toList()); + return tags.stream() + .filter(this::isAcceptableTag) + .map(tag -> new Dimension().withName(tag.getKey()).withValue(tag.getValue())) + .collect(toList()); } private boolean isAcceptableTag(Tag tag) { if (StringUtils.isBlank(tag.getValue())) { warnThenDebugLogger - .log(() -> "Dropping a tag with key '" + tag.getKey() + "' because its value is blank."); + .log(() -> "Dropping a tag with key '" + tag.getKey() + "' because its value is blank."); return false; } return true; diff --git a/implementations/micrometer-registry-cloudwatch/src/test/java/io/micrometer/cloudwatch/CloudWatchMeterRegistryTest.java b/implementations/micrometer-registry-cloudwatch/src/test/java/io/micrometer/cloudwatch/CloudWatchMeterRegistryTest.java index 4940b71cb1..3d3c95eac0 100644 --- a/implementations/micrometer-registry-cloudwatch/src/test/java/io/micrometer/cloudwatch/CloudWatchMeterRegistryTest.java +++ b/implementations/micrometer-registry-cloudwatch/src/test/java/io/micrometer/cloudwatch/CloudWatchMeterRegistryTest.java @@ -105,16 +105,17 @@ void batchFunctionCounterData() { @Test void batchFunctionCounterDataShouldClampInfiniteValues() { FunctionCounter counter = FunctionCounter - .builder("my.positive.infinity", Double.POSITIVE_INFINITY, Number::doubleValue).register(registry); + .builder("my.positive.infinity", Double.POSITIVE_INFINITY, Number::doubleValue) + .register(registry); clock.add(config.step()); assertThat(registry.new Batch().functionCounterData(counter).findFirst().get().getValue()) - .isEqualTo(CloudWatchUtils.MAXIMUM_ALLOWED_VALUE); + .isEqualTo(CloudWatchUtils.MAXIMUM_ALLOWED_VALUE); counter = FunctionCounter.builder("my.negative.infinity", Double.NEGATIVE_INFINITY, Number::doubleValue) - .register(registry); + .register(registry); clock.add(config.step()); assertThat(registry.new Batch().functionCounterData(counter).findFirst().get().getValue()) - .isEqualTo(-CloudWatchUtils.MAXIMUM_ALLOWED_VALUE); + .isEqualTo(-CloudWatchUtils.MAXIMUM_ALLOWED_VALUE); } @Test @@ -138,15 +139,16 @@ void writeMeterWhenCustomMeterHasMixedNaNAndNonNaNValuesShouldSkipOnlyNaNValues( @Test void writeShouldDropTagWithBlankValue() { registry.gauge("my.gauge", Tags.of("accepted", "foo").and("empty", ""), 1d); - assertThat(registry.metricData()).hasSize(1).allSatisfy(datum -> assertThat(datum.getDimensions()).hasSize(1) + assertThat(registry.metricData()).hasSize(1) + .allSatisfy(datum -> assertThat(datum.getDimensions()).hasSize(1) .contains(new Dimension().withName("accepted").withValue("foo"))); } @Test void functionTimerData() { FunctionTimer timer = FunctionTimer - .builder("my.function.timer", 1d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) - .register(registry); + .builder("my.function.timer", 1d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) + .register(registry); clock.add(config.step()); assertThat(registry.new Batch().functionTimerData(timer)).hasSize(3); } @@ -154,8 +156,8 @@ void functionTimerData() { @Test void functionTimerDataWhenSumIsNaNShouldReturnEmptyStream() { FunctionTimer timer = FunctionTimer - .builder("my.function.timer", Double.NaN, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) - .register(registry); + .builder("my.function.timer", Double.NaN, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) + .register(registry); clock.add(config.step()); assertThat(registry.new Batch().functionTimerData(timer)).isEmpty(); } diff --git a/implementations/micrometer-registry-cloudwatch/src/test/java/io/micrometer/cloudwatch/CloudWatchUtilsTest.java b/implementations/micrometer-registry-cloudwatch/src/test/java/io/micrometer/cloudwatch/CloudWatchUtilsTest.java index c3986d856a..b24d863b39 100644 --- a/implementations/micrometer-registry-cloudwatch/src/test/java/io/micrometer/cloudwatch/CloudWatchUtilsTest.java +++ b/implementations/micrometer-registry-cloudwatch/src/test/java/io/micrometer/cloudwatch/CloudWatchUtilsTest.java @@ -34,16 +34,16 @@ void testClamp() { assertThat(CloudWatchUtils.clampMetricValue(Double.NaN)).as("Check NaN").isNaN(); assertThat(CloudWatchUtils.clampMetricValue(Double.MIN_VALUE)).as("Check minimum value") - .isEqualTo(EXPECTED_MIN); + .isEqualTo(EXPECTED_MIN); assertThat(CloudWatchUtils.clampMetricValue(Double.NEGATIVE_INFINITY)).as("Check negative infinity") - .isEqualTo(-EXPECTED_MAX); + .isEqualTo(-EXPECTED_MAX); assertThat(CloudWatchUtils.clampMetricValue(Double.POSITIVE_INFINITY)).as("Check positive infinity") - .isEqualTo(EXPECTED_MAX); + .isEqualTo(EXPECTED_MAX); assertThat(CloudWatchUtils.clampMetricValue(-Double.MAX_VALUE)).as("Check negative max value") - .isEqualTo(-EXPECTED_MAX); + .isEqualTo(-EXPECTED_MAX); assertThat(CloudWatchUtils.clampMetricValue(0)).as("Check 0").isEqualTo(0); diff --git a/implementations/micrometer-registry-cloudwatch2/src/main/java/io/micrometer/cloudwatch2/CloudWatchMeterRegistry.java b/implementations/micrometer-registry-cloudwatch2/src/main/java/io/micrometer/cloudwatch2/CloudWatchMeterRegistry.java index d7db73f9c0..4ceb9661d4 100644 --- a/implementations/micrometer-registry-cloudwatch2/src/main/java/io/micrometer/cloudwatch2/CloudWatchMeterRegistry.java +++ b/implementations/micrometer-registry-cloudwatch2/src/main/java/io/micrometer/cloudwatch2/CloudWatchMeterRegistry.java @@ -109,8 +109,10 @@ protected void publish() { // VisibleForTesting void sendMetricData(List metricData) throws InterruptedException { - PutMetricDataRequest putMetricDataRequest = PutMetricDataRequest.builder().namespace(config.namespace()) - .metricData(metricData).build(); + PutMetricDataRequest putMetricDataRequest = PutMetricDataRequest.builder() + .namespace(config.namespace()) + .metricData(metricData) + .build(); CountDownLatch latch = new CountDownLatch(1); cloudWatchAsyncClient.putMetricData(putMetricDataRequest).whenComplete((response, t) -> { if (t != null) { @@ -175,8 +177,8 @@ private Stream counterData(Counter counter) { // VisibleForTesting Stream timerData(Timer timer) { Stream.Builder metrics = Stream.builder(); - metrics.add( - metricDatum(timer.getId(), "sum", getBaseTimeUnit().name(), timer.totalTime(getBaseTimeUnit()))); + metrics + .add(metricDatum(timer.getId(), "sum", getBaseTimeUnit().name(), timer.totalTime(getBaseTimeUnit()))); long count = timer.count(); metrics.add(metricDatum(timer.getId(), "count", StandardUnit.COUNT, count)); if (count > 0) { @@ -242,8 +244,8 @@ Stream functionTimerData(FunctionTimer timer) { // VisibleForTesting Stream metricData(Meter m) { return stream(m.measure().spliterator(), false) - .map(ms -> metricDatum(m.getId().withTag(ms.getStatistic()), ms.getValue())) - .filter(Objects::nonNull); + .map(ms -> metricDatum(m.getId().withTag(ms.getStatistic()), ms.getValue())) + .filter(Objects::nonNull); } @Nullable @@ -268,9 +270,14 @@ private MetricDatum metricDatum(Meter.Id id, @Nullable String suffix, StandardUn } List tags = id.getConventionTags(config().namingConvention()); - return MetricDatum.builder().storageResolution(config.highResolution() ? 1 : 60) - .metricName(getMetricName(id, suffix)).dimensions(toDimensions(tags)).timestamp(timestamp) - .value(CloudWatchUtils.clampMetricValue(value)).unit(standardUnit).build(); + return MetricDatum.builder() + .storageResolution(config.highResolution() ? 1 : 60) + .metricName(getMetricName(id, suffix)) + .dimensions(toDimensions(tags)) + .timestamp(timestamp) + .value(CloudWatchUtils.clampMetricValue(value)) + .unit(standardUnit) + .build(); } // VisibleForTesting @@ -289,14 +296,16 @@ StandardUnit toStandardUnit(@Nullable String unit) { } private List toDimensions(List tags) { - return tags.stream().filter(this::isAcceptableTag) - .map(tag -> Dimension.builder().name(tag.getKey()).value(tag.getValue()).build()).collect(toList()); + return tags.stream() + .filter(this::isAcceptableTag) + .map(tag -> Dimension.builder().name(tag.getKey()).value(tag.getValue()).build()) + .collect(toList()); } private boolean isAcceptableTag(Tag tag) { if (StringUtils.isBlank(tag.getValue())) { warnThenDebugLogger - .log(() -> "Dropping a tag with key '" + tag.getKey() + "' because its value is blank."); + .log(() -> "Dropping a tag with key '" + tag.getKey() + "' because its value is blank."); return false; } return true; diff --git a/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchConfigTest.java b/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchConfigTest.java index 89ff1b10dd..c3cfb4ec73 100644 --- a/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchConfigTest.java +++ b/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchConfigTest.java @@ -45,7 +45,7 @@ void invalid() { props.put("cloudwatch.batchSize", Integer.toString(CloudWatchConfig.MAX_BATCH_SIZE * 2)); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactly("is required"); + .containsExactly("is required"); // automatically clamped back down to max batch size assertThat(config.batchSize()).isEqualTo(CloudWatchConfig.MAX_BATCH_SIZE); @@ -71,7 +71,7 @@ public String get(String key) { }.validate(); assertThat(validate.failures().stream().map(Validated.Invalid::getMessage)) - .containsOnly("cannot be greater than " + CloudWatchConfig.MAX_BATCH_SIZE); + .containsOnly("cannot be greater than " + CloudWatchConfig.MAX_BATCH_SIZE); } @Test diff --git a/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchMeterRegistryTest.java b/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchMeterRegistryTest.java index bdfcbcca34..27c5bfae82 100644 --- a/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchMeterRegistryTest.java +++ b/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchMeterRegistryTest.java @@ -105,16 +105,17 @@ void batchFunctionCounterData() { @Test void batchFunctionCounterDataShouldClampInfiniteValues() { FunctionCounter counter = FunctionCounter - .builder("my.positive.infinity", Double.POSITIVE_INFINITY, Number::doubleValue).register(registry); + .builder("my.positive.infinity", Double.POSITIVE_INFINITY, Number::doubleValue) + .register(registry); clock.add(config.step()); assertThat(registry.new Batch().functionCounterData(counter).findFirst().get().value()) - .isEqualTo(1.174271e+108); + .isEqualTo(1.174271e+108); counter = FunctionCounter.builder("my.negative.infinity", Double.NEGATIVE_INFINITY, Number::doubleValue) - .register(registry); + .register(registry); clock.add(config.step()); assertThat(registry.new Batch().functionCounterData(counter).findFirst().get().value()) - .isEqualTo(-1.174271e+108); + .isEqualTo(-1.174271e+108); } @Test @@ -138,15 +139,16 @@ void writeMeterWhenCustomMeterHasMixedNaNAndNonNaNValuesShouldSkipOnlyNaNValues( @Test void writeShouldDropTagWithBlankValue() { registry.gauge("my.gauge", Tags.of("accepted", "foo").and("empty", ""), 1d); - assertThat(registry.metricData()).hasSize(1).allSatisfy(datum -> assertThat(datum.dimensions()).hasSize(1) + assertThat(registry.metricData()).hasSize(1) + .allSatisfy(datum -> assertThat(datum.dimensions()).hasSize(1) .contains(Dimension.builder().name("accepted").value("foo").build())); } @Test void functionTimerData() { FunctionTimer timer = FunctionTimer - .builder("my.function.timer", 1d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) - .register(registry); + .builder("my.function.timer", 1d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) + .register(registry); clock.add(config.step()); assertThat(registry.new Batch().functionTimerData(timer)).hasSize(3); } @@ -154,8 +156,8 @@ void functionTimerData() { @Test void functionTimerDataWhenSumIsNaNShouldReturnEmptyStream() { FunctionTimer timer = FunctionTimer - .builder("my.function.timer", Double.NaN, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) - .register(registry); + .builder("my.function.timer", Double.NaN, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) + .register(registry); clock.add(config.step()); assertThat(registry.new Batch().functionTimerData(timer)).isEmpty(); } diff --git a/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchUtilsTest.java b/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchUtilsTest.java index 978082cec5..678d531219 100644 --- a/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchUtilsTest.java +++ b/implementations/micrometer-registry-cloudwatch2/src/test/java/io/micrometer/cloudwatch2/CloudWatchUtilsTest.java @@ -33,16 +33,16 @@ void testClamp() { assertThat(CloudWatchUtils.clampMetricValue(Double.NaN)).as("Check NaN").isNaN(); assertThat(CloudWatchUtils.clampMetricValue(Double.MIN_VALUE)).as("Check minimum value") - .isEqualTo(EXPECTED_MIN); + .isEqualTo(EXPECTED_MIN); assertThat(CloudWatchUtils.clampMetricValue(Double.NEGATIVE_INFINITY)).as("Check negative infinity") - .isEqualTo(-EXPECTED_MAX); + .isEqualTo(-EXPECTED_MAX); assertThat(CloudWatchUtils.clampMetricValue(Double.POSITIVE_INFINITY)).as("Check positive infinity") - .isEqualTo(EXPECTED_MAX); + .isEqualTo(EXPECTED_MAX); assertThat(CloudWatchUtils.clampMetricValue(-Double.MAX_VALUE)).as("Check negative max value") - .isEqualTo(-EXPECTED_MAX); + .isEqualTo(-EXPECTED_MAX); assertThat(CloudWatchUtils.clampMetricValue(0)).as("Check 0").isEqualTo(0); diff --git a/implementations/micrometer-registry-datadog/src/main/java/io/micrometer/datadog/DatadogMeterRegistry.java b/implementations/micrometer-registry-datadog/src/main/java/io/micrometer/datadog/DatadogMeterRegistry.java index df670cd768..6785853733 100644 --- a/implementations/micrometer-registry-datadog/src/main/java/io/micrometer/datadog/DatadogMeterRegistry.java +++ b/implementations/micrometer-registry-datadog/src/main/java/io/micrometer/datadog/DatadogMeterRegistry.java @@ -97,8 +97,8 @@ private DatadogMeterRegistry(DatadogConfig config, Clock clock, ThreadFactory th public void start(ThreadFactory threadFactory) { if (config.enabled()) { if (config.applicationKey() == null) { - logger.info( - "An application key must be configured in order for unit information to be sent to Datadog."); + logger + .info("An application key must be configured in order for unit information to be sent to Datadog."); } } super.start(threadFactory); @@ -140,9 +140,11 @@ protected void publish() { logger.trace("sending metrics batch to datadog:{}{}", System.lineSeparator(), body); - httpClient.post(datadogEndpoint).withJsonContent(body).send() - .onSuccess(response -> logger.debug("successfully sent {} metrics to datadog", batch.size())) - .onError(response -> logger.error("failed to send metrics to datadog: {}", response.body())); + httpClient.post(datadogEndpoint) + .withJsonContent(body) + .send() + .onSuccess(response -> logger.debug("successfully sent {} metrics to datadog", batch.size())) + .onError(response -> logger.error("failed to send metrics to datadog: {}", response.body())); } } catch (Throwable e) { @@ -239,8 +241,10 @@ String writeMetric(Meter.Id id, @Nullable String suffix, long wallTime, double v // Create host attribute String host = config.hostTag() == null ? "" - : stream(tags.spliterator(), false).filter(t -> config.hostTag().equals(t.getKey())).findAny() - .map(t -> ",\"host\":\"" + escapeJson(t.getValue()) + "\"").orElse(""); + : stream(tags.spliterator(), false).filter(t -> config.hostTag().equals(t.getKey())) + .findAny() + .map(t -> ",\"host\":\"" + escapeJson(t.getValue()) + "\"") + .orElse(""); // Create type attribute String type = ",\"type\":\"" + DatadogMetricMetadata.sanitizeType(statistic) + "\""; // Create unit attribute @@ -248,8 +252,8 @@ String writeMetric(Meter.Id id, @Nullable String suffix, long wallTime, double v String unit = baseUnit != null ? ",\"unit\":\"" + baseUnit + "\"" : ""; // Create tags attribute String tagsArray = tags.iterator().hasNext() ? stream(tags.spliterator(), false) - .map(t -> "\"" + escapeJson(t.getKey()) + ":" + escapeJson(t.getValue()) + "\"") - .collect(joining(",", ",\"tags\":[", "]")) : ""; + .map(t -> "\"" + escapeJson(t.getKey()) + ":" + escapeJson(t.getValue()) + "\"") + .collect(joining(",", ",\"tags\":[", "]")) : ""; return "{\"metric\":\"" + escapeJson(getConventionName(fullId)) + "\"," + "\"points\":[[" + (wallTime / 1000) + ", " + value + "]]" + host + type + unit + tagsArray + "}"; @@ -267,25 +271,27 @@ void postMetricMetadata(String metricName, DatadogMetricMetadata metadata) { try { httpClient - .put(config.uri() + "/api/v1/metrics/" + URLEncoder.encode(metricName, "UTF-8") + "?api_key=" - + config.apiKey() + "&application_key=" + config.applicationKey()) - .withJsonContent(metadata.editMetadataBody()).send() - .onSuccess(response -> verifiedMetadata.add(metricName)).onError(response -> { - if (logger.isErrorEnabled()) { - String msg = response.body(); - - // Ignore when the response content contains "metric_name not - // found". - // Metrics that are newly created in Datadog are not - // immediately available - // for metadata modification. We will keep trying this request - // on subsequent publishes, - // where it will eventually succeed. - if (!msg.contains("metric_name not found")) { - logger.error("failed to send metric metadata to datadog: {}", msg); - } + .put(config.uri() + "/api/v1/metrics/" + URLEncoder.encode(metricName, "UTF-8") + "?api_key=" + + config.apiKey() + "&application_key=" + config.applicationKey()) + .withJsonContent(metadata.editMetadataBody()) + .send() + .onSuccess(response -> verifiedMetadata.add(metricName)) + .onError(response -> { + if (logger.isErrorEnabled()) { + String msg = response.body(); + + // Ignore when the response content contains "metric_name not + // found". + // Metrics that are newly created in Datadog are not + // immediately available + // for metadata modification. We will keep trying this request + // on subsequent publishes, + // where it will eventually succeed. + if (!msg.contains("metric_name not found")) { + logger.error("failed to send metric metadata to datadog: {}", msg); } - }); + } + }); } catch (Throwable e) { logger.warn("failed to send metric metadata to datadog", e); diff --git a/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogConfigTest.java b/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogConfigTest.java index 544530bb56..18d5859abc 100644 --- a/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogConfigTest.java +++ b/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogConfigTest.java @@ -32,7 +32,7 @@ class DatadogConfigTest { @Test void invalid() { assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactly("is required"); + .containsExactly("is required"); } @Test diff --git a/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogMeterRegistryTest.java b/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogMeterRegistryTest.java index a2785c5906..6de8683aea 100644 --- a/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogMeterRegistryTest.java +++ b/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogMeterRegistryTest.java @@ -70,8 +70,11 @@ public boolean enabled() { server.stubFor(any(anyUrl())); - Counter.builder("my.counter#abc").baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase()) - .description("metric description").register(registry).increment(Math.PI); + Counter.builder("my.counter#abc") + .baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase()) + .description("metric description") + .register(registry) + .increment(Math.PI); registry.publish(); server.verify(postRequestedFor(urlEqualTo("/api/v1/series?api_key=fake")).withRequestBody(equalToJson( @@ -117,16 +120,19 @@ public boolean enabled() { server.stubFor(any(anyUrl())); - Counter.builder("my.counter#abc").baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase()) - .description("metric description").register(registry).increment(Math.PI); + Counter.builder("my.counter#abc") + .baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase()) + .description("metric description") + .register(registry) + .increment(Math.PI); registry.publish(); server.verify(postRequestedFor(urlEqualTo("/api/v1/series?api_key=fake")).withRequestBody(equalToJson( "{\"series\":[{\"metric\":\"my.counter#abc\",\"points\":[[0,0.0]],\"type\":\"count\",\"unit\":\"microsecond\",\"tags\":[\"statistic:count\"]}]}"))); server.verify(putRequestedFor(urlEqualTo("/api/v1/metrics/my.counter%23abc?api_key=fake&application_key=fake")) - .withRequestBody(equalToJson( - "{\"type\":\"count\",\"unit\":\"microsecond\",\"description\":\"metric description\"}"))); + .withRequestBody(equalToJson( + "{\"type\":\"count\",\"unit\":\"microsecond\",\"description\":\"metric description\"}"))); registry.close(); } diff --git a/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogMetricMetadataTest.java b/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogMetricMetadataTest.java index a6e113a538..c89ba53d20 100644 --- a/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogMetricMetadataTest.java +++ b/implementations/micrometer-registry-datadog/src/test/java/io/micrometer/datadog/DatadogMetricMetadataTest.java @@ -28,9 +28,11 @@ class DatadogMetricMetadataTest { @Test void escapesStringsInDescription() { - DatadogMetricMetadata metricMetadata = new DatadogMetricMetadata(Counter.builder("name").tag("key", "value") - .description("The /\"recent cpu usage\" for the Java Virtual Machine process") - .register(new SimpleMeterRegistry()).getId(), Statistic.COUNT, true, null); + DatadogMetricMetadata metricMetadata = new DatadogMetricMetadata(Counter.builder("name") + .tag("key", "value") + .description("The /\"recent cpu usage\" for the Java Virtual Machine process") + .register(new SimpleMeterRegistry()) + .getId(), Statistic.COUNT, true, null); assertThat(metricMetadata.editMetadataBody()).isEqualTo( "{\"type\":\"count\",\"description\":\"The /\\\"recent cpu usage\\\" for the Java Virtual Machine process\"}"); @@ -38,18 +40,21 @@ void escapesStringsInDescription() { @Test void unitsAreConverted() { - DatadogMetricMetadata metricMetadata = new DatadogMetricMetadata(Timer.builder("name").tag("key", "value") - .description("Time spent in GC pause").register(new DatadogMeterRegistry(new DatadogConfig() { - @Override - public String apiKey() { - return "fake"; - } - - @Override - public String get(String key) { - return null; - } - }, Clock.SYSTEM)).getId(), Statistic.TOTAL_TIME, false, null); + DatadogMetricMetadata metricMetadata = new DatadogMetricMetadata(Timer.builder("name") + .tag("key", "value") + .description("Time spent in GC pause") + .register(new DatadogMeterRegistry(new DatadogConfig() { + @Override + public String apiKey() { + return "fake"; + } + + @Override + public String get(String key) { + return null; + } + }, Clock.SYSTEM)) + .getId(), Statistic.TOTAL_TIME, false, null); assertThat(metricMetadata.editMetadataBody()).isNull(); } diff --git a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/DynatraceConfig.java b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/DynatraceConfig.java index ba94668807..c5fd8f58d6 100644 --- a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/DynatraceConfig.java +++ b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/DynatraceConfig.java @@ -148,7 +148,7 @@ default Validated validate() { checkRequired("uri", DynatraceConfig::uri), check("deviceId", DynatraceConfig::deviceId).andThen(Validated::nonBlank), check("technologyType", DynatraceConfig::technologyType) - .andThen(Validated::nonBlank)); + .andThen(Validated::nonBlank)); } else { return checkAll(this, checkRequired("uri", DynatraceConfig::uri)); diff --git a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/types/DynatraceDistributionSummary.java b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/types/DynatraceDistributionSummary.java index 5bdc337f49..cd6ddd3e4d 100644 --- a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/types/DynatraceDistributionSummary.java +++ b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/types/DynatraceDistributionSummary.java @@ -39,7 +39,10 @@ public final class DynatraceDistributionSummary extends AbstractDistributionSumm // Configuration that will set the Histogram in AbstractDistributionSummary to a // NoopHistogram. private static final DistributionStatisticConfig NOOP_HISTOGRAM_CONFIG = DistributionStatisticConfig.builder() - .percentilesHistogram(false).percentiles().serviceLevelObjectives().build(); + .percentilesHistogram(false) + .percentiles() + .serviceLevelObjectives() + .build(); private final DynatraceSummary summary = new DynatraceSummary(); diff --git a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/types/DynatraceTimer.java b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/types/DynatraceTimer.java index f3bd2cc151..92f6fa5ec5 100644 --- a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/types/DynatraceTimer.java +++ b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/types/DynatraceTimer.java @@ -38,7 +38,10 @@ public final class DynatraceTimer extends AbstractTimer implements DynatraceSumm // Configuration that will set the Histogram in AbstractTimer to a NoopHistogram. private static final DistributionStatisticConfig NOOP_HISTOGRAM_CONFIG = DistributionStatisticConfig.builder() - .percentilesHistogram(false).percentiles().serviceLevelObjectives().build(); + .percentilesHistogram(false) + .percentiles() + .serviceLevelObjectives() + .build(); private final DynatraceSummary summary = new DynatraceSummary(); diff --git a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v1/DynatraceExporterV1.java b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v1/DynatraceExporterV1.java index f3ad8dd334..da97e9ed16 100644 --- a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v1/DynatraceExporterV1.java +++ b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v1/DynatraceExporterV1.java @@ -84,19 +84,23 @@ public void export(List meters) { for (List batch : new MeterPartition(meters, config.batchSize())) { final List series = batch.stream() - .flatMap(meter -> meter.match(this::writeMeter, this::writeMeter, this::writeTimer, - this::writeSummary, this::writeLongTaskTimer, this::writeMeter, this::writeMeter, - this::writeFunctionTimer, this::writeMeter)) - .collect(Collectors.toList()); + .flatMap(meter -> meter.match(this::writeMeter, this::writeMeter, this::writeTimer, this::writeSummary, + this::writeLongTaskTimer, this::writeMeter, this::writeMeter, this::writeFunctionTimer, + this::writeMeter)) + .collect(Collectors.toList()); // TODO is there a way to batch submissions of multiple metrics? - series.stream().map(DynatraceCustomMetric::getMetricDefinition).filter(this::isCustomMetricNotCreated) - .forEach(this::putCustomMetric); + series.stream() + .map(DynatraceCustomMetric::getMetricDefinition) + .filter(this::isCustomMetricNotCreated) + .forEach(this::putCustomMetric); if (!createdCustomMetrics.isEmpty() && !series.isEmpty()) { postCustomMetricValues(config.technologyType(), config.group(), - series.stream().map(DynatraceCustomMetric::getTimeSeries).filter(this::isCustomMetricCreated) - .collect(Collectors.toList()), + series.stream() + .map(DynatraceCustomMetric::getTimeSeries) + .filter(this::isCustomMetricCreated) + .collect(Collectors.toList()), customDeviceMetricEndpoint); } } @@ -105,8 +109,10 @@ public void export(List meters) { // VisibleForTesting Stream writeMeter(Meter meter) { final long wallTime = clock.wallTime(); - return StreamSupport.stream(meter.measure().spliterator(), false).map(Measurement::getValue) - .filter(Double::isFinite).map(value -> createCustomMetric(meter.getId(), wallTime, value)); + return StreamSupport.stream(meter.measure().spliterator(), false) + .map(Measurement::getValue) + .filter(Double::isFinite) + .map(value -> createCustomMetric(meter.getId(), wallTime, value)); } private Stream writeLongTaskTimer(LongTaskTimer longTaskTimer) { @@ -193,9 +199,9 @@ void putCustomMetric(final DynatraceMetricDefinition customMetric) { HttpSender.Request.Builder requestBuilder; try { requestBuilder = httpClient.put(customMetricEndpointTemplate + customMetric.getMetricId()) - .withHeader(AUTHORIZATION_HEADER_KEY, - String.format(AUTHORIZATION_HEADER_VALUE_TEMPLATE, config.apiToken())) - .withJsonContent(customMetric.asJson()); + .withHeader(AUTHORIZATION_HEADER_KEY, + String.format(AUTHORIZATION_HEADER_VALUE_TEMPLATE, config.apiToken())) + .withJsonContent(customMetric.asJson()); } catch (Exception ex) { if (logger.isErrorEnabled()) { @@ -210,9 +216,10 @@ void putCustomMetric(final DynatraceMetricDefinition customMetric) { httpResponse.onSuccess(response -> { logger.debug("created {} as custom metric in Dynatrace", customMetric.getMetricId()); createdCustomMetrics.add(customMetric.getMetricId()); - }).onError(response -> logger.error( - "failed to create custom metric {} in Dynatrace: Error Code={}, Response Body={}", - customMetric.getMetricId(), response.code(), response.body())); + }) + .onError(response -> logger.error( + "failed to create custom metric {} in Dynatrace: Error Code={}, Response Body={}", + customMetric.getMetricId(), response.code(), response.body())); } } @@ -221,9 +228,10 @@ private void postCustomMetricValues(String type, String group, List UNITS_MAPPING = Collections - .unmodifiableMap(Stream.of(DynatraceUnit.values()) - .collect(Collectors.toMap(k -> k.toString().toLowerCase() + "s", Function.identity()))); + .unmodifiableMap(Stream.of(DynatraceUnit.values()) + .collect(Collectors.toMap(k -> k.toString().toLowerCase() + "s", Function.identity()))); @Nullable static DynatraceUnit fromPlural(@Nullable String plural) { diff --git a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v1/DynatraceTimeSeries.java b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v1/DynatraceTimeSeries.java index b87b5359ce..107abcdc41 100644 --- a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v1/DynatraceTimeSeries.java +++ b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v1/DynatraceTimeSeries.java @@ -49,9 +49,10 @@ String asJson() { + DoubleFormat.wholeOrDecimal(value) + "]]"; if (dimensions != null && !dimensions.isEmpty()) { - body += ",\"dimensions\":{" + dimensions.entrySet().stream() - .map(t -> "\"" + t.getKey() + "\":\"" + StringEscapeUtils.escapeJson(t.getValue()) + "\"") - .collect(Collectors.joining(",")) + "}"; + body += ",\"dimensions\":{" + dimensions.entrySet() + .stream() + .map(t -> "\"" + t.getKey() + "\":\"" + StringEscapeUtils.escapeJson(t.getValue()) + "\"") + .collect(Collectors.joining(",")) + "}"; } body += "}"; return body; diff --git a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v2/DynatraceExporterV2.java b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v2/DynatraceExporterV2.java index 8b6a928f8c..7ba3bd616d 100644 --- a/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v2/DynatraceExporterV2.java +++ b/implementations/micrometer-registry-dynatrace/src/main/java/io/micrometer/dynatrace/v2/DynatraceExporterV2.java @@ -82,8 +82,8 @@ public DynatraceExporterV2(DynatraceConfig config, Clock clock, HttpSender httpC logger.info("Exporting to endpoint {}", config.uri()); MetricBuilderFactory.MetricBuilderFactoryBuilder factoryBuilder = MetricBuilderFactory.builder() - .withPrefix(config.metricKeyPrefix()) - .withDefaultDimensions(parseDefaultDimensions(config.defaultDimensions())); + .withPrefix(config.metricKeyPrefix()) + .withDefaultDimensions(parseDefaultDimensions(config.defaultDimensions())); if (config.enrichWithDynatraceMetadata()) { factoryBuilder.withDynatraceMetadata(); @@ -109,9 +109,9 @@ private boolean shouldIgnoreToken(DynatraceConfig config) { return true; } if (config.uri().equals(DynatraceMetricApiConstants.getDefaultOneAgentEndpoint())) { - logger.warn( - "Potential misconfiguration detected: Token is provided, but the endpoint is set to the local OneAgent endpoint, " - + "thus the token will be ignored. If exporting to the cluster API endpoint is intended, its URI has to be provided explicitly."); + logger + .warn("Potential misconfiguration detected: Token is provided, but the endpoint is set to the local OneAgent endpoint, " + + "thus the token will be ignored. If exporting to the cluster API endpoint is intended, its URI has to be provided explicitly."); return true; } return false; @@ -119,8 +119,9 @@ private boolean shouldIgnoreToken(DynatraceConfig config) { private DimensionList parseDefaultDimensions(Map defaultDimensions) { List dimensions = Stream - .concat(defaultDimensions.entrySet().stream(), staticDimensions.entrySet().stream()) - .map(entry -> Dimension.create(entry.getKey(), entry.getValue())).collect(Collectors.toList()); + .concat(defaultDimensions.entrySet().stream(), staticDimensions.entrySet().stream()) + .map(entry -> Dimension.create(entry.getKey(), entry.getValue())) + .collect(Collectors.toList()); return DimensionList.fromCollection(dimensions); } @@ -203,7 +204,7 @@ Stream toTimerLine(Timer meter) { } DynatraceSummarySnapshot snapshot = ((DynatraceSummarySnapshotSupport) meter) - .takeSummarySnapshotAndReset(getBaseTimeUnit()); + .takeSummarySnapshotAndReset(getBaseTimeUnit()); if (snapshot.getCount() == 0) { return Stream.empty(); @@ -290,12 +291,13 @@ Stream toMeterLine(Meter meter) { private Stream toMeterLine(Meter meter, BiFunction measurementConverter) { return streamOf(meter.measure()).map(measurement -> measurementConverter.apply(meter, measurement)) - .filter(Objects::nonNull); + .filter(Objects::nonNull); } private Metric.Builder createMetricBuilder(Meter meter) { return metricBuilderFactory.newMetricBuilder(meter.getId().getName()) - .setDimensions(fromTags(meter.getId().getTags())).setTimestamp(Instant.ofEpochMilli(clock.wallTime())); + .setDimensions(fromTags(meter.getId().getTags())) + .setTimestamp(Instant.ofEpochMilli(clock.wallTime())); } private DimensionList fromTags(List tags) { @@ -324,10 +326,12 @@ private void send(List metricLines) { requestBuilder.withHeader("Authorization", "Api-Token " + config.apiToken()); } - requestBuilder.withHeader("User-Agent", "micrometer").withPlainText(body).send() - .onSuccess(response -> handleSuccess(metricLines.size(), response)) - .onError(response -> logger.error("Failed metric ingestion: Error Code={}, Response Body={}", - response.code(), getTruncatedBody(response))); + requestBuilder.withHeader("User-Agent", "micrometer") + .withPlainText(body) + .send() + .onSuccess(response -> handleSuccess(metricLines.size(), response)) + .onError(response -> logger.error("Failed metric ingestion: Error Code={}, Response Body={}", + response.code(), getTruncatedBody(response))); } catch (Throwable throwable) { logger.warn("Failed metric ingestion: " + throwable); diff --git a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceConfigTest.java b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceConfigTest.java index d48e4ea54a..63d1be0d1e 100644 --- a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceConfigTest.java +++ b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceConfigTest.java @@ -43,8 +43,8 @@ class DynatraceConfigTest { void setUp() { // Make sure that all tests use the default configuration, even if there's an // `endpoint.properties` file in place - DynatraceFileBasedConfigurationProvider.getInstance().forceOverwriteConfig(nonExistentConfigFileName, - Duration.ofMillis(50)); + DynatraceFileBasedConfigurationProvider.getInstance() + .forceOverwriteConfig(nonExistentConfigFileName, Duration.ofMillis(50)); } @Test @@ -117,7 +117,7 @@ public String uri() { assertThat(validate.failures()).hasSize(1); assertThat(validate.failures().stream().map(Validated::toString)) - .containsExactlyInAnyOrder("Invalid{property='dynatrace.uri', value='null', message='is required'}"); + .containsExactlyInAnyOrder("Invalid{property='dynatrace.uri', value='null', message='is required'}"); } @Test @@ -286,10 +286,11 @@ void testFileBasedConfig() throws IOException { final Path tempFile = Files.createTempFile(uuid, ".properties"); Files.write(tempFile, ("DT_METRICS_INGEST_URL = https://your-dynatrace-ingest-url/api/v2/metrics/ingest\n" - + "DT_METRICS_INGEST_API_TOKEN = YOUR.DYNATRACE.TOKEN").getBytes()); + + "DT_METRICS_INGEST_API_TOKEN = YOUR.DYNATRACE.TOKEN") + .getBytes()); - DynatraceFileBasedConfigurationProvider.getInstance().forceOverwriteConfig(tempFile.toString(), - Duration.ofMillis(50)); + DynatraceFileBasedConfigurationProvider.getInstance() + .forceOverwriteConfig(tempFile.toString(), Duration.ofMillis(50)); DynatraceConfig config = new DynatraceConfig() { @Override @@ -307,7 +308,8 @@ public DynatraceApiVersion apiVersion() { assertThat(config.uri()).isEqualTo("https://your-dynatrace-ingest-url/api/v2/metrics/ingest"); Files.write(tempFile, ("DT_METRICS_INGEST_URL = https://a-different-url/api/v2/metrics/ingest\n" - + "DT_METRICS_INGEST_API_TOKEN = A.DIFFERENT.TOKEN").getBytes()); + + "DT_METRICS_INGEST_API_TOKEN = A.DIFFERENT.TOKEN") + .getBytes()); await().atMost(1_000, MILLISECONDS).until(() -> config.apiToken().equals("A.DIFFERENT.TOKEN")); assertThat(config.uri()).isEqualTo("https://a-different-url/api/v2/metrics/ingest"); diff --git a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceMeterRegistryTest.java b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceMeterRegistryTest.java index d7d9eea8c2..5ece4fdca0 100644 --- a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceMeterRegistryTest.java +++ b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceMeterRegistryTest.java @@ -63,7 +63,7 @@ void shouldSendProperRequest() throws Throwable { HttpSender.Request.Builder builder = HttpSender.Request.build(config.uri(), httpClient); when(httpClient.post(config.uri())).thenReturn(builder); when(httpClient.send(isA(HttpSender.Request.class))) - .thenReturn(new HttpSender.Response(202, "{ \"linesOk\": 3, \"linesInvalid\": 0, \"error\": null }")); + .thenReturn(new HttpSender.Response(202, "{ \"linesOk\": 3, \"linesInvalid\": 0, \"error\": null }")); Double gauge = meterRegistry.gauge("my.gauge", 42d); Counter counter = meterRegistry.counter("my.counter"); @@ -83,11 +83,12 @@ void shouldSendProperRequest() throws Throwable { assertThat(request.getRequestHeaders()).containsOnly(entry("Content-Type", "text/plain"), entry("User-Agent", "micrometer"), entry("Authorization", "Api-Token apiToken")); - assertThat(request.getEntity()).asString().hasLineCount(3) - .contains("my.counter,dt.metrics.source=micrometer count,delta=12.0 " + clock.wallTime()) - .contains("my.gauge,dt.metrics.source=micrometer gauge," + gauge + " " + clock.wallTime()) - .contains("my.timer,dt.metrics.source=micrometer gauge,min=12.0,max=42.0,sum=108.0,count=4 " - + clock.wallTime()); + assertThat(request.getEntity()).asString() + .hasLineCount(3) + .contains("my.counter,dt.metrics.source=micrometer count,delta=12.0 " + clock.wallTime()) + .contains("my.gauge,dt.metrics.source=micrometer gauge," + gauge + " " + clock.wallTime()) + .contains("my.timer,dt.metrics.source=micrometer gauge,min=12.0,max=42.0,sum=108.0,count=4 " + + clock.wallTime()); } @Test @@ -95,7 +96,7 @@ void shouldResetBetweenRequests() throws Throwable { HttpSender.Request.Builder builder = HttpSender.Request.build(config.uri(), httpClient); when(httpClient.post(config.uri())).thenReturn(builder); when(httpClient.send(isA(HttpSender.Request.class))) - .thenReturn(new HttpSender.Response(202, "{ \"linesOk\": 1, \"linesInvalid\": 0, \"error\": null }")); + .thenReturn(new HttpSender.Response(202, "{ \"linesOk\": 1, \"linesInvalid\": 0, \"error\": null }")); Timer timer = Timer.builder("my.timer").register(meterRegistry); timer.record(22, MILLISECONDS); @@ -108,8 +109,10 @@ void shouldResetBetweenRequests() throws Throwable { verify(httpClient).send(argumentCaptor.capture()); HttpSender.Request request = argumentCaptor.getValue(); - assertThat(request.getEntity()).asString().hasLineCount(1).contains( - "my.timer,dt.metrics.source=micrometer gauge,min=22.0,max=50.0,sum=72.0,count=2 " + clock.wallTime()); + assertThat(request.getEntity()).asString() + .hasLineCount(1) + .contains("my.timer,dt.metrics.source=micrometer gauge,min=22.0,max=50.0,sum=72.0,count=2 " + + clock.wallTime()); // both are bigger than the previous min and smaller than the previous max. They // will only show up if the @@ -124,8 +127,10 @@ void shouldResetBetweenRequests() throws Throwable { verify(httpClient, times(2)).send(argumentCaptor2.capture()); HttpSender.Request request2 = argumentCaptor2.getValue(); - assertThat(request2.getEntity()).asString().hasLineCount(1).contains( - "my.timer,dt.metrics.source=micrometer gauge,min=33.0,max=44.0,sum=77.0,count=2 " + clock.wallTime()); + assertThat(request2.getEntity()).asString() + .hasLineCount(1) + .contains("my.timer,dt.metrics.source=micrometer gauge,min=33.0,max=44.0,sum=77.0,count=2 " + + clock.wallTime()); } @Test @@ -143,8 +148,10 @@ void shouldNotTrackPercentilesWithDynatraceSummary() throws Throwable { verify(httpClient).send(argumentCaptor.capture()); HttpSender.Request request = argumentCaptor.getValue(); - assertThat(request.getEntity()).asString().hasLineCount(1).contains( - "my.timer,dt.metrics.source=micrometer gauge,min=22.0,max=55.0,sum=77.0,count=2 " + clock.wallTime()); + assertThat(request.getEntity()).asString() + .hasLineCount(1) + .contains("my.timer,dt.metrics.source=micrometer gauge,min=22.0,max=55.0,sum=77.0,count=2 " + + clock.wallTime()); } @Test @@ -162,8 +169,10 @@ void shouldNotExportLinesWithZeroCount() throws Throwable { verify(httpClient).send(argumentCaptor.capture()); HttpSender.Request request = argumentCaptor.getValue(); - assertThat(request.getEntity()).asString().hasLineCount(1).contains( - "my.timer,dt.metrics.source=micrometer gauge,min=44.0,max=44.0,sum=44.0,count=1 " + clock.wallTime()); + assertThat(request.getEntity()).asString() + .hasLineCount(1) + .contains("my.timer,dt.metrics.source=micrometer gauge,min=44.0,max=44.0,sum=44.0,count=1 " + + clock.wallTime()); // reset for next export interval reset(httpClient); @@ -189,8 +198,10 @@ void shouldNotExportLinesWithZeroCount() throws Throwable { verify(httpClient).send(argumentCaptor2.capture()); HttpSender.Request request2 = argumentCaptor2.getValue(); - assertThat(request2.getEntity()).asString().hasLineCount(1).contains( - "my.timer,dt.metrics.source=micrometer gauge,min=33.0,max=33.0,sum=33.0,count=1 " + clock.wallTime()); + assertThat(request2.getEntity()).asString() + .hasLineCount(1) + .contains("my.timer,dt.metrics.source=micrometer gauge,min=33.0,max=33.0,sum=33.0,count=1 " + + clock.wallTime()); } private DynatraceConfig createDefaultDynatraceConfig() { diff --git a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceNamingConventionTest.java b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceNamingConventionTest.java index e131bdd9fe..7aa8dea74c 100644 --- a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceNamingConventionTest.java +++ b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/DynatraceNamingConventionTest.java @@ -34,15 +34,15 @@ class DynatraceNamingConventionTest { void testDelegate() { DynatraceNamingConventionV1 v1Convention = new DynatraceNamingConventionV1(); assertThat(dynatraceConvention.name("mymetric", Meter.Type.COUNTER, null)) - .isEqualTo(v1Convention.name("mymetric", Meter.Type.COUNTER, null)); + .isEqualTo(v1Convention.name("mymetric", Meter.Type.COUNTER, null)); assertThat(dynatraceConvention.name("my.name1", Meter.Type.COUNTER, null)) - .isEqualTo(v1Convention.name("my.name1", Meter.Type.COUNTER, null)); + .isEqualTo(v1Convention.name("my.name1", Meter.Type.COUNTER, null)); assertThat(dynatraceConvention.name("my_name1", Meter.Type.COUNTER, null)) - .isEqualTo(v1Convention.name("my_name1", Meter.Type.COUNTER, null)); + .isEqualTo(v1Convention.name("my_name1", Meter.Type.COUNTER, null)); assertThat(dynatraceConvention.name("my-name1", Meter.Type.COUNTER, null)) - .isEqualTo(v1Convention.name("my-name1", Meter.Type.COUNTER, null)); + .isEqualTo(v1Convention.name("my-name1", Meter.Type.COUNTER, null)); assertThat(dynatraceConvention.name("system.load.average.1m", Meter.Type.COUNTER, null)) - .isEqualTo(v1Convention.name("system.load.average.1m", Meter.Type.COUNTER, null)); + .isEqualTo(v1Convention.name("system.load.average.1m", Meter.Type.COUNTER, null)); assertThat(dynatraceConvention.tagKey("{tagTag0}.-")).isEqualTo(v1Convention.tagKey("_tagTag0_.-")); } diff --git a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceExporterV1Test.java b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceExporterV1Test.java index 23da3b44b6..758cc66d7d 100644 --- a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceExporterV1Test.java +++ b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceExporterV1Test.java @@ -67,8 +67,10 @@ class DynatraceExporterV1Test { private final DynatraceExporterV1 exporter = FACTORY.injectLogger(() -> createExporter(httpClient)); - private final DynatraceMeterRegistry meterRegistry = DynatraceMeterRegistry.builder(config).clock(clock) - .httpClient(httpClient).build(); + private final DynatraceMeterRegistry meterRegistry = DynatraceMeterRegistry.builder(config) + .clock(clock) + .httpClient(httpClient) + .build(); private final ObjectMapper mapper = new ObjectMapper(); @@ -250,7 +252,7 @@ void writeCustomMetrics() { Gauge gauge = meterRegistry.find("my.gauge").gauge(); Stream series = exporter.writeMeter(gauge); List timeSeries = series.map(DynatraceCustomMetric::getTimeSeries) - .collect(Collectors.toList()); + .collect(Collectors.toList()); List entries = exporter.createPostMessages("my.type", null, timeSeries); assertThat(entries).hasSize(1); assertThat(entries.get(0).metricCount).isEqualTo(1); @@ -343,8 +345,9 @@ void writeSummary() { clock.add(config.step()); - List metrics = exporter.writeSummary(summary).map((metric) -> metric.getTimeSeries().asJson()) - .collect(Collectors.toList()); + List metrics = exporter.writeSummary(summary) + .map((metric) -> metric.getTimeSeries().asJson()) + .collect(Collectors.toList()); assertThat(metrics).containsExactlyInAnyOrder( "{\"timeseriesId\":\"custom:my.distribution.summary.sum\",\"dataPoints\":[[60001,6]]}", @@ -387,12 +390,12 @@ void failOnPostShouldHaveProperLogging() throws Throwable { assertThat(LOGGER.getLogEvents()).hasSize(3); assertThat(LOGGER.getLogEvents().get(0).getLevel()).isSameAs(DEBUG); assertThat(LOGGER.getLogEvents().get(0).getMessage()) - .isEqualTo("created custom:my.gauge as custom metric in Dynatrace"); + .isEqualTo("created custom:my.gauge as custom metric in Dynatrace"); assertThat(LOGGER.getLogEvents().get(0).getCause()).isNull(); assertThat(LOGGER.getLogEvents().get(1).getLevel()).isSameAs(ERROR); assertThat(LOGGER.getLogEvents().get(1).getMessage()) - .isEqualTo("failed to send metrics to Dynatrace: Error Code=500, Response Body=simulated"); + .isEqualTo("failed to send metrics to Dynatrace: Error Code=500, Response Body=simulated"); assertThat(LOGGER.getLogEvents().get(1).getCause()).isNull(); } @@ -411,12 +414,13 @@ void testTokenShouldNotShowUpInPutFailureErrorMessage() { exporter.export(Collections.singletonList(gauge)); assertThat(LOGGER.getLogEvents()) - // map to only keep the message strings - .extracting(LogEvent::getMessage).containsExactly("failed to build request") - // this is different from doesNotContain, as doesNotContain checks for - // whole strings in all log messages whereas this checks that none of the - // log messages contain the token. - .noneMatch(x -> x.contains(apiToken)); + // map to only keep the message strings + .extracting(LogEvent::getMessage) + .containsExactly("failed to build request") + // this is different from doesNotContain, as doesNotContain checks for + // whole strings in all log messages whereas this checks that none of the + // log messages contain the token. + .noneMatch(x -> x.contains(apiToken)); } @Test @@ -439,13 +443,14 @@ void testTokenShouldNotShowUpInPostFailureErrorMessage() throws Throwable { exporter.export(Collections.singletonList(gauge)); assertThat(LOGGER.getLogEvents()) - // map to only keep the message strings - .extracting(LogEvent::getMessage).containsExactly( - // the custom metric was created, meaning the PUT call succeeded - "created custom:my.gauge as custom metric in Dynatrace", - // the error message from the post call contains no token - "failed to build request") - .noneMatch(x -> x.contains(apiToken)); + // map to only keep the message strings + .extracting(LogEvent::getMessage) + .containsExactly( + // the custom metric was created, meaning the PUT call succeeded + "created custom:my.gauge as custom metric in Dynatrace", + // the error message from the post call contains no token + "failed to build request") + .noneMatch(x -> x.contains(apiToken)); } @Test @@ -489,13 +494,15 @@ void trySendHttpRequestThrows() throws Throwable { // Simulate that sending throws an exception AND adds the token to the message, // which shouldn't happen. when(reqBuilder.send()) - .thenThrow(new NullPointerException(String.format("Header key is null for value %s", apiToken))); + .thenThrow(new NullPointerException(String.format("Header key is null for value %s", apiToken))); exporter.trySendHttpRequest(reqBuilder); verify(reqBuilder).send(); // assert that an error is logged that does not contain the token. - assertThat(LOGGER.getLogEvents()).hasSize(1).extracting(LogEvent::getMessage) - .containsExactly("failed to send metrics to Dynatrace").noneMatch(x -> x.contains(apiToken)); + assertThat(LOGGER.getLogEvents()).hasSize(1) + .extracting(LogEvent::getMessage) + .containsExactly("failed to send metrics to Dynatrace") + .noneMatch(x -> x.contains(apiToken)); } private DynatraceExporterV1 getDynatraceExporterV1(HttpSender httpClient, String url, String apiToken) { diff --git a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceMetricDefinitionTest.java b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceMetricDefinitionTest.java index 5b31a91b80..1b25c02a34 100644 --- a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceMetricDefinitionTest.java +++ b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceMetricDefinitionTest.java @@ -49,7 +49,7 @@ void addsUnitWhenAvailable() { DynatraceMetricDefinition.DynatraceUnit.Count, null, technologyTypes, null); assertThat(metric.asJson()) - .isEqualTo("{\"displayName\":\"my test metric\",\"unit\":\"Count\",\"types\":[\"java\"]}"); + .isEqualTo("{\"displayName\":\"my test metric\",\"unit\":\"Count\",\"types\":[\"java\"]}"); } @Test diff --git a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceNamingConventionV1Test.java b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceNamingConventionV1Test.java index 983de74c58..2458c5c5ca 100644 --- a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceNamingConventionV1Test.java +++ b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v1/DynatraceNamingConventionV1Test.java @@ -54,7 +54,7 @@ void nameShouldSanitize() { @Test void nameWithSystemLoadAverageOneMintueShouldSanitize() { assertThat(convention.name("system.load.average.1m", Meter.Type.COUNTER, null)) - .isEqualTo("custom:system.load.average.oneminute"); + .isEqualTo("custom:system.load.average.oneminute"); } @Test diff --git a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v2/DynatraceExporterV2Test.java b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v2/DynatraceExporterV2Test.java index c8738a5912..1cf83c8f1a 100644 --- a/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v2/DynatraceExporterV2Test.java +++ b/implementations/micrometer-registry-dynatrace/src/test/java/io/micrometer/dynatrace/v2/DynatraceExporterV2Test.java @@ -163,7 +163,7 @@ void toCounterLine() { List lines = exporter.toCounterLine(counter).collect(Collectors.toList()); assertThat(lines).hasSize(1); assertThat(lines.get(0)) - .isEqualTo("my.counter,dt.metrics.source=micrometer count,delta=3.0 " + clock.wallTime()); + .isEqualTo("my.counter,dt.metrics.source=micrometer count,delta=3.0 " + clock.wallTime()); } @Test @@ -197,7 +197,7 @@ void toFunctionCounterLine() { List lines = exporter.toFunctionCounterLine(functionCounter).collect(Collectors.toList()); assertThat(lines).hasSize(1); assertThat(lines.get(0)) - .isEqualTo("my.functionCounter,dt.metrics.source=micrometer count,delta=2.3 " + clock.wallTime()); + .isEqualTo("my.functionCounter,dt.metrics.source=micrometer count,delta=2.3 " + clock.wallTime()); } @Test @@ -323,8 +323,8 @@ public Id getId() { List lines = exporter.toFunctionTimerLine(functionTimer).collect(Collectors.toList()); assertThat(lines).hasSize(1); assertThat(lines.get(0)) - .isEqualTo("my.functionTimer,dt.metrics.source=micrometer gauge,min=10.0,max=10.0,sum=5000.0,count=500 " - + clock.wallTime()); + .isEqualTo("my.functionTimer,dt.metrics.source=micrometer gauge,min=10.0,max=10.0,sum=5000.0,count=500 " + + clock.wallTime()); } @Test @@ -408,8 +408,8 @@ void toGaugeLineShouldContainTags() { List lines = exporter.toGaugeLine(gauge).collect(Collectors.toList()); assertThat(lines).hasSize(1); - assertThat(lines.get(0)).isEqualTo( - "my.gauge,tag1=value1,dt.metrics.source=micrometer,tag2=value2 gauge,1.23 " + clock.wallTime()); + assertThat(lines.get(0)) + .isEqualTo("my.gauge,tag1=value1,dt.metrics.source=micrometer,tag2=value2 gauge,1.23 " + clock.wallTime()); } @Test @@ -421,7 +421,7 @@ void toGaugeLineShouldExportBlankTagValues() { List lines = exporter.toGaugeLine(gauge).collect(Collectors.toList()); assertThat(lines).hasSize(1); assertThat(lines.get(0)) - .isEqualTo("my.gauge,tag1=value1,dt.metrics.source=micrometer,tag2= gauge,1.23 " + clock.wallTime()); + .isEqualTo("my.gauge,tag1=value1,dt.metrics.source=micrometer,tag2= gauge,1.23 " + clock.wallTime()); } @Test @@ -452,8 +452,8 @@ void toCounterLineShouldExportBlankTagValues() { List lines = exporter.toCounterLine(counter).collect(Collectors.toList()); assertThat(lines).hasSize(1); - assertThat(lines.get(0)).isEqualTo( - "my.counter,tag1=value1,dt.metrics.source=micrometer,tag2= count,delta=0.0 " + clock.wallTime()); + assertThat(lines.get(0)) + .isEqualTo("my.counter,tag1=value1,dt.metrics.source=micrometer,tag2= count,delta=0.0 " + clock.wallTime()); } @Test @@ -476,7 +476,7 @@ void shouldSendHeadersAndBody() throws Throwable { HttpSender.Request.Builder builder = HttpSender.Request.build(config.uri(), httpClient); when(httpClient.post(config.uri())).thenReturn(builder); when(httpClient.send(isA(HttpSender.Request.class))) - .thenReturn(new HttpSender.Response(202, "{ \"linesOk\": 3, \"linesInvalid\": 0, \"error\": null }")); + .thenReturn(new HttpSender.Response(202, "{ \"linesOk\": 3, \"linesInvalid\": 0, \"error\": null }")); Counter counter = meterRegistry.counter("my.counter"); counter.increment(12d); @@ -494,11 +494,12 @@ void shouldSendHeadersAndBody() throws Throwable { assertThat(request.getRequestHeaders()).containsOnly(entry("Content-Type", "text/plain"), entry("User-Agent", "micrometer"), entry("Authorization", "Api-Token apiToken")); - assertThat(request.getEntity()).asString().hasLineCount(3) - .contains("my.counter,dt.metrics.source=micrometer count,delta=12.0 " + clock.wallTime()) - .contains("my.gauge,dt.metrics.source=micrometer gauge,42.0 " + clock.wallTime()) - .contains("my.timer,dt.metrics.source=micrometer gauge,min=22.0,max=22.0,sum=22.0,count=1 " - + clock.wallTime()); + assertThat(request.getEntity()).asString() + .hasLineCount(3) + .contains("my.counter,dt.metrics.source=micrometer count,delta=12.0 " + clock.wallTime()) + .contains("my.gauge,dt.metrics.source=micrometer gauge,42.0 " + clock.wallTime()) + .contains("my.timer,dt.metrics.source=micrometer gauge,min=22.0,max=22.0,sum=22.0,count=1 " + + clock.wallTime()); } @Test @@ -511,8 +512,8 @@ void failOnSendShouldHaveProperLogging() throws Throwable { Gauge gauge = meterRegistry.find("my.gauge").gauge(); exporter.export(Collections.singletonList(gauge)); - assertThat(LOGGER.getLogEvents()).contains( - new LogEvent(ERROR, "Failed metric ingestion: Error Code=500, Response Body=simulated", null)); + assertThat(LOGGER.getLogEvents()) + .contains(new LogEvent(ERROR, "Failed metric ingestion: Error Code=500, Response Body=simulated", null)); } @Test @@ -538,8 +539,10 @@ public String get(String key) { HttpSender httpSender = mock(HttpSender.class); MockClock clock = new MockClock(); DynatraceExporterV2 exporter = new DynatraceExporterV2(config, clock, httpSender); - DynatraceMeterRegistry meterRegistry = DynatraceMeterRegistry.builder(config).httpClient(httpSender) - .clock(clock).build(); + DynatraceMeterRegistry meterRegistry = DynatraceMeterRegistry.builder(config) + .httpClient(httpSender) + .clock(clock) + .build(); when(httpSender.post(anyString())).thenCallRealMethod(); when(httpSender.newRequest(anyString())).thenCallRealMethod(); @@ -552,10 +555,11 @@ public String get(String key) { final String secondUri = baseUri + "second"; Files.write(tempFile, ("DT_METRICS_INGEST_URL = " + firstUri + "\n" - + "DT_METRICS_INGEST_API_TOKEN = YOUR.DYNATRACE.TOKEN.FIRST").getBytes()); + + "DT_METRICS_INGEST_API_TOKEN = YOUR.DYNATRACE.TOKEN.FIRST") + .getBytes()); - DynatraceFileBasedConfigurationProvider.getInstance().forceOverwriteConfig(tempFile.toString(), - Duration.ofMillis(50)); + DynatraceFileBasedConfigurationProvider.getInstance() + .forceOverwriteConfig(tempFile.toString(), Duration.ofMillis(50)); await().atMost(1_000, MILLISECONDS).until(() -> config.uri().equals(firstUri)); Counter counter = meterRegistry.counter("test.counter"); counter.increment(10); @@ -577,7 +581,8 @@ public String get(String key) { // overwrite the file content to use the second uri Files.write(tempFile, ("DT_METRICS_INGEST_URL = " + secondUri + "\n" - + "DT_METRICS_INGEST_API_TOKEN = YOUR.DYNATRACE.TOKEN.SECOND").getBytes()); + + "DT_METRICS_INGEST_API_TOKEN = YOUR.DYNATRACE.TOKEN.SECOND") + .getBytes()); await().atMost(1_000, MILLISECONDS).until(() -> config.uri().equals(secondUri)); exporter.export(Collections.singletonList(counter)); diff --git a/implementations/micrometer-registry-elastic/src/main/java/io/micrometer/elastic/ElasticConfig.java b/implementations/micrometer-registry-elastic/src/main/java/io/micrometer/elastic/ElasticConfig.java index 6986fd3189..1d9dedb608 100644 --- a/implementations/micrometer-registry-elastic/src/main/java/io/micrometer/elastic/ElasticConfig.java +++ b/implementations/micrometer-registry-elastic/src/main/java/io/micrometer/elastic/ElasticConfig.java @@ -184,19 +184,19 @@ default Validated validate() { checkRequired("index", ElasticConfig::index), checkRequired("timestampFieldName", ElasticConfig::timestampFieldName), checkRequired("indexDateFormat", ElasticConfig::indexDateFormat) - .andThen(v -> v.invalidateWhen(format -> { - if (format == null) { - return true; - } - - try { - DateTimeFormatter.ofPattern(format); - return false; - } - catch (IllegalArgumentException ignored) { - return true; - } - }, "invalid date format", InvalidReason.MALFORMED)), + .andThen(v -> v.invalidateWhen(format -> { + if (format == null) { + return true; + } + + try { + DateTimeFormatter.ofPattern(format); + return false; + } + catch (IllegalArgumentException ignored) { + return true; + } + }, "invalid date format", InvalidReason.MALFORMED)), checkRequired("indexDateSeparator", ElasticConfig::indexDateSeparator), checkRequired("documentType", ElasticConfig::documentType)); } diff --git a/implementations/micrometer-registry-elastic/src/main/java/io/micrometer/elastic/ElasticMeterRegistry.java b/implementations/micrometer-registry-elastic/src/main/java/io/micrometer/elastic/ElasticMeterRegistry.java index 42d31d8992..b0bbd3f663 100644 --- a/implementations/micrometer-registry-elastic/src/main/java/io/micrometer/elastic/ElasticMeterRegistry.java +++ b/implementations/micrometer-registry-elastic/src/main/java/io/micrometer/elastic/ElasticMeterRegistry.java @@ -147,8 +147,9 @@ private void createIndexTemplateIfNeeded() { return; } - connect(HttpSender.Method.PUT, uri).withJsonContent(getTemplateBody()).send().onError( - response -> logger.error("failed to add metrics template to elastic: {}", response.body())); + connect(HttpSender.Method.PUT, uri).withJsonContent(getTemplateBody()) + .send() + .onError(response -> logger.error("failed to add metrics template to elastic: {}", response.body())); } catch (Throwable e) { logger.error("could not create index in elastic", e); @@ -183,10 +184,12 @@ protected void publish() { for (List batch : MeterPartition.partition(this, config.batchSize())) { try { String requestBody = batch.stream() - .map(m -> m.match(this::writeGauge, this::writeCounter, this::writeTimer, this::writeSummary, - this::writeLongTaskTimer, this::writeTimeGauge, this::writeFunctionCounter, - this::writeFunctionTimer, this::writeMeter)) - .filter(Optional::isPresent).map(Optional::get).collect(joining("\n", "", "\n")); + .map(m -> m.match(this::writeGauge, this::writeCounter, this::writeTimer, this::writeSummary, + this::writeLongTaskTimer, this::writeTimeGauge, this::writeFunctionCounter, + this::writeFunctionTimer, this::writeMeter)) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(joining("\n", "", "\n")); connect(HttpSender.Method.POST, uri).withJsonContent(requestBody).send().onSuccess(response -> { int numberOfSentItems = batch.size(); String responseBody = response.body(); @@ -363,14 +366,25 @@ String writeDocument(Meter meter, Consumer consumer) { String timestamp = generateTimestamp(); String name = getConventionName(meter.getId()); String type = meter.getId().getType().toString().toLowerCase(); - sb.append("{\"").append(config.timestampFieldName()).append("\":\"").append(timestamp).append('"') - .append(",\"name\":\"").append(escapeJson(name)).append('"').append(",\"type\":\"").append(type) - .append('"'); + sb.append("{\"") + .append(config.timestampFieldName()) + .append("\":\"") + .append(timestamp) + .append('"') + .append(",\"name\":\"") + .append(escapeJson(name)) + .append('"') + .append(",\"type\":\"") + .append(type) + .append('"'); List tags = getConventionTags(meter.getId()); for (Tag tag : tags) { - sb.append(",\"").append(escapeJson(tag.getKey())).append("\":\"").append(escapeJson(tag.getValue())) - .append('"'); + sb.append(",\"") + .append(escapeJson(tag.getKey())) + .append("\":\"") + .append(escapeJson(tag.getValue())) + .append('"'); } consumer.accept(sb); diff --git a/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/AbstractElasticsearchApiKeyIntegrationTest.java b/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/AbstractElasticsearchApiKeyIntegrationTest.java index f7cae90fe7..75bee1f6bb 100644 --- a/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/AbstractElasticsearchApiKeyIntegrationTest.java +++ b/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/AbstractElasticsearchApiKeyIntegrationTest.java @@ -37,13 +37,14 @@ protected ElasticConfig getConfig() { // Create API key try { HttpSender.Response response = httpSender.post(host + "/_security/api_key") - .withBasicAuthentication(USER, PASSWORD) - .withJsonContent("{\"name\": \"my-api-key\",\"expiration\": \"1h\"}").send(); + .withBasicAuthentication(USER, PASSWORD) + .withJsonContent("{\"name\": \"my-api-key\",\"expiration\": \"1h\"}") + .send(); String body = response.body(); String id = JsonPath.parse(body).read("$.id"); String apiKey = JsonPath.parse(body).read("$.api_key"); apiKeyCredentials = Base64.getEncoder() - .encodeToString((id + ":" + apiKey).getBytes(StandardCharsets.UTF_8)); + .encodeToString((id + ":" + apiKey).getBytes(StandardCharsets.UTF_8)); } catch (Throwable e) { throw new RuntimeException(e); diff --git a/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/AbstractElasticsearchMeterRegistryIntegrationTest.java b/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/AbstractElasticsearchMeterRegistryIntegrationTest.java index fe5062f94b..1da3653cfe 100644 --- a/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/AbstractElasticsearchMeterRegistryIntegrationTest.java +++ b/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/AbstractElasticsearchMeterRegistryIntegrationTest.java @@ -88,7 +88,7 @@ protected String getCountTypePath(String indexName) { protected ElasticsearchContainer getContainer() { return new ElasticsearchContainer(DockerImageName.parse(getDockerImageName(getVersion()))) - .withPassword(PASSWORD); + .withPassword(PASSWORD); } protected ElasticConfig getConfig() { diff --git a/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/ElasticConfigTest.java b/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/ElasticConfigTest.java index 2f10fa8c59..06ae1c8f3e 100644 --- a/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/ElasticConfigTest.java +++ b/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/ElasticConfigTest.java @@ -35,7 +35,7 @@ void invalid() { props.put("elastic.indexDateFormat", "invalid"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactlyInAnyOrder("must be a valid URL", "invalid date format"); + .containsExactlyInAnyOrder("must be a valid URL", "invalid date format"); } @Test @@ -53,7 +53,7 @@ public String get(String key) { }.validate(); assertThat(validate.failures().stream().map(Validated.Invalid::getMessage)) - .containsExactly("invalid date format"); + .containsExactly("invalid date format"); } @Test diff --git a/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/ElasticMeterRegistryTest.java b/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/ElasticMeterRegistryTest.java index 3ff51f7422..88a53a4158 100644 --- a/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/ElasticMeterRegistryTest.java +++ b/implementations/micrometer-registry-elastic/src/test/java/io/micrometer/elastic/ElasticMeterRegistryTest.java @@ -45,7 +45,7 @@ class ElasticMeterRegistryTest { @Test void timestampFormat() { assertThat(ElasticMeterRegistry.TIMESTAMP_FORMATTER.format(Instant.ofEpochMilli(1))) - .contains("1970-01-01T00:00:00.001Z"); + .contains("1970-01-01T00:00:00.001Z"); } @Test @@ -75,7 +75,7 @@ void writeFunctionCounter() { @Test void nanFunctionCounterShouldNotBeWritten() { FunctionCounter counter = FunctionCounter.builder("myCounter", Double.NaN, Number::doubleValue) - .register(registry); + .register(registry); clock.add(config.step()); assertThat(registry.writeFunctionCounter(counter)).isEmpty(); } @@ -83,8 +83,8 @@ void nanFunctionCounterShouldNotBeWritten() { @Test void nanFunctionTimerShouldNotBeWritten() { FunctionTimer timer = FunctionTimer - .builder("myFunctionTimer", Double.NaN, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) - .register(registry); + .builder("myFunctionTimer", Double.NaN, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) + .register(registry); clock.add(config.step()); assertThat(registry.writeFunctionTimer(timer)).isEmpty(); } @@ -99,7 +99,7 @@ void writeGauge() { @Test void writeTimeGauge() { TimeGauge gauge = TimeGauge.builder("myGauge", 123.0, TimeUnit.MILLISECONDS, Number::doubleValue) - .register(registry); + .register(registry); assertThat(registry.writeTimeGauge(gauge)).contains( "{ \"create\" : {} }\n{\"@timestamp\":\"1970-01-01T00:00:00.001Z\",\"name\":\"myGauge\",\"type\":\"gauge\",\"value\":123.0}"); } @@ -192,8 +192,8 @@ void infinityGaugeShouldNotBeWritten() { @Test void infinityTimeGaugeShouldNotBeWritten() { TimeGauge gauge = TimeGauge - .builder("myGauge", Double.NEGATIVE_INFINITY, TimeUnit.MILLISECONDS, Number::doubleValue) - .register(registry); + .builder("myGauge", Double.NEGATIVE_INFINITY, TimeUnit.MILLISECONDS, Number::doubleValue) + .register(registry); assertThat(registry.writeTimeGauge(gauge)).isNotPresent(); } diff --git a/implementations/micrometer-registry-ganglia/src/main/java/io/micrometer/ganglia/GangliaConfig.java b/implementations/micrometer-registry-ganglia/src/main/java/io/micrometer/ganglia/GangliaConfig.java index fc887550eb..645c900cae 100644 --- a/implementations/micrometer-registry-ganglia/src/main/java/io/micrometer/ganglia/GangliaConfig.java +++ b/implementations/micrometer-registry-ganglia/src/main/java/io/micrometer/ganglia/GangliaConfig.java @@ -80,7 +80,7 @@ default String protocolVersion() { default GMetric.UDPAddressingMode addressingMode() { return getEnum(this, GMetric.UDPAddressingMode.class, "addressingMode") - .orElse(GMetric.UDPAddressingMode.MULTICAST); + .orElse(GMetric.UDPAddressingMode.MULTICAST); } default int ttl() { diff --git a/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteDimensionalNameMapper.java b/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteDimensionalNameMapper.java index 3adfe53f78..6755dd34d6 100644 --- a/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteDimensionalNameMapper.java +++ b/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteDimensionalNameMapper.java @@ -39,8 +39,10 @@ public String toHierarchicalName(Meter.Id id, NamingConvention convention) { StringBuilder hierarchicalName = new StringBuilder(); hierarchicalName.append(id.getConventionName(convention)); for (Tag tag : id.getTagsAsIterable()) { - hierarchicalName.append(';').append(convention.tagKey(tag.getKey())).append('=') - .append(convention.tagValue(tag.getValue())); + hierarchicalName.append(';') + .append(convention.tagKey(tag.getKey())) + .append('=') + .append(convention.tagValue(tag.getValue())); } return hierarchicalName.toString(); } diff --git a/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteHierarchicalNameMapper.java b/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteHierarchicalNameMapper.java index e93d69c4f8..6e96d4719b 100644 --- a/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteHierarchicalNameMapper.java +++ b/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteHierarchicalNameMapper.java @@ -50,8 +50,10 @@ public String toHierarchicalName(Meter.Id id, NamingConvention convention) { hierarchicalName.append(id.getConventionName(convention)); for (Tag tag : id.getTagsAsIterable()) { if (!tagsAsPrefix.contains(tag.getKey())) { - hierarchicalName.append('.').append(convention.tagKey(tag.getKey())).append('.') - .append(convention.tagValue(tag.getValue())); + hierarchicalName.append('.') + .append(convention.tagKey(tag.getKey())) + .append('.') + .append(convention.tagValue(tag.getValue())); } } return hierarchicalName.toString(); diff --git a/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteMeterRegistry.java b/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteMeterRegistry.java index 74f188d9b0..1f2f4842d8 100644 --- a/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteMeterRegistry.java +++ b/implementations/micrometer-registry-graphite/src/main/java/io/micrometer/graphite/GraphiteMeterRegistry.java @@ -59,9 +59,12 @@ public GraphiteMeterRegistry(GraphiteConfig config, Clock clock, HierarchicalNam private static GraphiteReporter defaultGraphiteReporter(GraphiteConfig config, Clock clock, MetricRegistry metricRegistry) { - return GraphiteReporter.forRegistry(metricRegistry).withClock(new DropwizardClock(clock)) - .convertRatesTo(config.rateUnits()).convertDurationsTo(config.durationUnits()) - .addMetricAttributesAsTags(config.graphiteTagsEnabled()).build(getGraphiteSender(config)); + return GraphiteReporter.forRegistry(metricRegistry) + .withClock(new DropwizardClock(clock)) + .convertRatesTo(config.rateUnits()) + .convertDurationsTo(config.durationUnits()) + .addMetricAttributesAsTags(config.graphiteTagsEnabled()) + .build(getGraphiteSender(config)); } private static GraphiteSender getGraphiteSender(GraphiteConfig config) { diff --git a/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteConfigTest.java b/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteConfigTest.java index 160f3c7f32..74fc70dc07 100644 --- a/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteConfigTest.java +++ b/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteConfigTest.java @@ -35,7 +35,7 @@ void invalid() { props.put("graphite.durationUnits", "bad duration"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsOnly("must contain a valid time unit"); + .containsOnly("must contain a valid time unit"); } @Test diff --git a/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteHierarchicalNameMapperTest.java b/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteHierarchicalNameMapperTest.java index a82bf40468..0bfe68107d 100644 --- a/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteHierarchicalNameMapperTest.java +++ b/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteHierarchicalNameMapperTest.java @@ -34,21 +34,23 @@ class GraphiteHierarchicalNameMapperTest { private final GraphiteHierarchicalNameMapper nameMapper = new GraphiteHierarchicalNameMapper("stack", "app.name"); private final Meter.Id id = new SimpleMeterRegistry() - .counter("my.name", "app.name", "MYAPP", "stack", "PROD", "other.tag", "value").getId(); + .counter("my.name", "app.name", "MYAPP", "stack", "PROD", "other.tag", "value") + .getId(); @Issue("#561") @Test void tagsAsPrefix() { assertThat(nameMapper.toHierarchicalName(id, NamingConvention.camelCase)) - .isEqualTo("PROD.MYAPP.myName.otherTag.value"); + .isEqualTo("PROD.MYAPP.myName.otherTag.value"); } @Test void toHierarchicalNameShouldSanitizeTagValueFromTagsAsPrefix() { Meter.Id id = new SimpleMeterRegistry() - .counter("my.name", "app.name", "MY APP", "stack", "PROD", "other.tag", "value").getId(); + .counter("my.name", "app.name", "MY APP", "stack", "PROD", "other.tag", "value") + .getId(); assertThat(nameMapper.toHierarchicalName(id, new GraphiteHierarchicalNamingConvention())) - .isEqualTo("PROD.MY_APP.myName.otherTag.value"); + .isEqualTo("PROD.MY_APP.myName.otherTag.value"); } } diff --git a/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteMeterRegistryTest.java b/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteMeterRegistryTest.java index 5d54c9f41c..c43dc23bdd 100644 --- a/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteMeterRegistryTest.java +++ b/implementations/micrometer-registry-graphite/src/test/java/io/micrometer/graphite/GraphiteMeterRegistryTest.java @@ -91,17 +91,23 @@ public String[] tagsAsPrefix() { } }, mockClock); - Connection server = UdpServer.create().option(ChannelOption.SO_REUSEADDR, true).host("localhost").port(PORT) - .handle((in, out) -> { - in.receive().asString().subscribe(line -> { - assertThat(line).startsWith("APPNAME.myTimer"); - receiveLatch.countDown(); - }); - return Flux.never(); - }).bind().doOnSuccess(v -> { - registry.timer("my.timer", "application", "APPNAME").record(1, TimeUnit.MILLISECONDS); - registry.close(); - }).block(Duration.ofSeconds(10)); + Connection server = UdpServer.create() + .option(ChannelOption.SO_REUSEADDR, true) + .host("localhost") + .port(PORT) + .handle((in, out) -> { + in.receive().asString().subscribe(line -> { + assertThat(line).startsWith("APPNAME.myTimer"); + receiveLatch.countDown(); + }); + return Flux.never(); + }) + .bind() + .doOnSuccess(v -> { + registry.timer("my.timer", "application", "APPNAME").record(1, TimeUnit.MILLISECONDS); + registry.close(); + }) + .block(Duration.ofSeconds(10)); assertTrue(receiveLatch.await(10, TimeUnit.SECONDS), "line was received"); server.dispose(); @@ -152,17 +158,23 @@ public String[] tagsAsPrefix() { } }, mockClock); - Connection server = UdpServer.create().option(ChannelOption.SO_REUSEADDR, true).host("localhost").port(PORT) - .handle((in, out) -> { - in.receive().asString().subscribe(line -> { - assertThat(line).startsWith("my.timer;key=value;metricattribute=max "); - receiveLatch.countDown(); - }); - return Flux.never(); - }).bind().doOnSuccess(v -> { - registry.timer("my.timer", "key", "value").record(1, TimeUnit.MILLISECONDS); - registry.close(); - }).block(Duration.ofSeconds(10)); + Connection server = UdpServer.create() + .option(ChannelOption.SO_REUSEADDR, true) + .host("localhost") + .port(PORT) + .handle((in, out) -> { + in.receive().asString().subscribe(line -> { + assertThat(line).startsWith("my.timer;key=value;metricattribute=max "); + receiveLatch.countDown(); + }); + return Flux.never(); + }) + .bind() + .doOnSuccess(v -> { + registry.timer("my.timer", "key", "value").record(1, TimeUnit.MILLISECONDS); + registry.close(); + }) + .block(Duration.ofSeconds(10)); assertTrue(receiveLatch.await(10, TimeUnit.SECONDS), "line was received"); server.dispose(); diff --git a/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/HealthMeterRegistry.java b/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/HealthMeterRegistry.java index 49d2d44faf..867d1d18cc 100644 --- a/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/HealthMeterRegistry.java +++ b/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/HealthMeterRegistry.java @@ -168,12 +168,14 @@ void tick() { } public Collection getServiceLevelObjectives() { - return serviceLevelObjectives.stream().filter(slo -> accept(slo.getId())) - .map(slo -> serviceLevelObjectiveFilters.stream().reduce(slo, + return serviceLevelObjectives.stream() + .filter(slo -> accept(slo.getId())) + .map(slo -> serviceLevelObjectiveFilters.stream() + .reduce(slo, (filtered, filter) -> new ServiceLevelObjective.FilteredServiceLevelObjective( filter.map(filtered.getId()), filtered), (obj1, obj2) -> obj2)) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } private boolean accept(Meter.Id id) { diff --git a/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/ServiceLevelObjective.java b/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/ServiceLevelObjective.java index 71a646baf2..5d40e4f2ef 100644 --- a/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/ServiceLevelObjective.java +++ b/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/ServiceLevelObjective.java @@ -296,9 +296,12 @@ public final NumericQuery maxPercentile(Function search, double } ValueAtPercentile[] valueAtPercentiles = ((HistogramSupport) m).takeSnapshot() - .percentileValues(); - return Arrays.stream(valueAtPercentiles).filter(vap -> vap.percentile() == percentile) - .map(ValueAtPercentile::value).findAny().orElse(Double.NaN); + .percentileValues(); + return Arrays.stream(valueAtPercentiles) + .filter(vap -> vap.percentile() == percentile) + .map(ValueAtPercentile::value) + .findAny() + .orElse(Double.NaN); }).reduce(Double.NaN, MAX_OR_NAN)); } diff --git a/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/objectives/JvmServiceLevelObjectives.java b/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/objectives/JvmServiceLevelObjectives.java index 51822dfbb1..717e7e28db 100644 --- a/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/objectives/JvmServiceLevelObjectives.java +++ b/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/objectives/JvmServiceLevelObjectives.java @@ -37,40 +37,48 @@ public class JvmServiceLevelObjectives { */ public static final ServiceLevelObjective[] MEMORY = new ServiceLevelObjective[] { ServiceLevelObjective.build("jvm.pool.memory") - .failedMessage("Memory usage in a single memory pool exceeds 90% after garbage collection.") - .requires(new JvmHeapPressureMetrics()).baseUnit("percent used") - .value(s -> s.name("jvm.memory.usage.after.gc")).isLessThan(0.9), + .failedMessage("Memory usage in a single memory pool exceeds 90% after garbage collection.") + .requires(new JvmHeapPressureMetrics()) + .baseUnit("percent used") + .value(s -> s.name("jvm.memory.usage.after.gc")) + .isLessThan(0.9), ServiceLevelObjective.build("jvm.gc.load") - .failedMessage("Memory cleaning is taking more than 50% of CPU resources on average. " - + "This usually means really serious problems with memory resulting in high performance degradation.") - .requires(new JvmHeapPressureMetrics()).baseUnit("percent CPU time spent") - .value(s -> s.name("jvm.gc.overhead")).isLessThan(0.5), + .failedMessage("Memory cleaning is taking more than 50% of CPU resources on average. " + + "This usually means really serious problems with memory resulting in high performance degradation.") + .requires(new JvmHeapPressureMetrics()) + .baseUnit("percent CPU time spent") + .value(s -> s.name("jvm.gc.overhead")) + .isLessThan(0.5), ServiceLevelObjective - .compose("jvm.total.memory", ServiceLevelObjective.build("jvm.gc.overhead") + .compose("jvm.total.memory", + ServiceLevelObjective.build("jvm.gc.overhead") .failedMessage("More than 20% of CPU resources are being consumed by garbage collection.") - .baseUnit( - "percent CPU time spent") - .requires(new JvmHeapPressureMetrics()).value(s -> s.name("jvm.gc.overhead")) + .baseUnit("percent CPU time spent") + .requires(new JvmHeapPressureMetrics()) + .value(s -> s.name("jvm.gc.overhead")) .isLessThan(0.2), - ServiceLevelObjective.build("jvm.memory.consumption") - .failedMessage( - "More than 90% of total memory has been in use during the last 5 minutes.") - .baseUnit("maximum percent used in last 5 minutes").requires(new JvmMemoryMetrics()) - .value(s -> s.name("jvm.memory.used")) - .dividedBy(denom -> denom.value(s -> s.name("jvm.memory.committed"))) - .maxOver(Duration.ofMinutes(5)).isLessThan(0.9)) - .failedMessage( - "More than 90% of total memory has been in use during the last 5 minutes and more than 20% of CPU resources are being consumed by garbage collection. " - + "Lasting memory lack may result in performance degradation and server instability.") - .and() }; + ServiceLevelObjective.build("jvm.memory.consumption") + .failedMessage("More than 90% of total memory has been in use during the last 5 minutes.") + .baseUnit("maximum percent used in last 5 minutes") + .requires(new JvmMemoryMetrics()) + .value(s -> s.name("jvm.memory.used")) + .dividedBy(denom -> denom.value(s -> s.name("jvm.memory.committed"))) + .maxOver(Duration.ofMinutes(5)) + .isLessThan(0.9)) + .failedMessage( + "More than 90% of total memory has been in use during the last 5 minutes and more than 20% of CPU resources are being consumed by garbage collection. " + + "Lasting memory lack may result in performance degradation and server instability.") + .and() }; - public static final ServiceLevelObjective[] ALLOCATIONS = new ServiceLevelObjective[] { ServiceLevelObjective - .build("jvm.allocations.g1.humongous") - .failedMessage("A single object was allocated that exceeded 50% of the total size of the eden space.") - .baseUnit("allocations").requires(new JvmGcMetrics()) - .count(s -> s.name("jvm.gc.pause").tag("cause", "G1 Humongous Allocation")).isEqualTo(0) }; + public static final ServiceLevelObjective[] ALLOCATIONS = new ServiceLevelObjective[] { + ServiceLevelObjective.build("jvm.allocations.g1.humongous") + .failedMessage("A single object was allocated that exceeded 50% of the total size of the eden space.") + .baseUnit("allocations") + .requires(new JvmGcMetrics()) + .count(s -> s.name("jvm.gc.pause").tag("cause", "G1 Humongous Allocation")) + .isEqualTo(0) }; private JvmServiceLevelObjectives() { } diff --git a/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/objectives/OperatingSystemServiceLevelObjectives.java b/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/objectives/OperatingSystemServiceLevelObjectives.java index 6a92cf9428..59f3c2aa64 100644 --- a/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/objectives/OperatingSystemServiceLevelObjectives.java +++ b/implementations/micrometer-registry-health/src/main/java/io/micrometer/health/objectives/OperatingSystemServiceLevelObjectives.java @@ -28,11 +28,13 @@ public class OperatingSystemServiceLevelObjectives { public static final ServiceLevelObjective[] DISK = new ServiceLevelObjective[] { ServiceLevelObjective.build("os.file.descriptors") - .failedMessage("Too many file descriptors are open. When the max is reached, " - + "further attempts to retrieve a file descriptor will block indefinitely.") - .baseUnit("used / available (percent)").requires(new FileDescriptorMetrics()) - .value(s -> s.name("process.open.fds")) - .dividedBy(denom -> denom.value(s -> s.name("process.max.fds"))).isLessThan(0.8) }; + .failedMessage("Too many file descriptors are open. When the max is reached, " + + "further attempts to retrieve a file descriptor will block indefinitely.") + .baseUnit("used / available (percent)") + .requires(new FileDescriptorMetrics()) + .value(s -> s.name("process.open.fds")) + .dividedBy(denom -> denom.value(s -> s.name("process.max.fds"))) + .isLessThan(0.8) }; private OperatingSystemServiceLevelObjectives() { } diff --git a/implementations/micrometer-registry-health/src/test/java/io/micrometer/health/HealthMeterRegistryTest.java b/implementations/micrometer-registry-health/src/test/java/io/micrometer/health/HealthMeterRegistryTest.java index 1a156a1a01..b4262f3366 100644 --- a/implementations/micrometer-registry-health/src/test/java/io/micrometer/health/HealthMeterRegistryTest.java +++ b/implementations/micrometer-registry-health/src/test/java/io/micrometer/health/HealthMeterRegistryTest.java @@ -38,16 +38,21 @@ class HealthMeterRegistryTest { @Test void healthFromServiceLevelObjective() { - HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT).clock(new MockClock()) - .serviceLevelObjectives(ServiceLevelObjective.build("api.error.ratio").failedMessage("API error ratio") - .errorRatio(search -> search.name("http.server.requests").tag("uri", "$ENDPOINT"), - all -> all.tag("outcome", "SERVER_ERROR")) - .isLessThan(0.01)) - .build(); + HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) + .clock(new MockClock()) + .serviceLevelObjectives(ServiceLevelObjective.build("api.error.ratio") + .failedMessage("API error ratio") + .errorRatio(search -> search.name("http.server.requests").tag("uri", "$ENDPOINT"), + all -> all.tag("outcome", "SERVER_ERROR")) + .isLessThan(0.01)) + .build(); for (int i = 0; i < 100; i++) { - Timer.builder("http.server.requests").tag("outcome", i == 0 ? "SERVER_ERROR" : "SUCCESS") - .tag("uri", "$ENDPOINT").register(registry).record(10, TimeUnit.MILLISECONDS); + Timer.builder("http.server.requests") + .tag("outcome", i == 0 ? "SERVER_ERROR" : "SUCCESS") + .tag("uri", "$ENDPOINT") + .register(registry) + .record(10, TimeUnit.MILLISECONDS); } clock(registry).add(Duration.ofSeconds(10)); @@ -56,8 +61,11 @@ void healthFromServiceLevelObjective() { assertThat(registry.getServiceLevelObjectives().iterator().next().healthy(registry)).isFalse(); for (int i = 0; i < 100; i++) { - Timer.builder("http.server.requests").tag("outcome", "SUCCESS").tag("uri", "$ENDPOINT").register(registry) - .record(10, TimeUnit.MILLISECONDS); + Timer.builder("http.server.requests") + .tag("outcome", "SUCCESS") + .tag("uri", "$ENDPOINT") + .register(registry) + .record(10, TimeUnit.MILLISECONDS); } clock(registry).add(Duration.ofSeconds(10)); @@ -68,20 +76,24 @@ void healthFromServiceLevelObjective() { @Test void unmatchedServiceLevelObjectiveReportsHealthy() { - HealthMeterRegistry registry = HealthMeterRegistry - .builder(HealthConfig.DEFAULT).clock(new MockClock()).serviceLevelObjectives(ServiceLevelObjective - .build("counter.throughput").count(search -> search.name("my.counter")).isGreaterThan(1)) - .build(); + HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) + .clock(new MockClock()) + .serviceLevelObjectives(ServiceLevelObjective.build("counter.throughput") + .count(search -> search.name("my.counter")) + .isGreaterThan(1)) + .build(); assertThat(registry.getServiceLevelObjectives().iterator().next().healthy(registry)).isTrue(); } @Test void onlyMetricsThatAreServiceLevelIndicatorsAreRegistered() { - HealthMeterRegistry registry = HealthMeterRegistry - .builder(HealthConfig.DEFAULT).clock(new MockClock()).serviceLevelObjectives(ServiceLevelObjective - .build("counter.throughput").count(search -> search.name("my.counter")).isGreaterThan(1)) - .build(); + HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) + .clock(new MockClock()) + .serviceLevelObjectives(ServiceLevelObjective.build("counter.throughput") + .count(search -> search.name("my.counter")) + .isGreaterThan(1)) + .build(); assertThat(registry.getMeters()).isEmpty(); @@ -94,29 +106,34 @@ void onlyMetricsThatAreServiceLevelIndicatorsAreRegistered() { @Test void applyRequiredBinders() { - HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT).clock(new MockClock()) - .serviceLevelObjectives( - ServiceLevelObjective.build("counter.throughput").requires(new JvmMemoryMetrics()) - .value(search -> search.name("jvm.memory.used")).isGreaterThan(1)) - .build(); + HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) + .clock(new MockClock()) + .serviceLevelObjectives(ServiceLevelObjective.build("counter.throughput") + .requires(new JvmMemoryMetrics()) + .value(search -> search.name("jvm.memory.used")) + .isGreaterThan(1)) + .build(); assertThat(registry.getMeters().stream().map(m -> m.getId().getName())).containsOnly("jvm.memory.used"); } @Test void meterFiltersAffectServiceLevelObjectives() { - HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT).clock(new MockClock()) - .serviceLevelObjectives(JvmServiceLevelObjectives.MEMORY) - .serviceLevelObjectiveFilter(MeterFilter.denyNameStartsWith("jvm.pool")) - .serviceLevelObjectiveFilter(new MeterFilter() { - @Override - public Meter.Id map(Meter.Id id) { - return id.getName().equals("jvm.gc.load") ? id.withName("jvm.collection.load") : id; - } - }).build(); + HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) + .clock(new MockClock()) + .serviceLevelObjectives(JvmServiceLevelObjectives.MEMORY) + .serviceLevelObjectiveFilter(MeterFilter.denyNameStartsWith("jvm.pool")) + .serviceLevelObjectiveFilter(new MeterFilter() { + @Override + public Meter.Id map(Meter.Id id) { + return id.getName().equals("jvm.gc.load") ? id.withName("jvm.collection.load") : id; + } + }) + .build(); assertThat(registry.getServiceLevelObjectives().stream().map(ServiceLevelObjective::getName)) - .contains("jvm.collection.load").doesNotContain("jvm.pool.memory"); + .contains("jvm.collection.load") + .doesNotContain("jvm.pool.memory"); } } diff --git a/implementations/micrometer-registry-health/src/test/java/io/micrometer/health/QueryTest.java b/implementations/micrometer-registry-health/src/test/java/io/micrometer/health/QueryTest.java index b00cdc5864..0cc4dfd47e 100644 --- a/implementations/micrometer-registry-health/src/test/java/io/micrometer/health/QueryTest.java +++ b/implementations/micrometer-registry-health/src/test/java/io/micrometer/health/QueryTest.java @@ -37,12 +37,13 @@ class QueryTest { HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) - // just so my.timer doesn't get filtered out eagerly - .serviceLevelObjectives( - ServiceLevelObjective.build("timer").count(s -> s.name("my.timer")).isGreaterThan(0)) - .serviceLevelObjectives(ServiceLevelObjective.build("function.counter") - .count(s -> s.name("my.function.counter")).isGreaterThan(0)) - .clock(new MockClock()).build(); + // just so my.timer doesn't get filtered out eagerly + .serviceLevelObjectives(ServiceLevelObjective.build("timer").count(s -> s.name("my.timer")).isGreaterThan(0)) + .serviceLevelObjectives(ServiceLevelObjective.build("function.counter") + .count(s -> s.name("my.function.counter")) + .isGreaterThan(0)) + .clock(new MockClock()) + .build(); @BeforeEach void before() { @@ -61,98 +62,121 @@ void before() { @Test void count() { assertThat(ServiceLevelObjective.build("timer.throughput").count(s -> s.name("my.timer")).getValue(registry)) - .isEqualTo(3); + .isEqualTo(3); } @Test void countWhenMeterIsFunctionCounter() { - assertThat(ServiceLevelObjective.build("function.counter.objective").count(s -> s.name("my.function.counter")) - .getValue(registry)).isEqualTo(1); + assertThat(ServiceLevelObjective.build("function.counter.objective") + .count(s -> s.name("my.function.counter")) + .getValue(registry)).isEqualTo(1); } @Test void max() { assertThat(TimeUtils.nanosToUnit( ServiceLevelObjective.build("timer.max").max(s -> s.name("my.timer")).getValue(registry), - TimeUnit.SECONDS)).isEqualTo(2); + TimeUnit.SECONDS)) + .isEqualTo(2); } @Test void total() { assertThat(TimeUtils.nanosToUnit( ServiceLevelObjective.build("timer.total").total(s -> s.name("my.timer")).getValue(registry), - TimeUnit.SECONDS)).isEqualTo(5); + TimeUnit.SECONDS)) + .isEqualTo(5); } @Test void divideBy() { - assertThat(ServiceLevelObjective.build("quotient").count(s -> s.name("my.timer").tag("k", "v1")) - .dividedBy(denom -> denom.count(s -> s.name("my.timer").tag("k", "v2"))).getValue(registry)) - .isEqualTo(1.0 / 2); + assertThat(ServiceLevelObjective.build("quotient") + .count(s -> s.name("my.timer").tag("k", "v1")) + .dividedBy(denom -> denom.count(s -> s.name("my.timer").tag("k", "v2"))) + .getValue(registry)).isEqualTo(1.0 / 2); } @Test void plus() { - assertThat(ServiceLevelObjective.build("sum").count(s -> s.name("my.timer").tag("k", "v1")) - .plus(with -> with.count(s -> s.name("my.timer").tag("k", "v2"))).getValue(registry)).isEqualTo(1 + 2); + assertThat(ServiceLevelObjective.build("sum") + .count(s -> s.name("my.timer").tag("k", "v1")) + .plus(with -> with.count(s -> s.name("my.timer").tag("k", "v2"))) + .getValue(registry)).isEqualTo(1 + 2); } @Test void minus() { - assertThat(ServiceLevelObjective.build("difference").count(s -> s.name("my.timer").tag("k", "v1")) - .minus(with -> with.count(s -> s.name("my.timer").tag("k", "v2"))).getValue(registry)).isEqualTo(1 - 2); + assertThat(ServiceLevelObjective.build("difference") + .count(s -> s.name("my.timer").tag("k", "v1")) + .minus(with -> with.count(s -> s.name("my.timer").tag("k", "v2"))) + .getValue(registry)).isEqualTo(1 - 2); } @Test void multipliedBy() { - assertThat(ServiceLevelObjective.build("product").count(s -> s.name("my.timer").tag("k", "v1")) - .multipliedBy(by -> by.count(s -> s.name("my.timer").tag("k", "v2"))).getValue(registry)) - .isEqualTo(1.0 * 2); + assertThat(ServiceLevelObjective.build("product") + .count(s -> s.name("my.timer").tag("k", "v1")) + .multipliedBy(by -> by.count(s -> s.name("my.timer").tag("k", "v2"))) + .getValue(registry)).isEqualTo(1.0 * 2); } @Test void isLessThan() { assertThat(ServiceLevelObjective.build("sum").count(s -> s.name("my.timer")).isLessThan(4).healthy(registry)) - .isTrue(); + .isTrue(); - assertThat(ServiceLevelObjective.build("sum").total(s -> s.name("my.timer")).isLessThan(Duration.ofSeconds(6)) - .healthy(registry)).isTrue(); + assertThat(ServiceLevelObjective.build("sum") + .total(s -> s.name("my.timer")) + .isLessThan(Duration.ofSeconds(6)) + .healthy(registry)).isTrue(); } @Test void isLessThanOrEqualTo() { - assertThat(ServiceLevelObjective.build("sum").count(s -> s.name("my.timer")).isLessThanOrEqualTo(3) - .healthy(registry)).isTrue(); - - assertThat(ServiceLevelObjective.build("sum").total(s -> s.name("my.timer")) - .isLessThanOrEqualTo(Duration.ofSeconds(5)).healthy(registry)).isTrue(); + assertThat(ServiceLevelObjective.build("sum") + .count(s -> s.name("my.timer")) + .isLessThanOrEqualTo(3) + .healthy(registry)).isTrue(); + + assertThat(ServiceLevelObjective.build("sum") + .total(s -> s.name("my.timer")) + .isLessThanOrEqualTo(Duration.ofSeconds(5)) + .healthy(registry)).isTrue(); } @Test void isGreaterThan() { assertThat(ServiceLevelObjective.build("sum").count(s -> s.name("my.timer")).isGreaterThan(2).healthy(registry)) - .isTrue(); + .isTrue(); - assertThat(ServiceLevelObjective.build("sum").total(s -> s.name("my.timer")) - .isGreaterThan(Duration.ofSeconds(4)).healthy(registry)).isTrue(); + assertThat(ServiceLevelObjective.build("sum") + .total(s -> s.name("my.timer")) + .isGreaterThan(Duration.ofSeconds(4)) + .healthy(registry)).isTrue(); } @Test void isGreaterThanOrEqualTo() { - assertThat(ServiceLevelObjective.build("sum").count(s -> s.name("my.timer")).isGreaterThanOrEqualTo(3) - .healthy(registry)).isTrue(); - - assertThat(ServiceLevelObjective.build("sum").total(s -> s.name("my.timer")) - .isGreaterThanOrEqualTo(Duration.ofSeconds(5)).healthy(registry)).isTrue(); + assertThat(ServiceLevelObjective.build("sum") + .count(s -> s.name("my.timer")) + .isGreaterThanOrEqualTo(3) + .healthy(registry)).isTrue(); + + assertThat(ServiceLevelObjective.build("sum") + .total(s -> s.name("my.timer")) + .isGreaterThanOrEqualTo(Duration.ofSeconds(5)) + .healthy(registry)).isTrue(); } @Test void isEqualTo() { assertThat(ServiceLevelObjective.build("sum").count(s -> s.name("my.timer")).isEqualTo(3).healthy(registry)) - .isTrue(); + .isTrue(); - assertThat(ServiceLevelObjective.build("sum").total(s -> s.name("my.timer")).isEqualTo(Duration.ofSeconds(5)) - .healthy(registry)).isTrue(); + assertThat(ServiceLevelObjective.build("sum") + .total(s -> s.name("my.timer")) + .isEqualTo(Duration.ofSeconds(5)) + .healthy(registry)).isTrue(); } } diff --git a/implementations/micrometer-registry-humio/src/main/java/io/micrometer/humio/HumioMeterRegistry.java b/implementations/micrometer-registry-humio/src/main/java/io/micrometer/humio/HumioMeterRegistry.java index 3b2409fe24..89b1dc0928 100644 --- a/implementations/micrometer-registry-humio/src/main/java/io/micrometer/humio/HumioMeterRegistry.java +++ b/implementations/micrometer-registry-humio/src/main/java/io/micrometer/humio/HumioMeterRegistry.java @@ -97,9 +97,10 @@ protected void publish() { String tags = ""; Map datasourceTags = config.tags(); if (datasourceTags != null && !datasourceTags.isEmpty()) { - tags = datasourceTags.entrySet().stream() - .map(tag -> "\"" + tag.getKey() + "\": \"" + tag.getValue() + "\"") - .collect(joining(",", "\"tags\":{", "},")); + tags = datasourceTags.entrySet() + .stream() + .map(tag -> "\"" + tag.getKey() + "\": \"" + tag.getValue() + "\"") + .collect(joining(",", "\"tags\":{", "},")); } post.withJsonContent(meters.stream() @@ -282,12 +283,17 @@ String writeEvent(Meter meter, Attribute... attributes) { String name = getConventionName(meter.getId()); - sb.append("{\"timestamp\":\"").append(timestamp).append("\",\"attributes\":{\"name\":\"") - .append(escapeJson(name)).append('"'); + sb.append("{\"timestamp\":\"") + .append(timestamp) + .append("\",\"attributes\":{\"name\":\"") + .append(escapeJson(name)) + .append('"'); for (Attribute attribute : attributes) { - sb.append(",\"").append(attribute.name).append("\":") - .append(DoubleFormat.wholeOrDecimal(attribute.value)); + sb.append(",\"") + .append(attribute.name) + .append("\":") + .append(DoubleFormat.wholeOrDecimal(attribute.value)); } List tags = getConventionTags(meter.getId()); diff --git a/implementations/micrometer-registry-humio/src/test/java/io/micrometer/humio/HumioConfigTest.java b/implementations/micrometer-registry-humio/src/test/java/io/micrometer/humio/HumioConfigTest.java index 4b09757a6a..4f1ec013c7 100644 --- a/implementations/micrometer-registry-humio/src/test/java/io/micrometer/humio/HumioConfigTest.java +++ b/implementations/micrometer-registry-humio/src/test/java/io/micrometer/humio/HumioConfigTest.java @@ -34,7 +34,7 @@ void invalid() { props.put("humio.uri", "bad"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsOnly("must be a valid URL"); + .containsOnly("must be a valid URL"); } @Test diff --git a/implementations/micrometer-registry-humio/src/test/java/io/micrometer/humio/HumioMeterRegistryTest.java b/implementations/micrometer-registry-humio/src/test/java/io/micrometer/humio/HumioMeterRegistryTest.java index 611d5d8fa6..9ffe7d9944 100644 --- a/implementations/micrometer-registry-humio/src/test/java/io/micrometer/humio/HumioMeterRegistryTest.java +++ b/implementations/micrometer-registry-humio/src/test/java/io/micrometer/humio/HumioMeterRegistryTest.java @@ -66,7 +66,7 @@ void datasourceTags(@WiremockResolver.Wiremock WireMockServer server) { server.stubFor(any(anyUrl())); registry.publish(); server.verify(postRequestedFor(urlMatching("/api/v1/ingest/humio-structured")) - .withRequestBody(containing("\"tags\":{\"name\": \"micrometer\"}"))); + .withRequestBody(containing("\"tags\":{\"name\": \"micrometer\"}"))); } @Test @@ -143,7 +143,7 @@ void writeFunctionCounter() { @Test void writeFunctionCounterShouldDropPositiveInfiniteValue() { FunctionCounter counter = FunctionCounter.builder("myCounter", Double.POSITIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(createBatch().writeFunctionCounter(counter)).isNull(); } @@ -151,7 +151,7 @@ void writeFunctionCounterShouldDropPositiveInfiniteValue() { @Test void writeFunctionCounterShouldDropNegativeInfiniteValue() { FunctionCounter counter = FunctionCounter.builder("myCounter", Double.NEGATIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(createBatch().writeFunctionCounter(counter)).isNull(); } diff --git a/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/CreateDatabaseQueryBuilder.java b/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/CreateDatabaseQueryBuilder.java index 40d62b4cd4..3af69748c4 100644 --- a/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/CreateDatabaseQueryBuilder.java +++ b/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/CreateDatabaseQueryBuilder.java @@ -85,8 +85,9 @@ CreateDatabaseQueryBuilder setRetentionPolicyName(@Nullable String retentionPoli String build() { StringBuilder queryStringBuilder = new StringBuilder(String.format(QUERY_MANDATORY_TEMPLATE, databaseName)); if (hasAnyRetentionPolicy()) { - String retentionPolicyClause = Stream.of(retentionPolicyClauses).filter(Objects::nonNull) - .reduce(RETENTION_POLICY_INTRODUCTION, String::concat); + String retentionPolicyClause = Stream.of(retentionPolicyClauses) + .filter(Objects::nonNull) + .reduce(RETENTION_POLICY_INTRODUCTION, String::concat); queryStringBuilder.append(retentionPolicyClause); } return queryStringBuilder.toString(); diff --git a/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxConfig.java b/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxConfig.java index 917aa4d122..8e4b704992 100644 --- a/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxConfig.java +++ b/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxConfig.java @@ -218,10 +218,10 @@ default Validated validate() { return checkAll(this, c -> StepRegistryConfig.validate(c), checkRequired("db", InfluxConfig::db), checkRequired("bucket", InfluxConfig::bucket), checkRequired("consistency", InfluxConfig::consistency), checkRequired("apiVersion", InfluxConfig::apiVersion) - .andThen(v -> v.invalidateWhen(a -> a == InfluxApiVersion.V2 && StringUtils.isBlank(org()), - "requires 'org' is also configured", InvalidReason.MISSING)) - .andThen(v -> v.invalidateWhen(a -> a == InfluxApiVersion.V2 && StringUtils.isBlank(token()), - "requires 'token' is also configured", InvalidReason.MISSING)), + .andThen(v -> v.invalidateWhen(a -> a == InfluxApiVersion.V2 && StringUtils.isBlank(org()), + "requires 'org' is also configured", InvalidReason.MISSING)) + .andThen(v -> v.invalidateWhen(a -> a == InfluxApiVersion.V2 && StringUtils.isBlank(token()), + "requires 'token' is also configured", InvalidReason.MISSING)), checkRequired("uri", InfluxConfig::uri)); } diff --git a/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxMeterRegistry.java b/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxMeterRegistry.java index 68807d5b9c..8ef3bc41c0 100644 --- a/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxMeterRegistry.java +++ b/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxMeterRegistry.java @@ -99,13 +99,15 @@ private void createDatabaseIfNecessary() { try { String createDatabaseQuery = new CreateDatabaseQueryBuilder(config.db()) - .setRetentionDuration(config.retentionDuration()).setRetentionPolicyName(config.retentionPolicy()) - .setRetentionReplicationFactor(config.retentionReplicationFactor()) - .setRetentionShardDuration(config.retentionShardDuration()).build(); + .setRetentionDuration(config.retentionDuration()) + .setRetentionPolicyName(config.retentionPolicy()) + .setRetentionReplicationFactor(config.retentionReplicationFactor()) + .setRetentionShardDuration(config.retentionShardDuration()) + .build(); HttpSender.Request.Builder requestBuilder = httpClient - .post(config.uri() + "/query?q=" + URLEncoder.encode(createDatabaseQuery, "UTF-8")) - .withBasicAuthentication(config.userName(), config.password()); + .post(config.uri() + "/query?q=" + URLEncoder.encode(createDatabaseQuery, "UTF-8")) + .withBasicAuthentication(config.userName(), config.password()); config.apiVersion().addHeaderToken(config, requestBuilder); requestBuilder.send().onSuccess(response -> { @@ -127,7 +129,7 @@ protected void publish() { for (List batch : MeterPartition.partition(this, config.batchSize())) { HttpSender.Request.Builder requestBuilder = httpClient.post(influxEndpoint) - .withBasicAuthentication(config.userName(), config.password()); + .withBasicAuthentication(config.userName(), config.password()); config.apiVersion().addHeaderToken(config, requestBuilder); // @formatter:off requestBuilder @@ -170,8 +172,10 @@ Stream writeMeter(Meter m) { if (!Double.isFinite(value)) { continue; } - String fieldKey = measurement.getStatistic().getTagValueRepresentation() - .replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase(); + String fieldKey = measurement.getStatistic() + .getTagValueRepresentation() + .replaceAll("(.)(\\p{Upper})", "$1_$2") + .toLowerCase(); fields.add(new Field(fieldKey, value)); } if (fields.isEmpty()) { @@ -236,8 +240,10 @@ private Stream writeSummary(DistributionSummary summary) { } private String influxLineProtocol(Meter.Id id, String metricType, Stream fields) { - String tags = getConventionTags(id).stream().filter(t -> StringUtils.isNotBlank(t.getValue())) - .map(t -> "," + t.getKey() + "=" + t.getValue()).collect(joining("")); + String tags = getConventionTags(id).stream() + .filter(t -> StringUtils.isNotBlank(t.getValue())) + .map(t -> "," + t.getKey() + "=" + t.getValue()) + .collect(joining("")); return getConventionName(id) + tags + ",metric_type=" + metricType + " " + fields.map(Field::toString).collect(joining(",")) + " " + clock.wallTime(); diff --git a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/CreateDatabaseQueryBuilderTest.java b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/CreateDatabaseQueryBuilderTest.java index a755068af1..64e2c7a423 100644 --- a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/CreateDatabaseQueryBuilderTest.java +++ b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/CreateDatabaseQueryBuilderTest.java @@ -53,8 +53,11 @@ void oneClauseInRetentionPolicy() { @Test void allClausesInRetentionPolicy() { - String query = createDatabaseQueryBuilder.setRetentionPolicyName("dummy_policy").setRetentionDuration("2d") - .setRetentionReplicationFactor(1).setRetentionShardDuration("3").build(); + String query = createDatabaseQueryBuilder.setRetentionPolicyName("dummy_policy") + .setRetentionDuration("2d") + .setRetentionReplicationFactor(1) + .setRetentionShardDuration("3") + .build(); assertEquals( "CREATE DATABASE \"dummy_database_0\" WITH DURATION 2d REPLICATION 1 SHARD DURATION 3 NAME dummy_policy", query); diff --git a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxConfigTest.java b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxConfigTest.java index 78ad2606fa..9d55fce603 100644 --- a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxConfigTest.java +++ b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxConfigTest.java @@ -35,7 +35,7 @@ void invalid() { props.put("influx.consistency", "bad"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactlyInAnyOrder("must be a valid URL", "should be one of 'ANY', 'ONE', 'QUORUM', 'ALL'"); + .containsExactlyInAnyOrder("must be a valid URL", "should be one of 'ANY', 'ONE', 'QUORUM', 'ALL'"); } @Test diff --git a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryFieldTest.java b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryFieldTest.java index 25f256facd..983e2ee0f4 100644 --- a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryFieldTest.java +++ b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryFieldTest.java @@ -69,7 +69,7 @@ void toStringWithSwedishLocale() { @Test void timeCannotBeAFieldKey() { assertThat(catchThrowable(() -> new InfluxMeterRegistry.Field("time", 1.0))) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryTest.java b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryTest.java index 255010d3ce..bf3d845cda 100644 --- a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryTest.java +++ b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryTest.java @@ -105,12 +105,12 @@ void writeCounterWithFunction() { @Test void writeCounterWithFunctionCounterShouldDropInfiniteValues() { FunctionCounter counter = FunctionCounter.builder("myCounter", Double.POSITIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeCounter(counter.getId(), Double.POSITIVE_INFINITY)).isEmpty(); counter = FunctionCounter.builder("myCounter", Double.NEGATIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeCounter(counter.getId(), Double.NEGATIVE_INFINITY)).isEmpty(); } @@ -120,7 +120,7 @@ void writeShouldDropTagWithBlankValue() { meterRegistry.gauge("my.gauge", Tags.of("foo", "bar").and("baz", ""), 1d); final Gauge gauge = meterRegistry.find("my.gauge").gauge(); assertThat(meterRegistry.writeGauge(gauge.getId(), 1d)).hasSize(1) - .allSatisfy(s -> assertThat(s).contains("foo=bar").doesNotContain("baz")); + .allSatisfy(s -> assertThat(s).contains("foo=bar").doesNotContain("baz")); } @Test @@ -161,8 +161,8 @@ void writeMeterWhenCustomMeterHasMixedFiniteAndNonFiniteValuesShouldSkipOnlyNonF @Test void nanFunctionTimerShouldNotBeWritten() { FunctionTimer timer = FunctionTimer - .builder("myFunctionTimer", Double.NaN, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) - .register(meterRegistry); + .builder("myFunctionTimer", Double.NaN, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS) + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionTimer(timer)).isEmpty(); } @@ -196,7 +196,7 @@ public double mean(TimeUnit unit) { } }; assertThat(meterRegistry.writeFunctionTimer(functionTimer)) - .containsOnly("func_timer,metric_type=histogram sum=1,count=1 1"); + .containsOnly("func_timer,metric_type=histogram sum=1,count=1 1"); } } diff --git a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryVersionsTest.java b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryVersionsTest.java index de3c9c0071..390420ca23 100644 --- a/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryVersionsTest.java +++ b/implementations/micrometer-registry-influx/src/test/java/io/micrometer/influx/InfluxMeterRegistryVersionsTest.java @@ -52,8 +52,8 @@ void writeToV1Token(@Wiremock WireMockServer server) { publishSimpleStat(InfluxApiVersion.V1, server); server.verify(postRequestedFor(urlEqualTo("/write?consistency=one&precision=ms&db=my-db")) - .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) - .withHeader("Authorization", equalTo("Bearer my-token"))); + .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) + .withHeader("Authorization", equalTo("Bearer my-token"))); } private void stubForV1(WireMockServer server) { @@ -74,8 +74,8 @@ void writeToV1BasicAuth(@Wiremock WireMockServer server) { publishSimpleStat(config); server.verify(postRequestedFor(urlEqualTo("/write?consistency=one&precision=ms&db=mydb")) - .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) - .withBasicAuth(new BasicCredentials("user", "pass"))); + .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) + .withBasicAuth(new BasicCredentials("user", "pass"))); } @Test @@ -92,8 +92,8 @@ void writeToV1TokenPreferredOverBasicAuth(@Wiremock WireMockServer server) { publishSimpleStat(config); server.verify(postRequestedFor(urlEqualTo("/write?consistency=one&precision=ms&db=mydb")) - .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) - .withHeader("Authorization", equalTo("Bearer some-token"))); + .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) + .withHeader("Authorization", equalTo("Bearer some-token"))); } @Test @@ -103,8 +103,8 @@ void writeToV2Token(@Wiremock WireMockServer server) { publishSimpleStat(InfluxApiVersion.V2, server); server.verify(postRequestedFor(urlEqualTo("/api/v2/write?precision=ms&bucket=my-bucket&org=my-org")) - .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) - .withHeader("Authorization", equalTo("Token my-token"))); + .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) + .withHeader("Authorization", equalTo("Token my-token"))); } private void stubForV2(WireMockServer server) { @@ -125,8 +125,8 @@ void writeToV1WithRP(@Wiremock WireMockServer server) { publishSimpleStat(config); server.verify(postRequestedFor(urlEqualTo("/write?consistency=one&precision=ms&db=my-db&rp=one_day_only")) - .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) - .withHeader("Authorization", equalTo("Bearer my-token"))); + .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) + .withHeader("Authorization", equalTo("Bearer my-token"))); } @Test @@ -156,8 +156,8 @@ public InfluxApiVersion apiVersion() { }; assertThatThrownBy(() -> publishSimpleStat(config)) - .hasMessage("influx.apiVersion was 'V2' but it requires 'token' is also configured") - .isInstanceOf(ValidationException.class); + .hasMessage("influx.apiVersion was 'V2' but it requires 'token' is also configured") + .isInstanceOf(ValidationException.class); server.verify(0, postRequestedFor(anyUrl())); } @@ -194,8 +194,8 @@ public InfluxApiVersion apiVersion() { }; assertThatThrownBy(() -> publishSimpleStat(config)) - .hasMessage("influx.apiVersion was 'V2' but it requires 'token' is also configured") - .isInstanceOf(ValidationException.class); + .hasMessage("influx.apiVersion was 'V2' but it requires 'token' is also configured") + .isInstanceOf(ValidationException.class); server.verify(0, postRequestedFor(anyUrl())); } @@ -227,8 +227,8 @@ public InfluxApiVersion apiVersion() { }; assertThatThrownBy(() -> publishSimpleStat(config)) - .hasMessage("influx.apiVersion was 'V2' but it requires 'org' is also configured") - .isInstanceOf(ValidationException.class); + .hasMessage("influx.apiVersion was 'V2' but it requires 'org' is also configured") + .isInstanceOf(ValidationException.class); server.verify(0, postRequestedFor(anyUrl())); } @@ -265,8 +265,8 @@ public InfluxApiVersion apiVersion() { }; assertThatThrownBy(() -> publishSimpleStat(config)) - .hasMessage("influx.apiVersion was 'V2' but it requires 'org' is also configured") - .isInstanceOf(ValidationException.class); + .hasMessage("influx.apiVersion was 'V2' but it requires 'org' is also configured") + .isInstanceOf(ValidationException.class); server.verify(0, postRequestedFor(anyUrl())); } @@ -285,13 +285,13 @@ void bucketOrDbShouldBeSpecified() { props.put("influx.db", ""); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactly("db or bucket should be specified"); + .containsExactly("db or bucket should be specified"); } @Test void createStorageV1(@Wiremock WireMockServer server) { server.stubFor(any(urlPathEqualTo("/query")) - .willReturn(aResponse().withStatus(200).withBody("{\"results\":[{\"statement_id\":0}]}"))); + .willReturn(aResponse().withStatus(200).withBody("{\"results\":[{\"statement_id\":0}]}"))); stubForV1(server); Map props = new HashMap<>(); @@ -306,8 +306,8 @@ void createStorageV1(@Wiremock WireMockServer server) { server.verify(postRequestedFor(urlEqualTo("/query?q=CREATE+DATABASE+%22my-db%22")).withHeader("Authorization", equalTo("Bearer my-token"))); server.verify(postRequestedFor(urlEqualTo("/write?consistency=one&precision=ms&db=my-db")) - .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) - .withHeader("Authorization", equalTo("Bearer my-token"))); + .withRequestBody(equalTo("my_counter,metric_type=counter value=0 1")) + .withHeader("Authorization", equalTo("Bearer my-token"))); } @Test @@ -385,8 +385,11 @@ public InfluxApiVersion apiVersion() { private void publishSimpleStat(InfluxConfig config) { InfluxMeterRegistry registry = new InfluxMeterRegistry(config, new MockClock()); - Counter.builder("my.counter").baseUnit(TimeUnit.MICROSECONDS.name().toLowerCase()) - .description("metric description").register(registry).increment(Math.PI); + Counter.builder("my.counter") + .baseUnit(TimeUnit.MICROSECONDS.name().toLowerCase()) + .description("metric description") + .register(registry) + .increment(Math.PI); registry.publish(); } diff --git a/implementations/micrometer-registry-kairos/src/main/java/io/micrometer/kairos/KairosMeterRegistry.java b/implementations/micrometer-registry-kairos/src/main/java/io/micrometer/kairos/KairosMeterRegistry.java index b3d5c055db..920ad15a8e 100644 --- a/implementations/micrometer-registry-kairos/src/main/java/io/micrometer/kairos/KairosMeterRegistry.java +++ b/implementations/micrometer-registry-kairos/src/main/java/io/micrometer/kairos/KairosMeterRegistry.java @@ -95,9 +95,9 @@ protected void publish() { ).collect(Collectors.joining(",", "[", "]")) ) // @formatter:on - .send() - .onSuccess(response -> logger.debug("successfully sent {} metrics to kairos.", batch.size())) - .onError(response -> logger.error("failed to send metrics to kairos: {}", response.body())); + .send() + .onSuccess(response -> logger.debug("successfully sent {} metrics to kairos.", batch.size())) + .onError(response -> logger.error("failed to send metrics to kairos: {}", response.body())); } catch (Throwable t) { logger.warn("failed to send metrics to kairos", t); @@ -176,14 +176,18 @@ Stream writeCustomMetric(Meter meter) { continue; } metrics.add(new KairosMetricBuilder().field("name", measurement.getStatistic().getTagValueRepresentation()) - .datapoints(wallTime, value).tags(tags).build()); + .datapoints(wallTime, value) + .tags(tags) + .build()); } return metrics.stream(); } String writeMetric(Meter.Id id, long wallTime, double value) { - return new KairosMetricBuilder().field("name", getConventionName(id)).datapoints(wallTime, value) - .tags(getConventionTags(id)).build(); + return new KairosMetricBuilder().field("name", getConventionName(id)) + .datapoints(wallTime, value) + .tags(getConventionTags(id)) + .build(); } private Meter.Id idWithSuffix(Meter.Id id, String suffix) { @@ -208,8 +212,11 @@ KairosMetricBuilder field(String key, String value) { } KairosMetricBuilder datapoints(long wallTime, double value) { - sb.append(",\"datapoints\":[[").append(wallTime).append(',').append(DoubleFormat.wholeOrDecimal(value)) - .append("]]"); + sb.append(",\"datapoints\":[[") + .append(wallTime) + .append(',') + .append(DoubleFormat.wholeOrDecimal(value)) + .append("]]"); return this; } diff --git a/implementations/micrometer-registry-kairos/src/test/java/io/micrometer/kairos/KairosConfigTest.java b/implementations/micrometer-registry-kairos/src/test/java/io/micrometer/kairos/KairosConfigTest.java index 441d2645a8..4237e65b96 100644 --- a/implementations/micrometer-registry-kairos/src/test/java/io/micrometer/kairos/KairosConfigTest.java +++ b/implementations/micrometer-registry-kairos/src/test/java/io/micrometer/kairos/KairosConfigTest.java @@ -34,7 +34,7 @@ void invalid() { props.put("kairos.uri", "bad"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactly("must be a valid URL"); + .containsExactly("must be a valid URL"); } @Test diff --git a/implementations/micrometer-registry-kairos/src/test/java/io/micrometer/kairos/KairosMeterRegistryTest.java b/implementations/micrometer-registry-kairos/src/test/java/io/micrometer/kairos/KairosMeterRegistryTest.java index 42e8c2cbc6..c80167abfa 100644 --- a/implementations/micrometer-registry-kairos/src/test/java/io/micrometer/kairos/KairosMeterRegistryTest.java +++ b/implementations/micrometer-registry-kairos/src/test/java/io/micrometer/kairos/KairosMeterRegistryTest.java @@ -102,12 +102,12 @@ void writeFunctionCounter() { @Test void writeFunctionCounterShouldDropInfiniteValues() { FunctionCounter counter = FunctionCounter.builder("myCounter", Double.POSITIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter)).isEmpty(); counter = FunctionCounter.builder("myCounter", Double.NEGATIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter)).isEmpty(); } diff --git a/implementations/micrometer-registry-new-relic/src/main/java/io/micrometer/newrelic/NewRelicConfig.java b/implementations/micrometer-registry-new-relic/src/main/java/io/micrometer/newrelic/NewRelicConfig.java index 9a441aa27d..65dfacac00 100644 --- a/implementations/micrometer-registry-new-relic/src/main/java/io/micrometer/newrelic/NewRelicConfig.java +++ b/implementations/micrometer-registry-new-relic/src/main/java/io/micrometer/newrelic/NewRelicConfig.java @@ -72,16 +72,18 @@ default ClientProviderType clientProviderType() { @Nullable default String apiKey() { - return getSecret(this, "apiKey").invalidateWhen( - secret -> isBlank(secret) && ClientProviderType.INSIGHTS_API.equals(clientProviderType()), - "is required when publishing to Insights API", InvalidReason.MISSING).orElse(null); + return getSecret(this, "apiKey") + .invalidateWhen(secret -> isBlank(secret) && ClientProviderType.INSIGHTS_API.equals(clientProviderType()), + "is required when publishing to Insights API", InvalidReason.MISSING) + .orElse(null); } @Nullable default String accountId() { - return getSecret(this, "accountId").invalidateWhen( - secret -> isBlank(secret) && ClientProviderType.INSIGHTS_API.equals(clientProviderType()), - "is required when publishing to Insights API", InvalidReason.MISSING).orElse(null); + return getSecret(this, "accountId") + .invalidateWhen(secret -> isBlank(secret) && ClientProviderType.INSIGHTS_API.equals(clientProviderType()), + "is required when publishing to Insights API", InvalidReason.MISSING) + .orElse(null); } /** @@ -95,11 +97,9 @@ default String uri() { @Override default Validated validate() { - return checkAll(this, c -> StepRegistryConfig.validate(c), - check("eventType", NewRelicConfig::eventType) - .andThen(v -> v.invalidateWhen(type -> isBlank(type) && !meterNameEventTypeEnabled(), - "event type is required when not using the meter name as the event type", - InvalidReason.MISSING)), + return checkAll(this, c -> StepRegistryConfig.validate(c), check("eventType", NewRelicConfig::eventType) + .andThen(v -> v.invalidateWhen(type -> isBlank(type) && !meterNameEventTypeEnabled(), + "event type is required when not using the meter name as the event type", InvalidReason.MISSING)), checkRequired("clientProviderType", NewRelicConfig::clientProviderType)); } diff --git a/implementations/micrometer-registry-new-relic/src/main/java/io/micrometer/newrelic/NewRelicInsightsApiClientProvider.java b/implementations/micrometer-registry-new-relic/src/main/java/io/micrometer/newrelic/NewRelicInsightsApiClientProvider.java index 2451945b26..d3135e20eb 100644 --- a/implementations/micrometer-registry-new-relic/src/main/java/io/micrometer/newrelic/NewRelicInsightsApiClientProvider.java +++ b/implementations/micrometer-registry-new-relic/src/main/java/io/micrometer/newrelic/NewRelicInsightsApiClientProvider.java @@ -163,8 +163,8 @@ public Stream writeTimeGauge(TimeGauge gauge) { @Override public Stream writeSummary(DistributionSummary summary) { return Stream - .of(event(summary.getId(), new Attribute(COUNT, summary.count()), new Attribute(AVG, summary.mean()), - new Attribute(TOTAL, summary.totalAmount()), new Attribute(MAX, summary.max()))); + .of(event(summary.getId(), new Attribute(COUNT, summary.count()), new Attribute(AVG, summary.mean()), + new Attribute(TOTAL, summary.totalAmount()), new Attribute(MAX, summary.max()))); } @Override @@ -223,34 +223,43 @@ private String event(Meter.Id id, Iterable extraTags, Attribute... attribut StringBuilder tagsJson = new StringBuilder(); for (Tag tag : id.getConventionTags(namingConvention)) { - tagsJson.append(",\"").append(escapeJson(tag.getKey())).append("\":\"").append(escapeJson(tag.getValue())) - .append("\""); + tagsJson.append(",\"") + .append(escapeJson(tag.getKey())) + .append("\":\"") + .append(escapeJson(tag.getValue())) + .append("\""); } for (Tag tag : extraTags) { - tagsJson.append(",\"").append(escapeJson(namingConvention.tagKey(tag.getKey()))).append("\":\"") - .append(escapeJson(namingConvention.tagValue(tag.getValue()))).append("\""); + tagsJson.append(",\"") + .append(escapeJson(namingConvention.tagKey(tag.getKey()))) + .append("\":\"") + .append(escapeJson(namingConvention.tagValue(tag.getValue()))) + .append("\""); } String eventType = getEventType(id, config, namingConvention); - return Arrays.stream(attributes).map(attr -> (attr.getValue() instanceof Number) - ? ",\"" + attr.getName() + "\":" + DoubleFormat.wholeOrDecimal(((Number) attr.getValue()).doubleValue()) - : ",\"" + attr.getName() + "\":\"" + namingConvention.tagValue(attr.getValue().toString()) + "\"") - .collect(Collectors.joining("", "{\"eventType\":\"" + escapeJson(eventType) + "\"", tagsJson + "}")); + return Arrays.stream(attributes) + .map(attr -> (attr.getValue() instanceof Number) + ? ",\"" + attr.getName() + "\":" + + DoubleFormat.wholeOrDecimal(((Number) attr.getValue()).doubleValue()) + : ",\"" + attr.getName() + "\":\"" + namingConvention.tagValue(attr.getValue().toString()) + "\"") + .collect(Collectors.joining("", "{\"eventType\":\"" + escapeJson(eventType) + "\"", tagsJson + "}")); } void sendEvents(Stream events) { try { AtomicInteger totalEvents = new AtomicInteger(); - httpClient.post(insightsEndpoint).withHeader("X-Insert-Key", config.apiKey()) - .withJsonContent( - events.peek(ev -> totalEvents.incrementAndGet()).collect(Collectors.joining(",", "[", "]"))) - .send() - .onSuccess(response -> logger.debug("successfully sent {} metrics to New Relic.", totalEvents)) - .onError(response -> logger.error("failed to send metrics to new relic: http {} {}", - response.code(), response.body())); + httpClient.post(insightsEndpoint) + .withHeader("X-Insert-Key", config.apiKey()) + .withJsonContent( + events.peek(ev -> totalEvents.incrementAndGet()).collect(Collectors.joining(",", "[", "]"))) + .send() + .onSuccess(response -> logger.debug("successfully sent {} metrics to New Relic.", totalEvents)) + .onError(response -> logger.error("failed to send metrics to new relic: http {} {}", response.code(), + response.body())); } catch (Throwable e) { logger.warn("failed to send metrics to new relic", e); diff --git a/implementations/micrometer-registry-new-relic/src/test/java/io/micrometer/newrelic/NewRelicConfigTest.java b/implementations/micrometer-registry-new-relic/src/test/java/io/micrometer/newrelic/NewRelicConfigTest.java index fe3134c25d..0f467f5407 100644 --- a/implementations/micrometer-registry-new-relic/src/test/java/io/micrometer/newrelic/NewRelicConfigTest.java +++ b/implementations/micrometer-registry-new-relic/src/test/java/io/micrometer/newrelic/NewRelicConfigTest.java @@ -34,7 +34,7 @@ void invalidClientProviderType() { props.put("newrelic.clientProviderType", "bad"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactly("should be one of 'INSIGHTS_API', 'INSIGHTS_AGENT'"); + .containsExactly("should be one of 'INSIGHTS_API', 'INSIGHTS_AGENT'"); } @Test @@ -42,7 +42,7 @@ void requiredConfigForInsightsApi() { props.put("newrelic.clientProviderType", "insights_api"); assertThat(config.validateForInsightsApi().failures().stream().map(Validated.Invalid::getProperty)) - .containsExactlyInAnyOrder("newrelic.apiKey", "newrelic.accountId"); + .containsExactlyInAnyOrder("newrelic.apiKey", "newrelic.accountId"); } @Test diff --git a/implementations/micrometer-registry-new-relic/src/test/java/io/micrometer/newrelic/NewRelicMeterRegistryTest.java b/implementations/micrometer-registry-new-relic/src/test/java/io/micrometer/newrelic/NewRelicMeterRegistryTest.java index ee79b75186..31ebae1885 100644 --- a/implementations/micrometer-registry-new-relic/src/test/java/io/micrometer/newrelic/NewRelicMeterRegistryTest.java +++ b/implementations/micrometer-registry-new-relic/src/test/java/io/micrometer/newrelic/NewRelicMeterRegistryTest.java @@ -273,21 +273,21 @@ void writeGaugeWithTimeGaugeShouldDropInfiniteValues() { private void writeGaugeWithTimeGaugeShouldDropInfiniteValues(NewRelicInsightsApiClientProvider clientProvider) { TimeGauge timeGauge = TimeGauge.builder("my.timeGauge", () -> Double.POSITIVE_INFINITY, TimeUnit.SECONDS) - .register(registry); + .register(registry); assertThat(clientProvider.writeTimeGauge(timeGauge)).isEmpty(); timeGauge = TimeGauge.builder("my.timeGauge", () -> Double.NEGATIVE_INFINITY, TimeUnit.SECONDS) - .register(registry); + .register(registry); assertThat(clientProvider.writeTimeGauge(timeGauge)).isEmpty(); } private void writeGaugeWithTimeGaugeShouldDropInfiniteValues(NewRelicInsightsAgentClientProvider clientProvider) { TimeGauge timeGauge = TimeGauge.builder("my.timeGauge2", () -> Double.POSITIVE_INFINITY, TimeUnit.SECONDS) - .register(registry); + .register(registry); assertThat(clientProvider.writeTimeGauge(timeGauge)).isEmpty(); timeGauge = TimeGauge.builder("my.timeGauge2", () -> Double.NEGATIVE_INFINITY, TimeUnit.SECONDS) - .register(registry); + .register(registry); assertThat(clientProvider.writeTimeGauge(timeGauge)).isEmpty(); } @@ -337,12 +337,12 @@ void writeCounterWithFunctionCounterShouldDropInfiniteValues() { private void writeCounterWithFunctionCounterShouldDropInfiniteValues( NewRelicInsightsApiClientProvider clientProvider) { FunctionCounter counter = FunctionCounter.builder("myCounter", Double.POSITIVE_INFINITY, Number::doubleValue) - .register(registry); + .register(registry); clock.add(insightsApiConfig.step()); assertThat(clientProvider.writeFunctionCounter(counter)).isEmpty(); counter = FunctionCounter.builder("myCounter", Double.NEGATIVE_INFINITY, Number::doubleValue) - .register(registry); + .register(registry); clock.add(insightsApiConfig.step()); assertThat(clientProvider.writeFunctionCounter(counter)).isEmpty(); } @@ -350,12 +350,12 @@ private void writeCounterWithFunctionCounterShouldDropInfiniteValues( private void writeCounterWithFunctionCounterShouldDropInfiniteValues( NewRelicInsightsAgentClientProvider clientProvider) { FunctionCounter counter = FunctionCounter.builder("myCounter", Double.POSITIVE_INFINITY, Number::doubleValue) - .register(registry); + .register(registry); clock.add(insightsAgentConfig.step()); assertThat(clientProvider.writeFunctionCounter(counter)).isEmpty(); counter = FunctionCounter.builder("myCounter", Double.NEGATIVE_INFINITY, Number::doubleValue) - .register(registry); + .register(registry); clock.add(insightsAgentConfig.step()); assertThat(clientProvider.writeFunctionCounter(counter)).isEmpty(); } @@ -625,7 +625,7 @@ void sendEventsWithApiProvider() { apiProvider.sendEvents(apiProvider.writeGauge(gauge)); assertThat(new String(mockHttpClient.getRequest().getEntity())) - .contains("{\"eventType\":\"myGauge2\",\"value\":1}"); + .contains("{\"eventType\":\"myGauge2\",\"value\":1}"); } @Test @@ -642,9 +642,9 @@ void sendEventsWithAgentProvider() { agentProvider.sendEvents(gauge.getId(), agentProvider.writeGauge(gauge)); assertThat(((MockNewRelicInsights) mockNewRelicAgent.getInsights()).getInsightData().getEventType()) - .isEqualTo("MicrometerSample"); + .isEqualTo("MicrometerSample"); assertThat(((MockNewRelicInsights) mockNewRelicAgent.getInsights()).getInsightData().getAttributes()) - .hasSize(3); + .hasSize(3); // test meterNameEventTypeEnabledConfig = true mockNewRelicAgent = new MockNewRelicAgent(); @@ -656,9 +656,9 @@ void sendEventsWithAgentProvider() { agentProvider.sendEvents(gauge.getId(), agentProvider.writeGauge(gauge)); assertThat(((MockNewRelicInsights) mockNewRelicAgent.getInsights()).getInsightData().getEventType()) - .isEqualTo("myGauge2"); + .isEqualTo("myGauge2"); assertThat(((MockNewRelicInsights) mockNewRelicAgent.getInsights()).getInsightData().getAttributes()) - .hasSize(1); + .hasSize(1); } @Test @@ -703,9 +703,9 @@ void publishWithAgentClientProvider() { // should delegate to the Agent one at a time assertThat(((MockNewRelicInsights) mockNewRelicAgent.getInsights()).getInsightData().getEventType()) - .isEqualTo("MicrometerSample"); + .isEqualTo("MicrometerSample"); assertThat(((MockNewRelicInsights) mockNewRelicAgent.getInsights()).getInsightData().getAttributes()) - .hasSize(4); + .hasSize(4); } @Test @@ -724,7 +724,7 @@ void succeedsConfigInsightsApiClientProviderAndDefaultNamingConvention() { assertThat(registry.clientProvider).isInstanceOf(NewRelicInsightsApiClientProvider.class); assertThat(((NewRelicInsightsApiClientProvider) registry.clientProvider).namingConvention) - .isInstanceOf(NewRelicNamingConvention.class); + .isInstanceOf(NewRelicNamingConvention.class); assertThat(registry.config().namingConvention()).isInstanceOf(NewRelicNamingConvention.class); } @@ -738,7 +738,7 @@ void succeedsConfigInsightsApiClientProviderAndCustomNamingConvention() { assertThat(registry.clientProvider).isInstanceOf(NewRelicInsightsApiClientProvider.class); assertThat(((NewRelicInsightsApiClientProvider) registry.clientProvider).namingConvention) - .isSameAs(customNamingConvention); + .isSameAs(customNamingConvention); assertThat(registry.config().namingConvention()).isSameAs(customNamingConvention); } @@ -749,7 +749,7 @@ void succeedsConfigInsightsAgentClientProviderAndDefaultNamingConvention() { assertThat(registry.clientProvider).isInstanceOf(NewRelicInsightsAgentClientProvider.class); assertThat(((NewRelicInsightsAgentClientProvider) registry.clientProvider).namingConvention) - .isInstanceOf(NewRelicNamingConvention.class); + .isInstanceOf(NewRelicNamingConvention.class); assertThat(registry.config().namingConvention()).isInstanceOf(NewRelicNamingConvention.class); } @@ -763,7 +763,7 @@ void succeedsConfigInsightsAgentClientProviderAndCustomNamingConvention() { assertThat(registry.clientProvider).isInstanceOf(NewRelicInsightsAgentClientProvider.class); assertThat(((NewRelicInsightsAgentClientProvider) registry.clientProvider).namingConvention) - .isSameAs(customNamingConvention); + .isSameAs(customNamingConvention); assertThat(registry.config().namingConvention()).isSameAs(customNamingConvention); } @@ -782,7 +782,7 @@ public String get(String key) { }; assertThatThrownBy(() -> getInsightsApiClientProvider(config)).isExactlyInstanceOf(ValidationException.class) - .hasMessageContaining("eventType"); + .hasMessageContaining("eventType"); } @Test @@ -837,7 +837,7 @@ public String get(String key) { }; assertThatThrownBy(() -> getInsightsApiClientProvider(config)).isExactlyInstanceOf(ValidationException.class) - .hasMessageContaining("accountId"); + .hasMessageContaining("accountId"); } @Test @@ -865,7 +865,7 @@ public String get(String key) { }; assertThatThrownBy(() -> getInsightsApiClientProvider(config)).isExactlyInstanceOf(ValidationException.class) - .hasMessageContaining("apiKey"); + .hasMessageContaining("apiKey"); } @Test @@ -898,7 +898,7 @@ public String get(String key) { }; assertThatThrownBy(() -> getInsightsApiClientProvider(config)).isExactlyInstanceOf(ValidationException.class) - .hasMessageContaining("uri"); + .hasMessageContaining("uri"); } @Test @@ -916,7 +916,7 @@ public String get(String key) { }; assertThatThrownBy(() -> getInsightsAgentClientProvider(config)).isExactlyInstanceOf(ValidationException.class) - .hasMessageContaining("eventType"); + .hasMessageContaining("eventType"); } @Test @@ -951,8 +951,9 @@ public ClientProviderType clientProviderType() { @Test void canCustomizeHttpSenderViaBuilder_deprecated() { HttpSender httpSender = mock(HttpSender.class); - NewRelicClientProvider clientProvider = NewRelicMeterRegistry.builder(insightsApiConfig).httpClient(httpSender) - .build().clientProvider; + NewRelicClientProvider clientProvider = NewRelicMeterRegistry.builder(insightsApiConfig) + .httpClient(httpSender) + .build().clientProvider; assertThat(clientProvider).isInstanceOf(NewRelicInsightsApiClientProvider.class); assertThat(((NewRelicInsightsApiClientProvider) clientProvider).httpClient).isEqualTo(httpSender); } @@ -960,9 +961,10 @@ void canCustomizeHttpSenderViaBuilder_deprecated() { @Test void canCustomizeHttpSenderViaBuilder() { HttpSender httpSender = mock(HttpSender.class); - NewRelicClientProvider clientProvider = NewRelicMeterRegistry.builder(insightsApiConfig).clientProvider( - new NewRelicInsightsApiClientProvider(insightsApiConfig, httpSender, new NewRelicNamingConvention())) - .build().clientProvider; + NewRelicClientProvider clientProvider = NewRelicMeterRegistry.builder(insightsApiConfig) + .clientProvider(new NewRelicInsightsApiClientProvider(insightsApiConfig, httpSender, + new NewRelicNamingConvention())) + .build().clientProvider; assertThat(clientProvider).isInstanceOf(NewRelicInsightsApiClientProvider.class); assertThat(((NewRelicInsightsApiClientProvider) clientProvider).httpClient).isEqualTo(httpSender); } @@ -972,25 +974,28 @@ void canChangeNamingConventionThroughConfig() { NamingConvention namingConvention1 = mock(NamingConvention.class); NamingConvention namingConvention2 = mock(NamingConvention.class); NewRelicMeterRegistry meterRegistry = NewRelicMeterRegistry.builder(insightsApiConfig) - .namingConvention(namingConvention1).build(); + .namingConvention(namingConvention1) + .build(); assertThat(meterRegistry.config().namingConvention()).isEqualTo(namingConvention1); assertThat(meterRegistry.clientProvider).isInstanceOf(NewRelicInsightsApiClientProvider.class); assertThat(((NewRelicInsightsApiClientProvider) meterRegistry.clientProvider).namingConvention) - .isEqualTo(namingConvention1); + .isEqualTo(namingConvention1); meterRegistry.config().namingConvention(namingConvention2); assertThat(meterRegistry.config().namingConvention()).isEqualTo(namingConvention2); assertThat(((NewRelicInsightsApiClientProvider) meterRegistry.clientProvider).namingConvention) - .isEqualTo(namingConvention2); + .isEqualTo(namingConvention2); } @SuppressWarnings("deprecation") @Test void builderBuildWhenBothHttpClientAndClientProviderAreSetShouldThrowIllegalStateException() { NewRelicConfig config = key -> null; - assertThatIllegalStateException().isThrownBy(() -> new NewRelicMeterRegistry.Builder(config) - .httpClient(mock(HttpSender.class)).clientProvider(mock(NewRelicClientProvider.class)).build()); + assertThatIllegalStateException() + .isThrownBy(() -> new NewRelicMeterRegistry.Builder(config).httpClient(mock(HttpSender.class)) + .clientProvider(mock(NewRelicClientProvider.class)) + .build()); } static class MockHttpSender implements HttpSender { diff --git a/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBDistributionSummary.java b/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBDistributionSummary.java index 7b4b54b8c2..41c90ffd14 100644 --- a/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBDistributionSummary.java +++ b/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBDistributionSummary.java @@ -46,19 +46,27 @@ public class OpenTSDBDistributionSummary extends AbstractDistributionSummary { OpenTSDBDistributionSummary(Id id, Clock clock, DistributionStatisticConfig distributionStatisticConfig, double scale, @Nullable OpenTSDBFlavor flavor) { - super(id, clock, DistributionStatisticConfig.builder().percentilesHistogram(false).serviceLevelObjectives() - .build().merge(distributionStatisticConfig), scale, false); + super(id, clock, + DistributionStatisticConfig.builder() + .percentilesHistogram(false) + .serviceLevelObjectives() + .build() + .merge(distributionStatisticConfig), + scale, false); this.max = new TimeWindowMax(clock, distributionStatisticConfig); if (distributionStatisticConfig.isPublishingHistogram()) { if (flavor == null) { histogram = new TimeWindowFixedBoundaryHistogram(clock, - DistributionStatisticConfig.builder().expiry(Duration.ofDays(1825)) // effectively - // never - // roll - // over - .bufferLength(1).build().merge(distributionStatisticConfig), + DistributionStatisticConfig.builder() + .expiry(Duration.ofDays(1825)) // effectively + // never + // roll + // over + .bufferLength(1) + .build() + .merge(distributionStatisticConfig), true); } else if (OpenTSDBFlavor.VictoriaMetrics.equals(flavor)) { diff --git a/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBMeterRegistry.java b/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBMeterRegistry.java index de5d316038..2fb554fea8 100644 --- a/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBMeterRegistry.java +++ b/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBMeterRegistry.java @@ -155,23 +155,27 @@ protected TimeUnit getBaseTimeUnit() { @Override protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.builder().expiry(config.step()).build() - .merge(DistributionStatisticConfig.DEFAULT); + return DistributionStatisticConfig.builder() + .expiry(config.step()) + .build() + .merge(DistributionStatisticConfig.DEFAULT); } @Override protected void publish() { for (List batch : MeterPartition.partition(this, config.batchSize())) { try { - httpClient.post(config.uri()).withBasicAuthentication(config.userName(), config.password()) - .withJsonContent(batch.stream() - .flatMap(m -> m.match(this::writeGauge, this::writeCounter, this::writeTimer, - this::writeSummary, this::writeLongTaskTimer, this::writeTimeGauge, - this::writeFunctionCounter, this::writeFunctionTimer, this::writeCustomMetric)) - .collect(Collectors.joining(",", "[", "]"))) - .compress().send() - .onSuccess(response -> logger.debug("successfully sent {} metrics to opentsdb.", batch.size())) - .onError(response -> logger.error("failed to send metrics to opentsdb: {}", response.body())); + httpClient.post(config.uri()) + .withBasicAuthentication(config.userName(), config.password()) + .withJsonContent(batch.stream() + .flatMap(m -> m.match(this::writeGauge, this::writeCounter, this::writeTimer, + this::writeSummary, this::writeLongTaskTimer, this::writeTimeGauge, + this::writeFunctionCounter, this::writeFunctionTimer, this::writeCustomMetric)) + .collect(Collectors.joining(",", "[", "]"))) + .compress() + .send() + .onSuccess(response -> logger.debug("successfully sent {} metrics to opentsdb.", batch.size())) + .onError(response -> logger.error("failed to send metrics to opentsdb: {}", response.body())); } catch (Throwable t) { logger.warn("failed to send metrics to opentsdb", t); @@ -244,9 +248,9 @@ private List writePercentiles(Meter meter, long wallTime, ValueAtPercent boolean forTimer = meter instanceof Timer; // satisfies https://prometheus.io/docs/concepts/metric_types/#summary for (ValueAtPercentile v : percentileValues) { - metrics.add( - writeMetric(meter.getId().withTag(new ImmutableTag("quantile", doubleToGoString(v.percentile()))), - wallTime, (forTimer ? v.value(getBaseTimeUnit()) : v.value()))); + metrics + .add(writeMetric(meter.getId().withTag(new ImmutableTag("quantile", doubleToGoString(v.percentile()))), + wallTime, (forTimer ? v.value(getBaseTimeUnit()) : v.value()))); } return metrics; @@ -263,8 +267,8 @@ private List writeHistogram(long wallTime, Meter meter, CountAtBucket[] for (CountAtBucket c : histogramCounts) { metrics.add(writeMetricWithSuffix( meter.getId() - .withTag(new ImmutableTag("le", - doubleToGoString(timeUnit == null ? c.bucket() : c.bucket(timeUnit)))), + .withTag(new ImmutableTag("le", + doubleToGoString(timeUnit == null ? c.bucket() : c.bucket(timeUnit)))), "bucket", wallTime, c.count())); } @@ -276,8 +280,8 @@ else if (OpenTSDBFlavor.VictoriaMetrics.equals(config.flavor())) { for (CountAtBucket c : histogramCounts) { metrics.add(writeMetricWithSuffix( meter.getId() - .withTag(Tag.of("vmrange", - getRangeTagValue(timeUnit == null ? c.bucket() : c.bucket(timeUnit)))), + .withTag(Tag.of("vmrange", + getRangeTagValue(timeUnit == null ? c.bucket() : c.bucket(timeUnit)))), "bucket", wallTime, c.count())); } } @@ -366,8 +370,10 @@ private Stream writeCustomMetric(Meter meter) { break; } - return new OpenTSDBMetricBuilder().field("metric", name).datapoints(wallTime, ms.getValue()).tags(localTags) - .build(); + return new OpenTSDBMetricBuilder().field("metric", name) + .datapoints(wallTime, ms.getValue()) + .tags(localTags) + .build(); }); } @@ -375,10 +381,12 @@ String writeMetricWithSuffix(Meter.Id id, String suffix, long wallTime, double v // usually tagKeys and metricNames naming rules are the same // but we can't call getConventionName again after adding suffix return new OpenTSDBMetricBuilder() - .field("metric", - suffix.isEmpty() ? getConventionName(id) - : config().namingConvention().tagKey(getConventionName(id) + "." + suffix)) - .datapoints(wallTime, value).tags(getConventionTags(id)).build(); + .field("metric", + suffix.isEmpty() ? getConventionName(id) + : config().namingConvention().tagKey(getConventionName(id) + "." + suffix)) + .datapoints(wallTime, value) + .tags(getConventionTags(id)) + .build(); } String writeMetric(Meter.Id id, long wallTime, double value) { @@ -398,8 +406,10 @@ OpenTSDBMetricBuilder field(String key, String value) { } OpenTSDBMetricBuilder datapoints(long wallTime, double value) { - sb.append(",\"timestamp\":").append(wallTime).append(",\"value\":") - .append(DoubleFormat.wholeOrDecimal(value)); + sb.append(",\"timestamp\":") + .append(wallTime) + .append(",\"value\":") + .append(DoubleFormat.wholeOrDecimal(value)); return this; } diff --git a/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBTimer.java b/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBTimer.java index e136e7f85a..17e6d9eacf 100644 --- a/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBTimer.java +++ b/implementations/micrometer-registry-opentsdb/src/main/java/io/micrometer/opentsdb/OpenTSDBTimer.java @@ -48,19 +48,27 @@ public class OpenTSDBTimer extends AbstractTimer { OpenTSDBTimer(Id id, Clock clock, DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetector, @Nullable OpenTSDBFlavor flavor) { - super(id, clock, DistributionStatisticConfig.builder().percentilesHistogram(false).serviceLevelObjectives() - .build().merge(distributionStatisticConfig), pauseDetector, TimeUnit.SECONDS, false); + super(id, clock, + DistributionStatisticConfig.builder() + .percentilesHistogram(false) + .serviceLevelObjectives() + .build() + .merge(distributionStatisticConfig), + pauseDetector, TimeUnit.SECONDS, false); this.max = new TimeWindowMax(clock, distributionStatisticConfig); if (distributionStatisticConfig.isPublishingHistogram()) { if (flavor == null) { histogram = new TimeWindowFixedBoundaryHistogram(clock, - DistributionStatisticConfig.builder().expiry(Duration.ofDays(1825)) // effectively - // never - // roll - // over - .bufferLength(1).build().merge(distributionStatisticConfig), + DistributionStatisticConfig.builder() + .expiry(Duration.ofDays(1825)) // effectively + // never + // roll + // over + .bufferLength(1) + .build() + .merge(distributionStatisticConfig), true); } else if (OpenTSDBFlavor.VictoriaMetrics.equals(flavor)) { diff --git a/implementations/micrometer-registry-opentsdb/src/test/java/io/micrometer/opentsdb/OpenTSDBConfigTest.java b/implementations/micrometer-registry-opentsdb/src/test/java/io/micrometer/opentsdb/OpenTSDBConfigTest.java index 2bd02cc70b..023bd446bc 100644 --- a/implementations/micrometer-registry-opentsdb/src/test/java/io/micrometer/opentsdb/OpenTSDBConfigTest.java +++ b/implementations/micrometer-registry-opentsdb/src/test/java/io/micrometer/opentsdb/OpenTSDBConfigTest.java @@ -35,7 +35,7 @@ void invalid() { props.put("opentsdb.flavor", "bad"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactlyInAnyOrder("must be a valid URL", "should be one of 'VictoriaMetrics'"); + .containsExactlyInAnyOrder("must be a valid URL", "should be one of 'VictoriaMetrics'"); } @Test diff --git a/implementations/micrometer-registry-opentsdb/src/test/java/io/micrometer/opentsdb/OpenTSDBMeterRegistryTest.java b/implementations/micrometer-registry-opentsdb/src/test/java/io/micrometer/opentsdb/OpenTSDBMeterRegistryTest.java index d992b0f631..3c1065a4c9 100644 --- a/implementations/micrometer-registry-opentsdb/src/test/java/io/micrometer/opentsdb/OpenTSDBMeterRegistryTest.java +++ b/implementations/micrometer-registry-opentsdb/src/test/java/io/micrometer/opentsdb/OpenTSDBMeterRegistryTest.java @@ -90,7 +90,7 @@ void writeTimeGaugeShouldDropInfiniteValues() { @Test void writeFunctionCounter() { FunctionCounter counter = FunctionCounter.builder("my.counter", 1d, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter)).hasSize(1); } @@ -98,12 +98,12 @@ void writeFunctionCounter() { @Test void writeFunctionCounterShouldDropInfiniteValues() { FunctionCounter counter = FunctionCounter.builder("my.counter", Double.POSITIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter)).isEmpty(); counter = FunctionCounter.builder("my.counter", Double.NEGATIVE_INFINITY, Number::doubleValue) - .register(meterRegistry); + .register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter)).isEmpty(); } @@ -111,16 +111,18 @@ void writeFunctionCounterShouldDropInfiniteValues() { @Issue("#2060") @Test void histogramBucketsHaveCorrectBaseUnit() { - Timer timer = Timer.builder("my.timer").publishPercentileHistogram() - .serviceLevelObjectives(Duration.ofMillis(900), Duration.ofSeconds(1)).register(meterRegistry); + Timer timer = Timer.builder("my.timer") + .publishPercentileHistogram() + .serviceLevelObjectives(Duration.ofMillis(900), Duration.ofSeconds(1)) + .register(meterRegistry); timer.record(1, TimeUnit.SECONDS); clock.add(config.step()); assertThat(meterRegistry.writeTimer(timer)).contains( "{\"metric\":\"my_timer_duration_seconds_bucket\",\"timestamp\":60001,\"value\":1,\"tags\":{\"le\":\"1.0\"}}") - .contains( - "{\"metric\":\"my_timer_duration_seconds_bucket\",\"timestamp\":60001,\"value\":0,\"tags\":{\"le\":\"0.9\"}}"); + .contains( + "{\"metric\":\"my_timer_duration_seconds_bucket\",\"timestamp\":60001,\"value\":0,\"tags\":{\"le\":\"0.9\"}}"); } @Test @@ -130,10 +132,10 @@ void longTaskTimer() { assertThat(meterRegistry.writeLongTaskTimer(timer)).contains( "{\"metric\":\"my_timer_duration_seconds_active_count\",\"timestamp\":1,\"value\":0,\"tags\":{\"tag\":\"value\"}}") - .contains( - "{\"metric\":\"my_timer_duration_seconds_duration_sum\",\"timestamp\":1,\"value\":0,\"tags\":{\"tag\":\"value\"}}") - .contains( - "{\"metric\":\"my_timer_duration_seconds_max\",\"timestamp\":1,\"value\":0,\"tags\":{\"tag\":\"value\"}}"); + .contains( + "{\"metric\":\"my_timer_duration_seconds_duration_sum\",\"timestamp\":1,\"value\":0,\"tags\":{\"tag\":\"value\"}}") + .contains( + "{\"metric\":\"my_timer_duration_seconds_max\",\"timestamp\":1,\"value\":0,\"tags\":{\"tag\":\"value\"}}"); } } diff --git a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpConfig.java b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpConfig.java index 81ba7be848..ea676bd945 100644 --- a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpConfig.java +++ b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpConfig.java @@ -70,14 +70,15 @@ default String url() { default Map resourceAttributes() { Map env = System.getenv(); String resourceAttributesConfig = getString(this, "resourceAttributes") - .orElse(env.get("OTEL_RESOURCE_ATTRIBUTES")); + .orElse(env.get("OTEL_RESOURCE_ATTRIBUTES")); String[] splitResourceAttributesString = resourceAttributesConfig == null ? new String[] {} : resourceAttributesConfig.trim().split(","); - Map resourceAttributes = Arrays.stream(splitResourceAttributesString).map(String::trim) - .filter(keyValue -> keyValue.length() > 2 && keyValue.indexOf('=') > 0) - .collect(Collectors.toMap(keyvalue -> keyvalue.substring(0, keyvalue.indexOf('=')).trim(), - keyValue -> keyValue.substring(keyValue.indexOf('=') + 1).trim())); + Map resourceAttributes = Arrays.stream(splitResourceAttributesString) + .map(String::trim) + .filter(keyValue -> keyValue.length() > 2 && keyValue.indexOf('=') > 0) + .collect(Collectors.toMap(keyvalue -> keyvalue.substring(0, keyvalue.indexOf('=')).trim(), + keyValue -> keyValue.substring(keyValue.indexOf('=') + 1).trim())); if (env.containsKey("OTEL_SERVICE_NAME") && !resourceAttributes.containsKey("service.name")) { resourceAttributes.put("service.name", env.get("OTEL_SERVICE_NAME")); diff --git a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpDistributionSummary.java b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpDistributionSummary.java index 49950ec5ab..1d03d14cce 100644 --- a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpDistributionSummary.java +++ b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpDistributionSummary.java @@ -34,17 +34,19 @@ class OtlpDistributionSummary extends CumulativeDistributionSummary implements S OtlpDistributionSummary(Id id, Clock clock, DistributionStatisticConfig distributionStatisticConfig, double scale, boolean supportsAggregablePercentiles) { - super(id, clock, DistributionStatisticConfig.builder().percentilesHistogram(false) // avoid - // a - // histogram - // for - // percentiles/SLOs - // in - // the - // super - .serviceLevelObjectives() // we will use a different implementation here - // instead - .build().merge(distributionStatisticConfig), scale, false); + super(id, clock, DistributionStatisticConfig.builder() + .percentilesHistogram(false) // avoid + // a + // histogram + // for + // percentiles/SLOs + // in + // the + // super + .serviceLevelObjectives() // we will use a different implementation here + // instead + .build() + .merge(distributionStatisticConfig), scale, false); this.startTimeNanos = TimeUnit.MILLISECONDS.toNanos(clock.wallTime()); // CumulativeDistributionSummary doesn't produce monotonic histogram counts; maybe // it should @@ -52,11 +54,14 @@ class OtlpDistributionSummary extends CumulativeDistributionSummary implements S // counts across buckets if (distributionStatisticConfig.isPublishingHistogram()) { this.monotonicBucketCountHistogram = new TimeWindowFixedBoundaryHistogram(clock, - DistributionStatisticConfig.builder().expiry(Duration.ofDays(1825)) // effectively - // never - // roll - // over - .bufferLength(1).build().merge(distributionStatisticConfig), + DistributionStatisticConfig.builder() + .expiry(Duration.ofDays(1825)) // effectively + // never + // roll + // over + .bufferLength(1) + .build() + .merge(distributionStatisticConfig), true, false); } else { diff --git a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpFunctionCounter.java b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpFunctionCounter.java index acf6358faf..3e7841e34a 100644 --- a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpFunctionCounter.java +++ b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpFunctionCounter.java @@ -21,7 +21,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; -class OtlpFunctionCounter extends CumulativeFunctionCounter implements StartTimeAwareMeter { +class OtlpFunctionCounterextends CumulativeFunctionCounter implements StartTimeAwareMeter { private final long startTimeNanos; diff --git a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpFunctionTimer.java b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpFunctionTimer.java index feb3a3745a..2088fa5f5a 100644 --- a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpFunctionTimer.java +++ b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpFunctionTimer.java @@ -22,7 +22,7 @@ import java.util.function.ToDoubleFunction; import java.util.function.ToLongFunction; -class OtlpFunctionTimer extends CumulativeFunctionTimer implements StartTimeAwareMeter { +class OtlpFunctionTimerextends CumulativeFunctionTimer implements StartTimeAwareMeter { private final long startTimeNanos; diff --git a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpMeterRegistry.java b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpMeterRegistry.java index 29d627480b..1fb0e2bc8a 100644 --- a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpMeterRegistry.java +++ b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpMeterRegistry.java @@ -90,23 +90,26 @@ private OtlpMeterRegistry(OtlpConfig config, Clock clock, HttpSender httpSender) protected void publish() { for (List batch : MeterPartition.partition(this, config.batchSize())) { List metrics = batch.stream() - .map(meter -> meter.match(this::writeGauge, this::writeCounter, this::writeHistogramSupport, - this::writeHistogramSupport, this::writeHistogramSupport, this::writeGauge, - this::writeFunctionCounter, this::writeFunctionTimer, this::writeMeter)) - .collect(Collectors.toList()); + .map(meter -> meter.match(this::writeGauge, this::writeCounter, this::writeHistogramSupport, + this::writeHistogramSupport, this::writeHistogramSupport, this::writeGauge, + this::writeFunctionCounter, this::writeFunctionTimer, this::writeMeter)) + .collect(Collectors.toList()); try { ExportMetricsServiceRequest request = ExportMetricsServiceRequest.newBuilder() - .addResourceMetrics(ResourceMetrics.newBuilder().setResource(this.resource) - .addScopeMetrics(ScopeMetrics.newBuilder() - // we don't have instrumentation library/version - // attached to meters; leave unknown for now - // .setScope(InstrumentationScope.newBuilder().setName("").setVersion("").build()) - .addAllMetrics(metrics).build()) - .build()) - .build(); - this.httpSender.post(this.config.url()).withContent("application/x-protobuf", request.toByteArray()) - .send(); + .addResourceMetrics(ResourceMetrics.newBuilder() + .setResource(this.resource) + .addScopeMetrics(ScopeMetrics.newBuilder() + // we don't have instrumentation library/version + // attached to meters; leave unknown for now + // .setScope(InstrumentationScope.newBuilder().setName("").setVersion("").build()) + .addAllMetrics(metrics) + .build()) + .build()) + .build(); + this.httpSender.post(this.config.url()) + .withContent("application/x-protobuf", request.toByteArray()) + .send(); } catch (Throwable e) { logger.warn("Failed to publish metrics to OTLP receiver", e); @@ -165,8 +168,10 @@ protected TimeUnit getBaseTimeUnit() { @Override protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.builder().expiry(this.config.step()).build() - .merge(DistributionStatisticConfig.DEFAULT); + return DistributionStatisticConfig.builder() + .expiry(this.config.step()) + .build() + .merge(DistributionStatisticConfig.DEFAULT); } private Metric writeMeter(Meter meter) { @@ -178,11 +183,13 @@ private Metric writeMeter(Meter meter) { // VisibleForTesting Metric writeGauge(Gauge gauge) { return getMetricBuilder(gauge.getId()) - .setGauge(io.opentelemetry.proto.metrics.v1.Gauge.newBuilder() - .addDataPoints(NumberDataPoint.newBuilder() - .setTimeUnixNano(TimeUnit.MILLISECONDS.toNanos(this.clock.wallTime())) - .setAsDouble(gauge.value()).addAllAttributes(getTagsForId(gauge.getId())).build())) - .build(); + .setGauge(io.opentelemetry.proto.metrics.v1.Gauge.newBuilder() + .addDataPoints(NumberDataPoint.newBuilder() + .setTimeUnixNano(TimeUnit.MILLISECONDS.toNanos(this.clock.wallTime())) + .setAsDouble(gauge.value()) + .addAllAttributes(getTagsForId(gauge.getId())) + .build())) + .build(); } // VisibleForTesting @@ -197,13 +204,17 @@ Metric writeFunctionCounter(FunctionCounter functionCounter) { private Metric writeSum(StartTimeAwareMeter meter, DoubleSupplier count) { return getMetricBuilder(meter.getId()) - .setSum(Sum.newBuilder() - .addDataPoints(NumberDataPoint.newBuilder().setStartTimeUnixNano(meter.getStartTimeNanos()) - .setTimeUnixNano(TimeUnit.MILLISECONDS.toNanos(this.clock.wallTime())) - .setAsDouble(count.getAsDouble()).addAllAttributes(getTagsForId(meter.getId())).build()) - .setIsMonotonic(true) - .setAggregationTemporality(AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE).build()) - .build(); + .setSum(Sum.newBuilder() + .addDataPoints(NumberDataPoint.newBuilder() + .setStartTimeUnixNano(meter.getStartTimeNanos()) + .setTimeUnixNano(TimeUnit.MILLISECONDS.toNanos(this.clock.wallTime())) + .setAsDouble(count.getAsDouble()) + .addAllAttributes(getTagsForId(meter.getId())) + .build()) + .setIsMonotonic(true) + .setAggregationTemporality(AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE) + .build()) + .build(); } // VisibleForTesting @@ -220,46 +231,59 @@ Metric writeHistogramSupport(HistogramSupport histogramSupport) { // if percentiles configured, use summary if (histogramSnapshot.percentileValues().length != 0) { - SummaryDataPoint.Builder summaryData = SummaryDataPoint.newBuilder().addAllAttributes(tags) - .setStartTimeUnixNano(startTimeNanos).setTimeUnixNano(wallTimeNanos).setSum(total).setCount(count); + SummaryDataPoint.Builder summaryData = SummaryDataPoint.newBuilder() + .addAllAttributes(tags) + .setStartTimeUnixNano(startTimeNanos) + .setTimeUnixNano(wallTimeNanos) + .setSum(total) + .setCount(count); for (ValueAtPercentile percentile : histogramSnapshot.percentileValues()) { - summaryData.addQuantileValues( - SummaryDataPoint.ValueAtQuantile.newBuilder().setQuantile(percentile.percentile()).setValue( - TimeUtils.convert(percentile.value(), TimeUnit.NANOSECONDS, getBaseTimeUnit()))); + summaryData.addQuantileValues(SummaryDataPoint.ValueAtQuantile.newBuilder() + .setQuantile(percentile.percentile()) + .setValue(TimeUtils.convert(percentile.value(), TimeUnit.NANOSECONDS, getBaseTimeUnit()))); } metricBuilder.setSummary(Summary.newBuilder().addDataPoints(summaryData)); return metricBuilder.build(); } - HistogramDataPoint.Builder histogramDataPoint = HistogramDataPoint.newBuilder().addAllAttributes(tags) - .setStartTimeUnixNano(startTimeNanos).setTimeUnixNano(wallTimeNanos).setSum(total).setCount(count); + HistogramDataPoint.Builder histogramDataPoint = HistogramDataPoint.newBuilder() + .addAllAttributes(tags) + .setStartTimeUnixNano(startTimeNanos) + .setTimeUnixNano(wallTimeNanos) + .setSum(total) + .setCount(count); // if histogram enabled, add histogram buckets if (histogramSnapshot.histogramCounts().length != 0) { for (CountAtBucket countAtBucket : histogramSnapshot.histogramCounts()) { - histogramDataPoint.addExplicitBounds( - isTimeBased ? countAtBucket.bucket(getBaseTimeUnit()) : countAtBucket.bucket()); + histogramDataPoint + .addExplicitBounds(isTimeBased ? countAtBucket.bucket(getBaseTimeUnit()) : countAtBucket.bucket()); histogramDataPoint.addBucketCounts((long) countAtBucket.count()); } metricBuilder.setHistogram(Histogram.newBuilder() - .setAggregationTemporality(AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE) - .addDataPoints(histogramDataPoint)); + .setAggregationTemporality(AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE) + .addDataPoints(histogramDataPoint)); return metricBuilder.build(); } - return metricBuilder.setHistogram(Histogram.newBuilder() + return metricBuilder + .setHistogram(Histogram.newBuilder() .setAggregationTemporality(AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE) - .addDataPoints(histogramDataPoint)).build(); + .addDataPoints(histogramDataPoint)) + .build(); } // VisibleForTesting Metric writeFunctionTimer(FunctionTimer functionTimer) { - return getMetricBuilder(functionTimer.getId()).setHistogram(Histogram.newBuilder() - .addDataPoints(HistogramDataPoint.newBuilder().addAllAttributes(getTagsForId(functionTimer.getId())) - .setStartTimeUnixNano(((StartTimeAwareMeter) functionTimer).getStartTimeNanos()) - .setTimeUnixNano(TimeUnit.MILLISECONDS.toNanos(this.clock.wallTime())) - .setSum(functionTimer.totalTime(getBaseTimeUnit())).setCount((long) functionTimer.count()))) - .build(); + return getMetricBuilder(functionTimer.getId()) + .setHistogram(Histogram.newBuilder() + .addDataPoints(HistogramDataPoint.newBuilder() + .addAllAttributes(getTagsForId(functionTimer.getId())) + .setStartTimeUnixNano(((StartTimeAwareMeter) functionTimer).getStartTimeNanos()) + .setTimeUnixNano(TimeUnit.MILLISECONDS.toNanos(this.clock.wallTime())) + .setSum(functionTimer.totalTime(getBaseTimeUnit())) + .setCount((long) functionTimer.count()))) + .build(); } private Metric.Builder getMetricBuilder(Meter.Id id) { @@ -274,8 +298,10 @@ private Metric.Builder getMetricBuilder(Meter.Id id) { } private Iterable getTagsForId(Meter.Id id) { - return id.getTags().stream().map(tag -> createKeyValue(tag.getKey(), tag.getValue())) - .collect(Collectors.toList()); + return id.getTags() + .stream() + .map(tag -> createKeyValue(tag.getKey(), tag.getValue())) + .collect(Collectors.toList()); } // VisibleForTesting diff --git a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpTimer.java b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpTimer.java index ab157e5723..f673d2fb87 100644 --- a/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpTimer.java +++ b/implementations/micrometer-registry-otlp/src/main/java/io/micrometer/registry/otlp/OtlpTimer.java @@ -34,28 +34,33 @@ class OtlpTimer extends CumulativeTimer implements StartTimeAwareMeter { OtlpTimer(Id id, Clock clock, DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetector, TimeUnit baseTimeUnit) { - super(id, clock, DistributionStatisticConfig.builder().percentilesHistogram(false) // avoid - // a - // histogram - // for - // percentiles/SLOs - // in - // the - // super - .serviceLevelObjectives() // we will use a different implementation here - // instead - .build().merge(distributionStatisticConfig), pauseDetector, baseTimeUnit, false); + super(id, clock, DistributionStatisticConfig.builder() + .percentilesHistogram(false) // avoid + // a + // histogram + // for + // percentiles/SLOs + // in + // the + // super + .serviceLevelObjectives() // we will use a different implementation here + // instead + .build() + .merge(distributionStatisticConfig), pauseDetector, baseTimeUnit, false); this.startTimeNanos = TimeUnit.MILLISECONDS.toNanos(clock.wallTime()); // CumulativeTimer doesn't produce monotonic histogram counts; maybe it should // Also, we need to customize the histogram behavior to not return cumulative // counts across buckets if (distributionStatisticConfig.isPublishingHistogram()) { this.monotonicCountBucketHistogram = new TimeWindowFixedBoundaryHistogram(clock, - DistributionStatisticConfig.builder().expiry(Duration.ofDays(1825)) // effectively - // never - // roll - // over - .bufferLength(1).build().merge(distributionStatisticConfig), + DistributionStatisticConfig.builder() + .expiry(Duration.ofDays(1825)) // effectively + // never + // roll + // over + .bufferLength(1) + .build() + .merge(distributionStatisticConfig), true, false); } else { diff --git a/implementations/micrometer-registry-otlp/src/test/java/io/micrometer/registry/otlp/OtlpConfigTest.java b/implementations/micrometer-registry-otlp/src/test/java/io/micrometer/registry/otlp/OtlpConfigTest.java index df8c6818d1..664ae03ac8 100644 --- a/implementations/micrometer-registry-otlp/src/test/java/io/micrometer/registry/otlp/OtlpConfigTest.java +++ b/implementations/micrometer-registry-otlp/src/test/java/io/micrometer/registry/otlp/OtlpConfigTest.java @@ -46,10 +46,12 @@ void resourceAttributesInputParsing() { @Test void resourceAttributesFromEnvironmentVariables() throws Exception { withEnvironmentVariables("OTEL_RESOURCE_ATTRIBUTES", "a=1,b=2", "OTEL_SERVICE_NAME", "my-service") - .execute(() -> { - assertThat(OtlpConfig.DEFAULT.resourceAttributes()).hasSize(3).containsEntry("a", "1") - .containsEntry("b", "2").containsEntry("service.name", "my-service"); - }); + .execute(() -> { + assertThat(OtlpConfig.DEFAULT.resourceAttributes()).hasSize(3) + .containsEntry("a", "1") + .containsEntry("b", "2") + .containsEntry("service.name", "my-service"); + }); } @Test @@ -58,10 +60,11 @@ void resourceAttributesFromGetTakePrecedenceOverOnesFromEnvironmentVariables() t "a=100,service.name=your-service"); OtlpConfig config = map::get; withEnvironmentVariables("OTEL_RESOURCE_ATTRIBUTES", "a=1,b=2", "OTEL_SERVICE_NAME", "my-service") - .execute(() -> { - assertThat(config.resourceAttributes()).hasSize(2).containsEntry("a", "100") - .containsEntry("service.name", "your-service"); - }); + .execute(() -> { + assertThat(config.resourceAttributes()).hasSize(2) + .containsEntry("a", "100") + .containsEntry("service.name", "your-service"); + }); } } diff --git a/implementations/micrometer-registry-otlp/src/test/java/io/micrometer/registry/otlp/OtlpMeterRegistryTest.java b/implementations/micrometer-registry-otlp/src/test/java/io/micrometer/registry/otlp/OtlpMeterRegistryTest.java index edde2319c6..15196abff1 100644 --- a/implementations/micrometer-registry-otlp/src/test/java/io/micrometer/registry/otlp/OtlpMeterRegistryTest.java +++ b/implementations/micrometer-registry-otlp/src/test/java/io/micrometer/registry/otlp/OtlpMeterRegistryTest.java @@ -44,11 +44,13 @@ class OtlpMeterRegistryTest { @Test void gauge() { - Gauge cpus = Gauge.builder("cpus", ManagementFactory.getOperatingSystemMXBean(), - OperatingSystemMXBean::getAvailableProcessors).register(registry); + Gauge cpus = Gauge + .builder("cpus", ManagementFactory.getOperatingSystemMXBean(), + OperatingSystemMXBean::getAvailableProcessors) + .register(registry); assertThat(registry.writeGauge(cpus).toString()) - .matches("name: \"cpus\"\n" + "gauge \\{\n" + " data_points \\{\n" + " time_unix_nano: 1000000\n" - + " as_double: \\d+\\.0\n" + " }\n" + "}\n"); + .matches("name: \"cpus\"\n" + "gauge \\{\n" + " data_points \\{\n" + " time_unix_nano: 1000000\n" + + " as_double: \\d+\\.0\n" + " }\n" + "}\n"); } @Test @@ -56,8 +58,8 @@ void timeGauge() { TimeGauge timeGauge = TimeGauge.builder("gauge.time", this, TimeUnit.MICROSECONDS, o -> 24).register(registry); assertThat(registry.writeGauge(timeGauge).toString()) - .isEqualTo("name: \"gauge.time\"\n" + "unit: \"milliseconds\"\n" + "gauge {\n" + " data_points {\n" - + " time_unix_nano: 1000000\n" + " as_double: 0.024\n" + " }\n" + "}\n"); + .isEqualTo("name: \"gauge.time\"\n" + "unit: \"milliseconds\"\n" + "gauge {\n" + " data_points {\n" + + " time_unix_nano: 1000000\n" + " as_double: 0.024\n" + " }\n" + "}\n"); } @Test @@ -76,9 +78,11 @@ void counter() { @Test void functionCounter() { - FunctionCounter counter = FunctionCounter.builder("jvm.compilation.time", - ManagementFactory.getCompilationMXBean(), CompilationMXBean::getTotalCompilationTime) - .baseUnit("milliseconds").register(registry); + FunctionCounter counter = FunctionCounter + .builder("jvm.compilation.time", ManagementFactory.getCompilationMXBean(), + CompilationMXBean::getTotalCompilationTime) + .baseUnit("milliseconds") + .register(registry); assertThat(registry.writeFunctionCounter(counter).toString()).matches("name: \"jvm.compilation.time\"\n" + "unit: \"milliseconds\"\n" + "sum \\{\n" + " data_points \\{\n" @@ -111,67 +115,67 @@ void timerWithHistogram() { clock.add(OtlpConfig.DEFAULT.step()); timer.record(4, TimeUnit.MILLISECONDS); - assertThat(registry.writeHistogramSupport(timer).toString()).isEqualTo( - "name: \"http.client.requests\"\n" + "unit: \"milliseconds\"\n" + "histogram {\n" + " data_points {\n" - + " start_time_unix_nano: 1000000\n" + " time_unix_nano: 60001000000\n" + " count: 4\n" - + " sum: 202.0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 1\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 1\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 1\n" + " bucket_counts: 1\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" - + " explicit_bounds: 1.0\n" + " explicit_bounds: 1.048576\n" - + " explicit_bounds: 1.398101\n" + " explicit_bounds: 1.747626\n" - + " explicit_bounds: 2.097151\n" + " explicit_bounds: 2.446676\n" - + " explicit_bounds: 2.796201\n" + " explicit_bounds: 3.145726\n" - + " explicit_bounds: 3.495251\n" + " explicit_bounds: 3.844776\n" - + " explicit_bounds: 4.194304\n" + " explicit_bounds: 5.592405\n" - + " explicit_bounds: 6.990506\n" + " explicit_bounds: 8.388607\n" - + " explicit_bounds: 9.786708\n" + " explicit_bounds: 11.184809\n" - + " explicit_bounds: 12.58291\n" + " explicit_bounds: 13.981011\n" - + " explicit_bounds: 15.379112\n" + " explicit_bounds: 16.777216\n" - + " explicit_bounds: 22.369621\n" + " explicit_bounds: 27.962026\n" - + " explicit_bounds: 33.554431\n" + " explicit_bounds: 39.146836\n" - + " explicit_bounds: 44.739241\n" + " explicit_bounds: 50.331646\n" - + " explicit_bounds: 55.924051\n" + " explicit_bounds: 61.516456\n" - + " explicit_bounds: 67.108864\n" + " explicit_bounds: 89.478485\n" - + " explicit_bounds: 111.848106\n" + " explicit_bounds: 134.217727\n" - + " explicit_bounds: 156.587348\n" + " explicit_bounds: 178.956969\n" - + " explicit_bounds: 201.32659\n" + " explicit_bounds: 223.696211\n" - + " explicit_bounds: 246.065832\n" + " explicit_bounds: 268.435456\n" - + " explicit_bounds: 357.913941\n" + " explicit_bounds: 447.392426\n" - + " explicit_bounds: 536.870911\n" + " explicit_bounds: 626.349396\n" - + " explicit_bounds: 715.827881\n" + " explicit_bounds: 805.306366\n" - + " explicit_bounds: 894.784851\n" + " explicit_bounds: 984.263336\n" - + " explicit_bounds: 1073.741824\n" + " explicit_bounds: 1431.655765\n" - + " explicit_bounds: 1789.569706\n" + " explicit_bounds: 2147.483647\n" - + " explicit_bounds: 2505.397588\n" + " explicit_bounds: 2863.311529\n" - + " explicit_bounds: 3221.22547\n" + " explicit_bounds: 3579.139411\n" - + " explicit_bounds: 3937.053352\n" + " explicit_bounds: 4294.967296\n" - + " explicit_bounds: 5726.623061\n" + " explicit_bounds: 7158.278826\n" - + " explicit_bounds: 8589.934591\n" + " explicit_bounds: 10021.590356\n" - + " explicit_bounds: 11453.246121\n" + " explicit_bounds: 12884.901886\n" - + " explicit_bounds: 14316.557651\n" + " explicit_bounds: 15748.213416\n" - + " explicit_bounds: 17179.869184\n" + " explicit_bounds: 22906.492245\n" - + " explicit_bounds: 28633.115306\n" + " explicit_bounds: 30000.0\n" + " }\n" - + " aggregation_temporality: AGGREGATION_TEMPORALITY_CUMULATIVE\n" + "}\n"); + assertThat(registry.writeHistogramSupport(timer).toString()) + .isEqualTo("name: \"http.client.requests\"\n" + "unit: \"milliseconds\"\n" + "histogram {\n" + + " data_points {\n" + " start_time_unix_nano: 1000000\n" + " time_unix_nano: 60001000000\n" + + " count: 4\n" + " sum: 202.0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 1\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 1\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 1\n" + " bucket_counts: 1\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " bucket_counts: 0\n" + " bucket_counts: 0\n" + " bucket_counts: 0\n" + + " explicit_bounds: 1.0\n" + " explicit_bounds: 1.048576\n" + + " explicit_bounds: 1.398101\n" + " explicit_bounds: 1.747626\n" + + " explicit_bounds: 2.097151\n" + " explicit_bounds: 2.446676\n" + + " explicit_bounds: 2.796201\n" + " explicit_bounds: 3.145726\n" + + " explicit_bounds: 3.495251\n" + " explicit_bounds: 3.844776\n" + + " explicit_bounds: 4.194304\n" + " explicit_bounds: 5.592405\n" + + " explicit_bounds: 6.990506\n" + " explicit_bounds: 8.388607\n" + + " explicit_bounds: 9.786708\n" + " explicit_bounds: 11.184809\n" + + " explicit_bounds: 12.58291\n" + " explicit_bounds: 13.981011\n" + + " explicit_bounds: 15.379112\n" + " explicit_bounds: 16.777216\n" + + " explicit_bounds: 22.369621\n" + " explicit_bounds: 27.962026\n" + + " explicit_bounds: 33.554431\n" + " explicit_bounds: 39.146836\n" + + " explicit_bounds: 44.739241\n" + " explicit_bounds: 50.331646\n" + + " explicit_bounds: 55.924051\n" + " explicit_bounds: 61.516456\n" + + " explicit_bounds: 67.108864\n" + " explicit_bounds: 89.478485\n" + + " explicit_bounds: 111.848106\n" + " explicit_bounds: 134.217727\n" + + " explicit_bounds: 156.587348\n" + " explicit_bounds: 178.956969\n" + + " explicit_bounds: 201.32659\n" + " explicit_bounds: 223.696211\n" + + " explicit_bounds: 246.065832\n" + " explicit_bounds: 268.435456\n" + + " explicit_bounds: 357.913941\n" + " explicit_bounds: 447.392426\n" + + " explicit_bounds: 536.870911\n" + " explicit_bounds: 626.349396\n" + + " explicit_bounds: 715.827881\n" + " explicit_bounds: 805.306366\n" + + " explicit_bounds: 894.784851\n" + " explicit_bounds: 984.263336\n" + + " explicit_bounds: 1073.741824\n" + " explicit_bounds: 1431.655765\n" + + " explicit_bounds: 1789.569706\n" + " explicit_bounds: 2147.483647\n" + + " explicit_bounds: 2505.397588\n" + " explicit_bounds: 2863.311529\n" + + " explicit_bounds: 3221.22547\n" + " explicit_bounds: 3579.139411\n" + + " explicit_bounds: 3937.053352\n" + " explicit_bounds: 4294.967296\n" + + " explicit_bounds: 5726.623061\n" + " explicit_bounds: 7158.278826\n" + + " explicit_bounds: 8589.934591\n" + " explicit_bounds: 10021.590356\n" + + " explicit_bounds: 11453.246121\n" + " explicit_bounds: 12884.901886\n" + + " explicit_bounds: 14316.557651\n" + " explicit_bounds: 15748.213416\n" + + " explicit_bounds: 17179.869184\n" + " explicit_bounds: 22906.492245\n" + + " explicit_bounds: 28633.115306\n" + " explicit_bounds: 30000.0\n" + " }\n" + + " aggregation_temporality: AGGREGATION_TEMPORALITY_CUMULATIVE\n" + "}\n"); } @Test @@ -182,29 +186,31 @@ void timerWithPercentiles() { timer.record(111, TimeUnit.MILLISECONDS); assertThat(registry.writeHistogramSupport(timer).toString()) - .isEqualTo("name: \"service.requests\"\n" + "unit: \"milliseconds\"\n" + "summary {\n" - + " data_points {\n" + " start_time_unix_nano: 1000000\n" + " time_unix_nano: 1000000\n" - + " count: 3\n" + " sum: 198.0\n" + " quantile_values {\n" + " quantile: 0.5\n" - + " value: 79.167488\n" + " }\n" + " quantile_values {\n" + " quantile: 0.9\n" - + " value: 112.72192\n" + " }\n" + " quantile_values {\n" + " quantile: 0.99\n" - + " value: 112.72192\n" + " }\n" + " }\n" + "}\n"); + .isEqualTo("name: \"service.requests\"\n" + "unit: \"milliseconds\"\n" + "summary {\n" + " data_points {\n" + + " start_time_unix_nano: 1000000\n" + " time_unix_nano: 1000000\n" + " count: 3\n" + + " sum: 198.0\n" + " quantile_values {\n" + " quantile: 0.5\n" + + " value: 79.167488\n" + " }\n" + " quantile_values {\n" + " quantile: 0.9\n" + + " value: 112.72192\n" + " }\n" + " quantile_values {\n" + " quantile: 0.99\n" + + " value: 112.72192\n" + " }\n" + " }\n" + "}\n"); } @Test void functionTimer() { FunctionTimer functionTimer = FunctionTimer - .builder("function.timer", this, o -> 5, o -> 127, TimeUnit.MILLISECONDS).register(registry); + .builder("function.timer", this, o -> 5, o -> 127, TimeUnit.MILLISECONDS) + .register(registry); assertThat(registry.writeFunctionTimer(functionTimer).toString()) - .isEqualTo("name: \"function.timer\"\n" + "unit: \"milliseconds\"\n" + "histogram {\n" - + " data_points {\n" + " start_time_unix_nano: 1000000\n" + " time_unix_nano: 1000000\n" - + " count: 5\n" + " sum: 127.0\n" + " }\n" + "}\n"); + .isEqualTo("name: \"function.timer\"\n" + "unit: \"milliseconds\"\n" + "histogram {\n" + " data_points {\n" + + " start_time_unix_nano: 1000000\n" + " time_unix_nano: 1000000\n" + " count: 5\n" + + " sum: 127.0\n" + " }\n" + "}\n"); } @Test void distributionSummary() { - DistributionSummary size = DistributionSummary.builder("http.response.size").baseUnit("bytes") - .register(registry); + DistributionSummary size = DistributionSummary.builder("http.response.size") + .baseUnit("bytes") + .register(registry); size.record(100); size.record(15); size.record(2233); @@ -219,8 +225,10 @@ void distributionSummary() { @Test void distributionSummaryWithHistogramBuckets() { - DistributionSummary size = DistributionSummary.builder("http.request.size").baseUnit("bytes") - .publishPercentileHistogram().register(registry); + DistributionSummary size = DistributionSummary.builder("http.request.size") + .baseUnit("bytes") + .publishPercentileHistogram() + .register(registry); size.record(100); size.record(15); size.record(2233); @@ -484,10 +492,10 @@ void longTaskTimer() { this.clock.add(OtlpConfig.DEFAULT.step().multipliedBy(3)); assertThat(registry.writeHistogramSupport(taskTimer).toString()) - .isEqualTo("name: \"checkout.batch\"\n" + "unit: \"milliseconds\"\n" + "histogram {\n" - + " data_points {\n" + " start_time_unix_nano: 1000000\n" - + " time_unix_nano: 180001000000\n" + " count: 2\n" + " sum: 360000.0\n" + " }\n" - + " aggregation_temporality: AGGREGATION_TEMPORALITY_CUMULATIVE\n" + "}\n"); + .isEqualTo("name: \"checkout.batch\"\n" + "unit: \"milliseconds\"\n" + "histogram {\n" + " data_points {\n" + + " start_time_unix_nano: 1000000\n" + " time_unix_nano: 180001000000\n" + " count: 2\n" + + " sum: 360000.0\n" + " }\n" + + " aggregation_temporality: AGGREGATION_TEMPORALITY_CUMULATIVE\n" + "}\n"); task1.stop(); task2.stop(); @@ -495,17 +503,17 @@ void longTaskTimer() { // this is not right that count/sum reset, but it's the same thing we do with // prometheus - assertThat(registry.writeHistogramSupport(taskTimer).toString()).isEqualTo("name: \"checkout.batch\"\n" - + "unit: \"milliseconds\"\n" + "histogram {\n" + " data_points {\n" - + " start_time_unix_nano: 1000000\n" + " time_unix_nano: 240001000000\n" + " sum: 0.0\n" - + " }\n" + " aggregation_temporality: AGGREGATION_TEMPORALITY_CUMULATIVE\n" + "}\n"); + assertThat(registry.writeHistogramSupport(taskTimer).toString()) + .isEqualTo("name: \"checkout.batch\"\n" + "unit: \"milliseconds\"\n" + "histogram {\n" + " data_points {\n" + + " start_time_unix_nano: 1000000\n" + " time_unix_nano: 240001000000\n" + " sum: 0.0\n" + + " }\n" + " aggregation_temporality: AGGREGATION_TEMPORALITY_CUMULATIVE\n" + "}\n"); } // If the service.name was not specified, SDKs MUST fallback to 'unknown_service' @Test void unknownServiceByDefault() { assertThat(registry.getResourceAttributes()) - .contains(OtlpMeterRegistry.createKeyValue("service.name", "unknown_service")); + .contains(OtlpMeterRegistry.createKeyValue("service.name", "unknown_service")); } @Test @@ -523,7 +531,7 @@ public Map resourceAttributes() { }, Clock.SYSTEM); assertThat(registry.getResourceAttributes()) - .contains(OtlpMeterRegistry.createKeyValue("service.name", "myService")); + .contains(OtlpMeterRegistry.createKeyValue("service.name", "myService")); } @Test @@ -538,11 +546,11 @@ void setResourceAttributesAsString() throws IOException { @Test void setResourceAttributesFromEnvironmentVariables() throws Exception { withEnvironmentVariables("OTEL_RESOURCE_ATTRIBUTES", "a=1,b=2", "OTEL_SERVICE_NAME", "my-service") - .execute(() -> { - assertThat(registry.getResourceAttributes()).contains(OtlpMeterRegistry.createKeyValue("a", "1"), - OtlpMeterRegistry.createKeyValue("b", "2"), - OtlpMeterRegistry.createKeyValue("service.name", "my-service")); - }); + .execute(() -> { + assertThat(registry.getResourceAttributes()).contains(OtlpMeterRegistry.createKeyValue("a", "1"), + OtlpMeterRegistry.createKeyValue("b", "2"), + OtlpMeterRegistry.createKeyValue("service.name", "my-service")); + }); } } diff --git a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/MicrometerCollector.java b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/MicrometerCollector.java index 54c3d68dd2..521a8ca875 100644 --- a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/MicrometerCollector.java +++ b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/MicrometerCollector.java @@ -78,9 +78,10 @@ public List collect() { }); } - return families.values().stream() - .map(family -> new MetricFamilySamples(family.conventionName, family.type, help, family.samples)) - .collect(toList()); + return families.values() + .stream() + .map(family -> new MetricFamilySamples(family.conventionName, family.type, help, family.samples)) + .collect(toList()); } @Override @@ -91,8 +92,8 @@ public List describe() { new MetricFamilySamples(conventionName, Type.COUNTER, help, Collections.emptyList())); case GAUGE: - return Collections.singletonList( - new MetricFamilySamples(conventionName, Type.GAUGE, help, Collections.emptyList())); + return Collections + .singletonList(new MetricFamilySamples(conventionName, Type.GAUGE, help, Collections.emptyList())); case TIMER: case DISTRIBUTION_SUMMARY: diff --git a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusDistributionSummary.java b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusDistributionSummary.java index 517c704d19..f085adbd52 100644 --- a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusDistributionSummary.java +++ b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusDistributionSummary.java @@ -51,8 +51,13 @@ public class PrometheusDistributionSummary extends AbstractDistributionSummary { PrometheusDistributionSummary(Id id, Clock clock, DistributionStatisticConfig distributionStatisticConfig, double scale, HistogramFlavor histogramFlavor, @Nullable HistogramExemplarSampler exemplarSampler) { - super(id, clock, DistributionStatisticConfig.builder().percentilesHistogram(false).serviceLevelObjectives() - .build().merge(distributionStatisticConfig), scale, false); + super(id, clock, + DistributionStatisticConfig.builder() + .percentilesHistogram(false) + .serviceLevelObjectives() + .build() + .merge(distributionStatisticConfig), + scale, false); this.histogramFlavor = histogramFlavor; this.max = new TimeWindowMax(clock, distributionStatisticConfig); diff --git a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusHistogram.java b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusHistogram.java index fc1da12c34..a220245654 100644 --- a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusHistogram.java +++ b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusHistogram.java @@ -50,11 +50,14 @@ class PrometheusHistogram extends TimeWindowFixedBoundaryHistogram { PrometheusHistogram(Clock clock, DistributionStatisticConfig config, @Nullable HistogramExemplarSampler exemplarSampler) { - super(clock, DistributionStatisticConfig.builder().expiry(Duration.ofDays(1825)) // effectively - // never - // roll - // over - .bufferLength(1).build().merge(config), true); + super(clock, DistributionStatisticConfig.builder() + .expiry(Duration.ofDays(1825)) // effectively + // never + // roll + // over + .bufferLength(1) + .build() + .merge(config), true); this.exemplarSampler = exemplarSampler; if (isExemplarsEnabled()) { diff --git a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusMeterRegistry.java b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusMeterRegistry.java index 2647f3ad0d..17df8b52b2 100644 --- a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusMeterRegistry.java +++ b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusMeterRegistry.java @@ -288,7 +288,7 @@ public DistributionSummary newDistributionSummary(Meter.Id id, for (CountAtBucket c : histogramCounts) { final List histogramValuesVM = new ArrayList<>(tagValues); histogramValuesVM - .add(FixedBoundaryVictoriaMetricsHistogram.getRangeTagValue(c.bucket())); + .add(FixedBoundaryVictoriaMetricsHistogram.getRangeTagValue(c.bucket())); samples.add(new Collector.MetricFamilySamples.Sample(sampleName, histogramKeys, histogramValuesVM, c.count())); } @@ -330,9 +330,9 @@ protected io.micrometer.core.instrument.Gauge newGauge(Meter.Id id, @Nullabl Gauge gauge = new DefaultGauge<>(id, obj, valueFunction); applyToCollector(id, (collector) -> { List tagValues = tagValues(id); - collector.add(tagValues, (conventionName, tagKeys) -> Stream.of(new MicrometerCollector.Family( - Collector.Type.GAUGE, conventionName, - new Collector.MetricFamilySamples.Sample(conventionName, tagKeys, tagValues, gauge.value())))); + collector.add(tagValues, (conventionName, tagKeys) -> Stream + .of(new MicrometerCollector.Family(Collector.Type.GAUGE, conventionName, + new Collector.MetricFamilySamples.Sample(conventionName, tagKeys, tagValues, gauge.value())))); }); return gauge; } @@ -580,8 +580,10 @@ private void applyToCollector(Meter.Id id, Consumer consume @Override protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.builder().expiry(prometheusConfig.step()).build() - .merge(DistributionStatisticConfig.DEFAULT); + return DistributionStatisticConfig.builder() + .expiry(prometheusConfig.step()) + .build() + .merge(DistributionStatisticConfig.DEFAULT); } /** diff --git a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusTimer.java b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusTimer.java index cb8963f9a9..af3f835172 100644 --- a/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusTimer.java +++ b/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusTimer.java @@ -54,8 +54,13 @@ public class PrometheusTimer extends AbstractTimer { PrometheusTimer(Id id, Clock clock, DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetector, HistogramFlavor histogramFlavor, @Nullable HistogramExemplarSampler exemplarSampler) { - super(id, clock, DistributionStatisticConfig.builder().percentilesHistogram(false).serviceLevelObjectives() - .build().merge(distributionStatisticConfig), pauseDetector, TimeUnit.SECONDS, false); + super(id, clock, + DistributionStatisticConfig.builder() + .percentilesHistogram(false) + .serviceLevelObjectives() + .build() + .merge(distributionStatisticConfig), + pauseDetector, TimeUnit.SECONDS, false); this.histogramFlavor = histogramFlavor; this.max = new TimeWindowMax(clock, distributionStatisticConfig); diff --git a/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/MicrometerCollectorTest.java b/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/MicrometerCollectorTest.java index 4f0161ace7..8e0cbe2a07 100644 --- a/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/MicrometerCollectorTest.java +++ b/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/MicrometerCollectorTest.java @@ -42,7 +42,7 @@ void manyTags() { singletonList("k"), singletonList(i.toString()), 1.0); collector.add(Collections.emptyList(), (conventionName, tagKeys) -> Stream - .of(new MicrometerCollector.Family(Collector.Type.COUNTER, "my_counter", sample))); + .of(new MicrometerCollector.Family(Collector.Type.COUNTER, "my_counter", sample))); } // Threw StackOverflowException because of too many nested streams originally @@ -60,9 +60,9 @@ void sameValuesDifferentOrder() { asList("k", "k2"), asList("v2", "v1"), 1.0); collector.add(asList("v1", "v2"), (conventionName, tagKeys) -> Stream - .of(new MicrometerCollector.Family(Collector.Type.COUNTER, "my_counter", sample))); + .of(new MicrometerCollector.Family(Collector.Type.COUNTER, "my_counter", sample))); collector.add(asList("v2", "v1"), (conventionName, tagKeys) -> Stream - .of(new MicrometerCollector.Family(Collector.Type.COUNTER, "my_counter", sample2))); + .of(new MicrometerCollector.Family(Collector.Type.COUNTER, "my_counter", sample2))); assertThat(collector.collect().get(0).samples).hasSize(2); } diff --git a/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/PrometheusMeterRegistryTest.java b/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/PrometheusMeterRegistryTest.java index 214c7b3c98..fe2de765c1 100644 --- a/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/PrometheusMeterRegistryTest.java +++ b/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/PrometheusMeterRegistryTest.java @@ -76,12 +76,14 @@ void meterRegistrationFailedListenerCalledOnSameNameDifferentTags() throws Inter assertThat(failedLatch.await(1, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> registry.throwExceptionOnRegistrationFailure().counter("my.counter", "k1", "v1")) - .isInstanceOf(IllegalArgumentException.class).hasMessageStartingWith( - "Prometheus requires that all meters with the same name have the same set of tag keys."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith( + "Prometheus requires that all meters with the same name have the same set of tag keys."); assertThatThrownBy(() -> registry.counter("my.counter", "k2", "v2")) - .isInstanceOf(IllegalArgumentException.class).hasMessageStartingWith( - "Prometheus requires that all meters with the same name have the same set of tag keys."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith( + "Prometheus requires that all meters with the same name have the same set of tag keys."); } @Test @@ -107,22 +109,25 @@ void quantiles() { void customSummaries() { Arrays.asList("v1", "v2").forEach(v -> { registry.summary("s", "k", v).record(1.0); - assertThat(registry.getPrometheusRegistry().getSampleValue("s_count", new String[] { "k" }, - new String[] { v })).describedAs("distribution summary s with a tag value of %s", v).isEqualTo(1.0, - offset(1e-12)); + assertThat(registry.getPrometheusRegistry() + .getSampleValue("s_count", new String[] { "k" }, new String[] { v })) + .describedAs("distribution summary s with a tag value of %s", v) + .isEqualTo(1.0, offset(1e-12)); }); } @DisplayName("custom meters can be typed") @Test void typedCustomMeters() { - Meter.builder("name", Meter.Type.COUNTER, - Collections.singletonList(new Measurement(() -> 1.0, Statistic.COUNT))).register(registry); + Meter + .builder("name", Meter.Type.COUNTER, Collections.singletonList(new Measurement(() -> 1.0, Statistic.COUNT))) + .register(registry); - Collector.MetricFamilySamples metricFamilySamples = registry.getPrometheusRegistry().metricFamilySamples() - .nextElement(); + Collector.MetricFamilySamples metricFamilySamples = registry.getPrometheusRegistry() + .metricFamilySamples() + .nextElement(); assertThat(metricFamilySamples.type).describedAs("custom counter with a type of COUNTER") - .isEqualTo(Collector.Type.COUNTER); + .isEqualTo(Collector.Type.COUNTER); assertThat(metricFamilySamples.samples.get(0).labelNames).containsExactly("statistic"); assertThat(metricFamilySamples.samples.get(0).labelValues).containsExactly("COUNT"); } @@ -140,13 +145,16 @@ void helpText() { Timer.builder("timer").description("my timer").register(registry); Counter.builder("counter").description("my counter").register(registry); DistributionSummary.builder("summary").description("my summary").register(registry); - Gauge.builder("gauge", new AtomicInteger(), AtomicInteger::doubleValue).description("my gauge") - .register(registry); + Gauge.builder("gauge", new AtomicInteger(), AtomicInteger::doubleValue) + .description("my gauge") + .register(registry); LongTaskTimer.builder("long.task.timer").description("my long task timer").register(registry); - assertThat(registry.scrape()).contains("HELP timer_seconds my timer").contains("HELP summary my summary") - .contains("HELP gauge my gauge").contains("HELP counter_total my counter") - .contains("HELP long_task_timer_seconds my long task timer"); + assertThat(registry.scrape()).contains("HELP timer_seconds my timer") + .contains("HELP summary my summary") + .contains("HELP gauge my gauge") + .contains("HELP counter_total my counter") + .contains("HELP long_task_timer_seconds my long task timer"); } @Issue("#249") @@ -196,8 +204,11 @@ void percentileHistogramsAccumulateToInfinityEvenWhenClamped() { @Issue("#265") @Test void percentileHistogramsNeverResetForTimers() { - Timer t = Timer.builder("t1").publishPercentileHistogram().distributionStatisticExpiry(Duration.ofSeconds(60)) - .serviceLevelObjectives(Duration.ofMillis(100)).register(registry); + Timer t = Timer.builder("t1") + .publishPercentileHistogram() + .distributionStatisticExpiry(Duration.ofSeconds(60)) + .serviceLevelObjectives(Duration.ofMillis(100)) + .register(registry); t.record(100, TimeUnit.MILLISECONDS); clock.addSeconds(60); @@ -208,8 +219,11 @@ void percentileHistogramsNeverResetForTimers() { @Issue("#265") @Test void percentileHistogramsNeverResetForSummaries() { - DistributionSummary s = DistributionSummary.builder("s1").publishPercentileHistogram() - .distributionStatisticExpiry(Duration.ofSeconds(60)).serviceLevelObjectives(100.0).register(registry); + DistributionSummary s = DistributionSummary.builder("s1") + .publishPercentileHistogram() + .distributionStatisticExpiry(Duration.ofSeconds(60)) + .serviceLevelObjectives(100.0) + .register(registry); s.record(100); clock.addSeconds(60); @@ -220,8 +234,10 @@ void percentileHistogramsNeverResetForSummaries() { @Test void percentileHistogramWithUpperBoundContainsExactlyOneInf() { - DistributionSummary s = DistributionSummary.builder("s").publishPercentileHistogram().maximumExpectedValue(3.0) - .register(registry); + DistributionSummary s = DistributionSummary.builder("s") + .publishPercentileHistogram() + .maximumExpectedValue(3.0) + .register(registry); s.record(100); @@ -241,8 +257,11 @@ void percentileHistogramWithoutUpperBoundContainsExactlyOneInf() { @Issue("#247") @Test void distributionPercentileBuckets() { - DistributionSummary ds = DistributionSummary.builder("ds").publishPercentileHistogram() - .minimumExpectedValue(1.0).maximumExpectedValue(2100.0).register(registry); + DistributionSummary ds = DistributionSummary.builder("ds") + .publishPercentileHistogram() + .minimumExpectedValue(1.0) + .maximumExpectedValue(2100.0) + .register(registry); ds.record(30); ds.record(9); @@ -254,8 +273,11 @@ void distributionPercentileBuckets() { @Issue("#127") @Test void percentileHistogramsWhenValueIsLessThanTheSmallestBucket() { - DistributionSummary speedIndexRatings = DistributionSummary.builder("speed.index").tags("page", "home") - .description("Distribution of 'speed index' ratings").publishPercentileHistogram().register(registry); + DistributionSummary speedIndexRatings = DistributionSummary.builder("speed.index") + .tags("page", "home") + .description("Distribution of 'speed index' ratings") + .publishPercentileHistogram() + .register(registry); speedIndexRatings.record(0); @@ -268,8 +290,10 @@ void serviceLevelObjectivesOnlyNoPercentileHistogram() { DistributionSummary.builder("my.summary").serviceLevelObjectives(1.0).register(registry).record(1); assertThat(registry.scrape()).contains("my_summary_bucket{le=\"1.0\",} 1.0"); - Timer.builder("my.timer").serviceLevelObjectives(Duration.ofMillis(1)).register(registry).record(1, - TimeUnit.MILLISECONDS); + Timer.builder("my.timer") + .serviceLevelObjectives(Duration.ofMillis(1)) + .register(registry) + .record(1, TimeUnit.MILLISECONDS); assertThat(registry.scrape()).contains("my_timer_seconds_bucket{le=\"0.001\",} 1.0"); } @@ -388,13 +412,16 @@ void meterRemoval() { registry.remove(timer); assertThat(prometheusRegistry.metricFamilySamples()) - .doesNotHave(withNameAndQuantile("timer_to_be_removed_seconds")); + .doesNotHave(withNameAndQuantile("timer_to_be_removed_seconds")); } @Test void timerQuantilesAreBasedOffOfOnlyRecentSamples() { - Timer timer = Timer.builder("my.timer").publishPercentiles(1.0).distributionStatisticBufferLength(2) - .distributionStatisticExpiry(Duration.ofMinutes(1)).register(registry); + Timer timer = Timer.builder("my.timer") + .publishPercentiles(1.0) + .distributionStatisticBufferLength(2) + .distributionStatisticExpiry(Duration.ofMinutes(1)) + .register(registry); timer.record(1, TimeUnit.SECONDS); assertThat(timer.takeSnapshot().percentileValues()[0].value(TimeUnit.SECONDS)).isEqualTo(1.0, offset(0.1)); @@ -411,9 +438,11 @@ void timerQuantilesAreBasedOffOfOnlyRecentSamples() { @Test void summaryQuantilesAreBasedOffOfOnlyRecentSamples() { - DistributionSummary timer = DistributionSummary.builder("my.summary").publishPercentiles(1.0) - .distributionStatisticBufferLength(2).distributionStatisticExpiry(Duration.ofMinutes(1)) - .register(registry); + DistributionSummary timer = DistributionSummary.builder("my.summary") + .publishPercentiles(1.0) + .distributionStatisticBufferLength(2) + .distributionStatisticExpiry(Duration.ofMinutes(1)) + .register(registry); timer.record(1); assertThat(timer.takeSnapshot().percentileValues()[0].value()).isEqualTo(1.0, offset(0.2)); @@ -447,10 +476,12 @@ void filteredMetricFamilySamplesWithCounter() { private void assertFilteredMetricFamilySamples(String[] includedNames, String[] expectedNames) { Enumeration metricFamilySamples = registry.getPrometheusRegistry() - .filteredMetricFamilySamples(new HashSet<>(Arrays.asList(includedNames))); - String[] names = Collections.list(metricFamilySamples).stream() - .flatMap(metricFamilySample -> metricFamilySample.samples.stream()).map(sample -> sample.name) - .toArray(String[]::new); + .filteredMetricFamilySamples(new HashSet<>(Arrays.asList(includedNames))); + String[] names = Collections.list(metricFamilySamples) + .stream() + .flatMap(metricFamilySample -> metricFamilySample.samples.stream()) + .map(sample -> sample.name) + .toArray(String[]::new); assertThat(names).containsExactlyInAnyOrder(expectedNames); } @@ -524,8 +555,8 @@ void timerSumAndMaxHaveCorrectBaseUnit_whenPercentileHistogramEnabled() { void scrapeWithLongTaskTimer() { LongTaskTimer.builder("my.long.task.timer").register(registry); assertThat(registry.scrape()).contains("my_long_task_timer_seconds_max") - .contains("my_long_task_timer_seconds_active_count") - .contains("my_long_task_timer_seconds_duration_sum"); + .contains("my_long_task_timer_seconds_active_count") + .contains("my_long_task_timer_seconds_duration_sum"); } @Issue("#2087") @@ -562,13 +593,13 @@ void openMetricsScrape() { Counter.builder("my.counter").baseUnit("bytes").register(registry); Timer.builder("my.timer").register(registry); assertThat(registry.scrape(TextFormat.CONTENT_TYPE_OPENMETRICS_100)) - .contains("# TYPE my_counter_bytes counter\n" + "# HELP my_counter_bytes \n" - + "my_counter_bytes_total 0.0\n") - .contains("# TYPE my_timer_seconds_max gauge\n" + "# HELP my_timer_seconds_max \n" - + "my_timer_seconds_max 0.0\n") - .contains("# TYPE my_timer_seconds summary\n" + "# HELP my_timer_seconds \n" - + "my_timer_seconds_count 0.0\n" + "my_timer_seconds_sum 0.0\n") - .endsWith("# EOF\n"); + .contains("# TYPE my_counter_bytes counter\n" + "# HELP my_counter_bytes \n" + + "my_counter_bytes_total 0.0\n") + .contains("# TYPE my_timer_seconds_max gauge\n" + "# HELP my_timer_seconds_max \n" + + "my_timer_seconds_max 0.0\n") + .contains("# TYPE my_timer_seconds summary\n" + "# HELP my_timer_seconds \n" + + "my_timer_seconds_count 0.0\n" + "my_timer_seconds_sum 0.0\n") + .endsWith("# EOF\n"); } @Test @@ -581,20 +612,22 @@ void openMetricsScrapeWithExemplars() { counter.increment(); Timer timer = Timer.builder("test.timer") - .serviceLevelObjectives(Duration.ofMillis(100), Duration.ofMillis(200), Duration.ofMillis(300)) - .register(registry); + .serviceLevelObjectives(Duration.ofMillis(100), Duration.ofMillis(200), Duration.ofMillis(300)) + .register(registry); timer.record(Duration.ofMillis(15)); timer.record(Duration.ofMillis(150)); timer.record(Duration.ofMillis(1_500)); - DistributionSummary histogram = DistributionSummary.builder("test.histogram").publishPercentileHistogram() - .register(registry); + DistributionSummary histogram = DistributionSummary.builder("test.histogram") + .publishPercentileHistogram() + .register(registry); histogram.record(0.15); histogram.record(15); histogram.record(5E18); - DistributionSummary slos = DistributionSummary.builder("test.slos").serviceLevelObjectives(100, 200, 300) - .register(registry); + DistributionSummary slos = DistributionSummary.builder("test.slos") + .serviceLevelObjectives(100, 200, 300) + .register(registry); slos.record(10); slos.record(250); slos.record(1_000); @@ -602,16 +635,16 @@ void openMetricsScrapeWithExemplars() { String scraped = registry.scrape(TextFormat.CONTENT_TYPE_OPENMETRICS_100); assertThat(scraped).contains("my_counter_total 1.0 # {span_id=\"1\",trace_id=\"2\"} 1.0"); assertThat(scraped).contains("test_timer_seconds_bucket{le=\"0.1\"} 1.0 # {span_id=\"3\",trace_id=\"4\"} 0.015") - .contains("test_timer_seconds_bucket{le=\"0.2\"} 2.0 # {span_id=\"5\",trace_id=\"6\"} 0.15") - .contains("test_timer_seconds_bucket{le=\"0.3\"} 2.0\n") - .contains("test_timer_seconds_bucket{le=\"+Inf\"} 3.0 # {span_id=\"7\",trace_id=\"8\"} 1.5"); + .contains("test_timer_seconds_bucket{le=\"0.2\"} 2.0 # {span_id=\"5\",trace_id=\"6\"} 0.15") + .contains("test_timer_seconds_bucket{le=\"0.3\"} 2.0\n") + .contains("test_timer_seconds_bucket{le=\"+Inf\"} 3.0 # {span_id=\"7\",trace_id=\"8\"} 1.5"); assertThat(scraped).contains("test_histogram_bucket{le=\"1.0\"} 1.0 # {span_id=\"9\",trace_id=\"10\"} 0.15") - .contains("test_histogram_bucket{le=\"16.0\"} 2.0 # {span_id=\"11\",trace_id=\"12\"} 15.0") - .contains("test_histogram_bucket{le=\"+Inf\"} 3.0 # {span_id=\"13\",trace_id=\"14\"} 5.0E18"); + .contains("test_histogram_bucket{le=\"16.0\"} 2.0 # {span_id=\"11\",trace_id=\"12\"} 15.0") + .contains("test_histogram_bucket{le=\"+Inf\"} 3.0 # {span_id=\"13\",trace_id=\"14\"} 5.0E18"); assertThat(scraped).contains("test_slos_bucket{le=\"100.0\"} 1.0 # {span_id=\"15\",trace_id=\"16\"} 10.0") - .contains("test_slos_bucket{le=\"200.0\"} 1.0\n") - .contains("test_slos_bucket{le=\"300.0\"} 2.0 # {span_id=\"17\",trace_id=\"18\"} 250.0") - .contains("test_slos_bucket{le=\"+Inf\"} 3.0 # {span_id=\"19\",trace_id=\"20\"} 1000.0"); + .contains("test_slos_bucket{le=\"200.0\"} 1.0\n") + .contains("test_slos_bucket{le=\"300.0\"} 2.0 # {span_id=\"17\",trace_id=\"18\"} 250.0") + .contains("test_slos_bucket{le=\"+Inf\"} 3.0 # {span_id=\"19\",trace_id=\"20\"} 1000.0"); assertThat(scraped).endsWith("# EOF\n"); } @@ -624,20 +657,22 @@ void noExemplarsIfNoSampler() { counter.increment(); Timer timer = Timer.builder("test.timer") - .serviceLevelObjectives(Duration.ofMillis(100), Duration.ofMillis(200), Duration.ofMillis(300)) - .register(registry); + .serviceLevelObjectives(Duration.ofMillis(100), Duration.ofMillis(200), Duration.ofMillis(300)) + .register(registry); timer.record(Duration.ofMillis(15)); timer.record(Duration.ofMillis(150)); timer.record(Duration.ofMillis(1_500)); - DistributionSummary histogram = DistributionSummary.builder("test.histogram").publishPercentileHistogram() - .register(registry); + DistributionSummary histogram = DistributionSummary.builder("test.histogram") + .publishPercentileHistogram() + .register(registry); histogram.record(0.15); histogram.record(15); histogram.record(5E18); - DistributionSummary slos = DistributionSummary.builder("test.slos").serviceLevelObjectives(100, 200, 300) - .register(registry); + DistributionSummary slos = DistributionSummary.builder("test.slos") + .serviceLevelObjectives(100, 200, 300) + .register(registry); slos.record(10); slos.record(250); slos.record(1_000); @@ -645,15 +680,16 @@ void noExemplarsIfNoSampler() { String scraped = registry.scrape(TextFormat.CONTENT_TYPE_OPENMETRICS_100); assertThat(scraped).contains("my_counter_total 1.0\n"); assertThat(scraped).contains("test_timer_seconds_bucket{le=\"0.1\"} 1.0\n") - .contains("test_timer_seconds_bucket{le=\"0.2\"} 2.0\n") - .contains("test_timer_seconds_bucket{le=\"0.3\"} 2.0\n") - .contains("test_timer_seconds_bucket{le=\"+Inf\"} 3.0\n"); + .contains("test_timer_seconds_bucket{le=\"0.2\"} 2.0\n") + .contains("test_timer_seconds_bucket{le=\"0.3\"} 2.0\n") + .contains("test_timer_seconds_bucket{le=\"+Inf\"} 3.0\n"); assertThat(scraped).contains("test_histogram_bucket{le=\"1.0\"} 1.0\n") - .contains("test_histogram_bucket{le=\"16.0\"} 2.0\n") - .contains("test_histogram_bucket{le=\"+Inf\"} 3.0\n"); + .contains("test_histogram_bucket{le=\"16.0\"} 2.0\n") + .contains("test_histogram_bucket{le=\"+Inf\"} 3.0\n"); assertThat(scraped).contains("test_slos_bucket{le=\"100.0\"} 1.0\n") - .contains("test_slos_bucket{le=\"200.0\"} 1.0\n").contains("test_slos_bucket{le=\"300.0\"} 2.0\n") - .contains("test_slos_bucket{le=\"+Inf\"} 3.0\n"); + .contains("test_slos_bucket{le=\"200.0\"} 1.0\n") + .contains("test_slos_bucket{le=\"300.0\"} 2.0\n") + .contains("test_slos_bucket{le=\"+Inf\"} 3.0\n"); assertThat(scraped).doesNotContain("span_id").doesNotContain("trace_id"); assertThat(scraped).endsWith("# EOF\n"); } diff --git a/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/PrometheusNamingConventionTest.java b/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/PrometheusNamingConventionTest.java index 43ec3f9432..7cb6785fca 100644 --- a/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/PrometheusNamingConventionTest.java +++ b/implementations/micrometer-registry-prometheus/src/test/java/io/micrometer/prometheus/PrometheusNamingConventionTest.java @@ -49,21 +49,21 @@ void unitsAreAppendedToTimers() { @Test void unitsAreAppendedToDistributionSummaries() { assertThat(convention.name("response.size", Meter.Type.DISTRIBUTION_SUMMARY, BaseUnits.BYTES)) - .isEqualTo("response_size_bytes"); + .isEqualTo("response_size_bytes"); assertThat(convention.name("summary", Meter.Type.DISTRIBUTION_SUMMARY)).isEqualTo("summary"); } @Test void unitsAreAppendedToCounters() { assertThat(convention.name("response.size", Meter.Type.COUNTER, BaseUnits.BYTES)) - .isEqualTo("response_size_bytes_total"); + .isEqualTo("response_size_bytes_total"); assertThat(convention.name("counter", Meter.Type.COUNTER)).isEqualTo("counter_total"); } @Test void unitsAreAppendedToGauges() { assertThat(convention.name("response.size", Meter.Type.GAUGE, BaseUnits.BYTES)) - .isEqualTo("response_size_bytes"); + .isEqualTo("response_size_bytes"); assertThat(convention.name("gauge", Meter.Type.GAUGE)).isEqualTo("gauge"); } diff --git a/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/CumulativeHistogramConfigUtil.java b/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/CumulativeHistogramConfigUtil.java index 6030b72506..44de0db871 100644 --- a/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/CumulativeHistogramConfigUtil.java +++ b/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/CumulativeHistogramConfigUtil.java @@ -41,11 +41,14 @@ static DistributionStatisticConfig updateConfig(DistributionStatisticConfig dist } return DistributionStatisticConfig.builder() - // Set the expiration duration for the histogram counts to be effectively - // infinite. - // Without this, the counts are reset every expiry duration. - .expiry(Duration.ofNanos(Long.MAX_VALUE)) // effectively infinite - .bufferLength(1).serviceLevelObjectives(newSloBoundaries).build().merge(distributionStatisticConfig); + // Set the expiration duration for the histogram counts to be effectively + // infinite. + // Without this, the counts are reset every expiry duration. + .expiry(Duration.ofNanos(Long.MAX_VALUE)) // effectively infinite + .bufferLength(1) + .serviceLevelObjectives(newSloBoundaries) + .build() + .merge(distributionStatisticConfig); } private static boolean isPositiveInf(double bucket) { diff --git a/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxConfig.java b/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxConfig.java index 1ff80253a2..1ff054ef2d 100644 --- a/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxConfig.java +++ b/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxConfig.java @@ -60,7 +60,7 @@ default String uri() { // method 'uri', so we accept // either here for backwards compatibility. return getUrlString(this, "apiHost").flatMap((uri, valid) -> uri == null ? getUrlString(this, "uri") : valid) - .orElse("https://ingest.signalfx.com"); + .orElse("https://ingest.signalfx.com"); } /** diff --git a/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxMeterRegistry.java b/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxMeterRegistry.java index df86c31667..412fd9dfd8 100644 --- a/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxMeterRegistry.java +++ b/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxMeterRegistry.java @@ -66,7 +66,7 @@ public class SignalFxMeterRegistry extends StepMeterRegistry { private final HttpEventProtobufReceiverFactory eventReceiverFactory; private final Set onSendErrorHandlerCollection = Collections - .singleton(metricError -> this.logger.warn("failed to send metrics: {}", metricError.getMessage())); + .singleton(metricError -> this.logger.warn("failed to send metrics: {}", metricError.getMessage())); private final boolean publishCumulativeHistogram; @@ -180,18 +180,23 @@ private SignalFxProtocolBuffers.DataPoint.Builder addDatapoint(Meter meter, SignalFxProtocolBuffers.MetricType metricType, @Nullable String statSuffix, Number value) { SignalFxProtocolBuffers.Datum.Builder datumBuilder = SignalFxProtocolBuffers.Datum.newBuilder(); SignalFxProtocolBuffers.Datum datum = (value instanceof Double ? datumBuilder.setDoubleValue((Double) value) - : datumBuilder.setIntValue(value.longValue())).build(); + : datumBuilder.setIntValue(value.longValue())) + .build(); - String metricName = config().namingConvention().name( - statSuffix == null ? meter.getId().getName() : meter.getId().getName() + "." + statSuffix, - meter.getId().getType(), meter.getId().getBaseUnit()); + String metricName = config().namingConvention() + .name(statSuffix == null ? meter.getId().getName() : meter.getId().getName() + "." + statSuffix, + meter.getId().getType(), meter.getId().getBaseUnit()); SignalFxProtocolBuffers.DataPoint.Builder dataPointBuilder = SignalFxProtocolBuffers.DataPoint.newBuilder() - .setMetric(metricName).setMetricType(metricType).setValue(datum); + .setMetric(metricName) + .setMetricType(metricType) + .setValue(datum); for (Tag tag : getConventionTags(meter.getId())) { - dataPointBuilder.addDimensions(SignalFxProtocolBuffers.Dimension.newBuilder().setKey(tag.getKey()) - .setValue(tag.getValue()).build()); + dataPointBuilder.addDimensions(SignalFxProtocolBuffers.Dimension.newBuilder() + .setKey(tag.getKey()) + .setValue(tag.getValue()) + .build()); } return dataPointBuilder; diff --git a/implementations/micrometer-registry-signalfx/src/test/java/io/micrometer/signalfx/SignalFxConfigTest.java b/implementations/micrometer-registry-signalfx/src/test/java/io/micrometer/signalfx/SignalFxConfigTest.java index 47029973a8..7fef3a68ce 100644 --- a/implementations/micrometer-registry-signalfx/src/test/java/io/micrometer/signalfx/SignalFxConfigTest.java +++ b/implementations/micrometer-registry-signalfx/src/test/java/io/micrometer/signalfx/SignalFxConfigTest.java @@ -34,7 +34,7 @@ void invalid() { props.put("signalfx.uri", "bad"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactlyInAnyOrder("must be a valid URL", "is required"); + .containsExactlyInAnyOrder("must be a valid URL", "is required"); } @Test diff --git a/implementations/micrometer-registry-signalfx/src/test/java/io/micrometer/signalfx/SignalFxMeterRegistryTest.java b/implementations/micrometer-registry-signalfx/src/test/java/io/micrometer/signalfx/SignalFxMeterRegistryTest.java index 36783258fa..c4d7836ebd 100644 --- a/implementations/micrometer-registry-signalfx/src/test/java/io/micrometer/signalfx/SignalFxMeterRegistryTest.java +++ b/implementations/micrometer-registry-signalfx/src/test/java/io/micrometer/signalfx/SignalFxMeterRegistryTest.java @@ -92,9 +92,10 @@ void shouldConfigureCumulativeHistogram_Timer() { MockClock clock = new MockClock(); SignalFxMeterRegistry registry = new SignalFxMeterRegistry(cumulativeHistogramConfig, clock); Timer timer = Timer.builder("testTimer") - .serviceLevelObjectives(Duration.ofMillis(10), Duration.ofMillis(100), Duration.ofMillis(1000)) - .distributionStatisticExpiry(Duration.ofSeconds(10)).distributionStatisticBufferLength(1) - .register(registry); + .serviceLevelObjectives(Duration.ofMillis(10), Duration.ofMillis(100), Duration.ofMillis(1000)) + .distributionStatisticExpiry(Duration.ofSeconds(10)) + .distributionStatisticBufferLength(1) + .register(registry); timer.record(Duration.ofSeconds(10)); clock.add(Duration.ofSeconds(3)); @@ -119,9 +120,11 @@ void shouldConfigureCumulativeHistogram_Timer() { void shouldConfigureCumulativeHistogram_DistributionSummary() { MockClock clock = new MockClock(); SignalFxMeterRegistry registry = new SignalFxMeterRegistry(cumulativeHistogramConfig, clock); - DistributionSummary summary = DistributionSummary.builder("testSummary").serviceLevelObjectives(10, 100, 1000) - .distributionStatisticExpiry(Duration.ofSeconds(10)).distributionStatisticBufferLength(1) - .register(registry); + DistributionSummary summary = DistributionSummary.builder("testSummary") + .serviceLevelObjectives(10, 100, 1000) + .distributionStatisticExpiry(Duration.ofSeconds(10)) + .distributionStatisticBufferLength(1) + .register(registry); summary.record(10_000); clock.add(Duration.ofSeconds(3)); @@ -157,14 +160,15 @@ void shouldExportCumulativeHistogramData_Timer(Duration[] buckets) { mockClock.add(config.step()); assertThat(getDataPoints(registry, mockClock.wallTime())).hasSize(9) - .has(gaugePoint("my.timer.avg", 0.55), atIndex(0)).has(counterPoint("my.timer.count", 4), atIndex(1)) - .has(allOf(cumulativeCounterPoint("my.timer.histogram", 4), bucket("+Inf")), atIndex(2)) - .has(allOf(cumulativeCounterPoint("my.timer.histogram", 0), bucket(buckets[0])), atIndex(3)) - .has(allOf(cumulativeCounterPoint("my.timer.histogram", 1), bucket(buckets[1])), atIndex(4)) - .has(allOf(cumulativeCounterPoint("my.timer.histogram", 2), bucket(buckets[2])), atIndex(5)) - .has(allOf(cumulativeCounterPoint("my.timer.histogram", 3), bucket(buckets[3])), atIndex(6)) - .has(gaugePoint("my.timer.max", 2), atIndex(7)) - .has(counterPoint("my.timer.totalTime", 2.2), atIndex(8)); + .has(gaugePoint("my.timer.avg", 0.55), atIndex(0)) + .has(counterPoint("my.timer.count", 4), atIndex(1)) + .has(allOf(cumulativeCounterPoint("my.timer.histogram", 4), bucket("+Inf")), atIndex(2)) + .has(allOf(cumulativeCounterPoint("my.timer.histogram", 0), bucket(buckets[0])), atIndex(3)) + .has(allOf(cumulativeCounterPoint("my.timer.histogram", 1), bucket(buckets[1])), atIndex(4)) + .has(allOf(cumulativeCounterPoint("my.timer.histogram", 2), bucket(buckets[2])), atIndex(5)) + .has(allOf(cumulativeCounterPoint("my.timer.histogram", 3), bucket(buckets[3])), atIndex(6)) + .has(gaugePoint("my.timer.max", 2), atIndex(7)) + .has(counterPoint("my.timer.totalTime", 2.2), atIndex(8)); registry.close(); } @@ -188,7 +192,8 @@ void shouldExportCumulativeHistogramData_DistributionSummary(double[] buckets) { MockClock mockClock = new MockClock(); SignalFxMeterRegistry registry = new SignalFxMeterRegistry(cumulativeHistogramConfig, mockClock); DistributionSummary distributionSummary = DistributionSummary.builder("my.distribution") - .serviceLevelObjectives(buckets).register(registry); + .serviceLevelObjectives(buckets) + .register(registry); distributionSummary.record(5); distributionSummary.record(20); @@ -200,15 +205,15 @@ void shouldExportCumulativeHistogramData_DistributionSummary(double[] buckets) { mockClock.add(cumulativeHistogramConfig.step()); assertThat(getDataPoints(registry, mockClock.wallTime())).hasSize(9) - .has(gaugePoint("my.distribution.avg", 550), atIndex(0)) - .has(counterPoint("my.distribution.count", 4), atIndex(1)) - .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 4), bucket("+Inf")), atIndex(2)) - .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 0), bucket(buckets[0])), atIndex(3)) - .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 1), bucket(buckets[1])), atIndex(4)) - .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 2), bucket(buckets[2])), atIndex(5)) - .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 3), bucket(buckets[3])), atIndex(6)) - .has(gaugePoint("my.distribution.max", 2000), atIndex(7)) - .has(counterPoint("my.distribution.totalTime", 2200), atIndex(8)); + .has(gaugePoint("my.distribution.avg", 550), atIndex(0)) + .has(counterPoint("my.distribution.count", 4), atIndex(1)) + .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 4), bucket("+Inf")), atIndex(2)) + .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 0), bucket(buckets[0])), atIndex(3)) + .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 1), bucket(buckets[1])), atIndex(4)) + .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 2), bucket(buckets[2])), atIndex(5)) + .has(allOf(cumulativeCounterPoint("my.distribution.histogram", 3), bucket(buckets[3])), atIndex(6)) + .has(gaugePoint("my.distribution.max", 2000), atIndex(7)) + .has(counterPoint("my.distribution.totalTime", 2200), atIndex(8)); registry.close(); } @@ -229,10 +234,11 @@ void shouldNotExportCumulativeHistogramDataByDefault_Timer() { MockClock mockClock = new MockClock(); SignalFxMeterRegistry registry = new SignalFxMeterRegistry(config, mockClock); Timer timer = Timer.builder("my.timer") - .serviceLevelObjectives(Duration.ofMillis(1), Duration.ofMillis(10), Duration.ofMillis(100), - Duration.ofMillis(1000)) - .distributionStatisticExpiry(Duration.ofSeconds(10)).distributionStatisticBufferLength(1) - .register(registry); + .serviceLevelObjectives(Duration.ofMillis(1), Duration.ofMillis(10), Duration.ofMillis(100), + Duration.ofMillis(1000)) + .distributionStatisticExpiry(Duration.ofSeconds(10)) + .distributionStatisticBufferLength(1) + .register(registry); timer.record(50, TimeUnit.MILLISECONDS); timer.record(5000, TimeUnit.MILLISECONDS); @@ -244,13 +250,14 @@ void shouldNotExportCumulativeHistogramDataByDefault_Timer() { mockClock.add(config.step().minus(Duration.ofMillis(1))); assertThat(getDataPoints(registry, mockClock.wallTime())).hasSize(8) - .has(gaugePoint("my.timer.avg", 0.2525), atIndex(0)).has(counterPoint("my.timer.count", 2), atIndex(1)) - .has(allOf(gaugePoint("my.timer.histogram", 0), bucket(Duration.ofMillis(1))), atIndex(2)) - .has(allOf(gaugePoint("my.timer.histogram", 1), bucket(Duration.ofMillis(10))), atIndex(3)) - .has(allOf(gaugePoint("my.timer.histogram", 1), bucket(Duration.ofMillis(100))), atIndex(4)) - .has(allOf(gaugePoint("my.timer.histogram", 2), bucket(Duration.ofMillis(1000))), atIndex(5)) - .has(gaugePoint("my.timer.max", 0.5), atIndex(6)) - .has(counterPoint("my.timer.totalTime", 0.505), atIndex(7)); + .has(gaugePoint("my.timer.avg", 0.2525), atIndex(0)) + .has(counterPoint("my.timer.count", 2), atIndex(1)) + .has(allOf(gaugePoint("my.timer.histogram", 0), bucket(Duration.ofMillis(1))), atIndex(2)) + .has(allOf(gaugePoint("my.timer.histogram", 1), bucket(Duration.ofMillis(10))), atIndex(3)) + .has(allOf(gaugePoint("my.timer.histogram", 1), bucket(Duration.ofMillis(100))), atIndex(4)) + .has(allOf(gaugePoint("my.timer.histogram", 2), bucket(Duration.ofMillis(1000))), atIndex(5)) + .has(gaugePoint("my.timer.max", 0.5), atIndex(6)) + .has(counterPoint("my.timer.totalTime", 0.505), atIndex(7)); registry.close(); } @@ -260,8 +267,10 @@ void shouldNotExportCumulativeHistogramDataByDefault_DistributionSummary() { MockClock mockClock = new MockClock(); SignalFxMeterRegistry registry = new SignalFxMeterRegistry(config, mockClock); DistributionSummary summary = DistributionSummary.builder("my.distribution") - .serviceLevelObjectives(1, 10, 100, 1000).distributionStatisticExpiry(Duration.ofSeconds(10)) - .distributionStatisticBufferLength(1).register(registry); + .serviceLevelObjectives(1, 10, 100, 1000) + .distributionStatisticExpiry(Duration.ofSeconds(10)) + .distributionStatisticBufferLength(1) + .register(registry); summary.record(50); summary.record(5000); @@ -273,28 +282,29 @@ void shouldNotExportCumulativeHistogramDataByDefault_DistributionSummary() { mockClock.add(config.step().minus(Duration.ofMillis(1))); assertThat(getDataPoints(registry, mockClock.wallTime())).hasSize(8) - .has(gaugePoint("my.distribution.avg", 252.5), atIndex(0)) - .has(counterPoint("my.distribution.count", 2), atIndex(1)) - .has(allOf(gaugePoint("my.distribution.histogram", 0), bucket(1)), atIndex(2)) - .has(allOf(gaugePoint("my.distribution.histogram", 1), bucket(10)), atIndex(3)) - .has(allOf(gaugePoint("my.distribution.histogram", 1), bucket(100)), atIndex(4)) - .has(allOf(gaugePoint("my.distribution.histogram", 2), bucket(1000)), atIndex(5)) - .has(gaugePoint("my.distribution.max", 500), atIndex(6)) - .has(counterPoint("my.distribution.totalTime", 505), atIndex(7)); + .has(gaugePoint("my.distribution.avg", 252.5), atIndex(0)) + .has(counterPoint("my.distribution.count", 2), atIndex(1)) + .has(allOf(gaugePoint("my.distribution.histogram", 0), bucket(1)), atIndex(2)) + .has(allOf(gaugePoint("my.distribution.histogram", 1), bucket(10)), atIndex(3)) + .has(allOf(gaugePoint("my.distribution.histogram", 1), bucket(100)), atIndex(4)) + .has(allOf(gaugePoint("my.distribution.histogram", 2), bucket(1000)), atIndex(5)) + .has(gaugePoint("my.distribution.max", 500), atIndex(6)) + .has(counterPoint("my.distribution.totalTime", 505), atIndex(7)); registry.close(); } private static List getDataPoints(SignalFxMeterRegistry registry, long timestamp) { - return registry.getMeters().stream() - .map(meter -> meter.match(registry::addGauge, registry::addCounter, registry::addTimer, - registry::addDistributionSummary, registry::addLongTaskTimer, registry::addTimeGauge, - registry::addFunctionCounter, registry::addFunctionTimer, registry::addMeter)) - .flatMap(builders -> builders.map(builder -> builder.setTimestamp(timestamp).build())) - .sorted(Comparator.comparing(SignalFxProtocolBuffers.DataPoint::getMetric) - .thenComparing((point) -> point.getDimensions(0).getValue())) - .collect(Collectors.toList()); + return registry.getMeters() + .stream() + .map(meter -> meter.match(registry::addGauge, registry::addCounter, registry::addTimer, + registry::addDistributionSummary, registry::addLongTaskTimer, registry::addTimeGauge, + registry::addFunctionCounter, registry::addFunctionTimer, registry::addMeter)) + .flatMap(builders -> builders.map(builder -> builder.setTimestamp(timestamp).build())) + .sorted(Comparator.comparing(SignalFxProtocolBuffers.DataPoint::getMetric) + .thenComparing((point) -> point.getDimensions(0).getValue())) + .collect(Collectors.toList()); } private static Condition bucket(double bucket) { diff --git a/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/StackdriverConfig.java b/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/StackdriverConfig.java index 30b75f3f08..333a228e6c 100644 --- a/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/StackdriverConfig.java +++ b/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/StackdriverConfig.java @@ -97,8 +97,8 @@ default CredentialsProvider credentials() { try { FixedCredentialsProvider provider = FixedCredentialsProvider - .create(GoogleCredentials.fromStream(new FileInputStream(credentials)) - .createScoped(MetricServiceSettings.getDefaultServiceScopes())); + .create(GoogleCredentials.fromStream(new FileInputStream(credentials)) + .createScoped(MetricServiceSettings.getDefaultServiceScopes())); return Validated.valid(valid.getProperty(), provider); } catch (IOException t) { diff --git a/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/StackdriverMeterRegistry.java b/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/StackdriverMeterRegistry.java index a3b77d90d1..1790265d43 100644 --- a/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/StackdriverMeterRegistry.java +++ b/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/StackdriverMeterRegistry.java @@ -155,17 +155,20 @@ protected void publish() { long partitionSize = Math.min(config.batchSize(), TIMESERIES_PER_REQUEST_LIMIT); Collection> series = getMeters().stream() - .flatMap(meter -> meter.match(m -> createGauge(publishBatch, m), m -> createCounter(publishBatch, m), - m -> createTimer(publishBatch, m), m -> createSummary(publishBatch, m), - m -> createLongTaskTimer(publishBatch, m), m -> createTimeGauge(publishBatch, m), - m -> createFunctionCounter(publishBatch, m), m -> createFunctionTimer(publishBatch, m), - m -> createMeter(publishBatch, m))) - .collect(groupingBy(o -> partitioningCounter.incrementAndGet() / partitionSize)).values(); + .flatMap(meter -> meter.match(m -> createGauge(publishBatch, m), m -> createCounter(publishBatch, m), + m -> createTimer(publishBatch, m), m -> createSummary(publishBatch, m), + m -> createLongTaskTimer(publishBatch, m), m -> createTimeGauge(publishBatch, m), + m -> createFunctionCounter(publishBatch, m), m -> createFunctionTimer(publishBatch, m), + m -> createMeter(publishBatch, m))) + .collect(groupingBy(o -> partitioningCounter.incrementAndGet() / partitionSize)) + .values(); for (List partition : series) { try { CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder() - .setName("projects/" + config.projectId()).addAllTimeSeries(partition).build(); + .setName("projects/" + config.projectId()) + .addAllTimeSeries(partition) + .build(); logger.trace("publishing batch to Stackdriver:{}{}", System.lineSeparator(), request); @@ -180,18 +183,20 @@ protected void publish() { // VisibleForTesting Stream createMeter(Batch batch, Meter m) { - return stream(m.measure().spliterator(), false).map( - ms -> batch.createTimeSeries(m, ms.getValue(), ms.getStatistic().getTagValueRepresentation(), GAUGE)); + return stream(m.measure().spliterator(), false) + .map(ms -> batch.createTimeSeries(m, ms.getValue(), ms.getStatistic().getTagValueRepresentation(), GAUGE)); } // VisibleForTesting Stream createFunctionTimer(Batch batch, FunctionTimer timer) { long count = (long) timer.count(); - Distribution.Builder distribution = Distribution.newBuilder().setMean(timer.mean(getBaseTimeUnit())) - .setCount(count) - .setBucketOptions(Distribution.BucketOptions.newBuilder() - .setExplicitBuckets(Distribution.BucketOptions.Explicit.newBuilder().addBounds(0.0).build())) - .addBucketCounts(0).addBucketCounts(count); + Distribution.Builder distribution = Distribution.newBuilder() + .setMean(timer.mean(getBaseTimeUnit())) + .setCount(count) + .setBucketOptions(Distribution.BucketOptions.newBuilder() + .setExplicitBuckets(Distribution.BucketOptions.Explicit.newBuilder().addBounds(0.0).build())) + .addBucketCounts(0) + .addBucketCounts(count); return Stream.of(batch.createTimeSeries(timer, distribution.build(), null, GAUGE)); } @@ -341,9 +346,9 @@ Stream createTimeSeries(HistogramSupport histogramSupport, boolean t createTimeSeries(histogramSupport, snapshot.count(), "count", config.useSemanticMetricTypes() ? CUMULATIVE : GAUGE)), Arrays.stream(snapshot.percentileValues()) - .map(valueAtP -> createTimeSeries(histogramSupport, - timeDomain ? valueAtP.value(getBaseTimeUnit()) : valueAtP.value(), - "p" + DoubleFormat.wholeOrDecimal(valueAtP.percentile() * 100), GAUGE))); + .map(valueAtP -> createTimeSeries(histogramSupport, + timeDomain ? valueAtP.value(getBaseTimeUnit()) : valueAtP.value(), + "p" + DoubleFormat.wholeOrDecimal(valueAtP.percentile() * 100), GAUGE))); } private TimeSeries createTimeSeries(Meter meter, TypedValue typedValue, MetricDescriptor.ValueType valueType, @@ -355,16 +360,19 @@ private TimeSeries createTimeSeries(Meter meter, TypedValue typedValue, MetricDe String metricType = metricType(id, statistic); Map metricLabels = getConventionTags(id).stream() - .collect(Collectors.toMap(Tag::getKey, Tag::getValue)); + .collect(Collectors.toMap(Tag::getKey, Tag::getValue)); return TimeSeries.newBuilder() - .setMetric(Metric.newBuilder().setType(metricType).putAllLabels(metricLabels).build()) - .setResource(MonitoredResource.newBuilder().setType(config.resourceType()) - .putLabels("project_id", config.projectId()).putAllLabels(config.resourceLabels()).build()) - .setMetricKind(metricKind) // https://cloud.google.com/monitoring/api/v3/metrics-details#metric-kinds - .setValueType(valueType) - .addPoints(Point.newBuilder().setInterval(interval(metricKind)).setValue(typedValue).build()) - .build(); + .setMetric(Metric.newBuilder().setType(metricType).putAllLabels(metricLabels).build()) + .setResource(MonitoredResource.newBuilder() + .setType(config.resourceType()) + .putLabels("project_id", config.projectId()) + .putAllLabels(config.resourceLabels()) + .build()) + .setMetricKind(metricKind) // https://cloud.google.com/monitoring/api/v3/metrics-details#metric-kinds + .setValueType(valueType) + .addPoints(Point.newBuilder().setInterval(interval(metricKind)).setValue(typedValue).build()) + .build(); } private void createMetricDescriptorIfNecessary(MetricServiceClient client, Meter.Id id, @@ -377,14 +385,19 @@ private void createMetricDescriptorIfNecessary(MetricServiceClient client, Meter final String metricType = metricType(id, statistic); if (!verifiedDescriptors.contains(metricType)) { - MetricDescriptor descriptor = MetricDescriptor.newBuilder().setType(metricType) - .setDescription(id.getDescription() == null ? "" : id.getDescription()) - .setMetricKind(metricKind).setValueType(valueType).build(); + MetricDescriptor descriptor = MetricDescriptor.newBuilder() + .setType(metricType) + .setDescription(id.getDescription() == null ? "" : id.getDescription()) + .setMetricKind(metricKind) + .setValueType(valueType) + .build(); ProjectName name = ProjectName.of(config.projectId()); CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest.newBuilder() - .setName(name.toString()).setMetricDescriptor(descriptor).build(); + .setName(name.toString()) + .setMetricDescriptor(descriptor) + .build(); logger.trace("creating metric descriptor:{}{}", System.lineSeparator(), request); @@ -407,12 +420,15 @@ private void prePopulateVerifiedDescriptors() { final String projectName = "projects/" + config.projectId(); final ListMetricDescriptorsRequest listMetricDescriptorsRequest = ListMetricDescriptorsRequest - .newBuilder().setName(projectName).setFilter(filter).build(); + .newBuilder() + .setName(projectName) + .setFilter(filter) + .build(); final MetricServiceClient.ListMetricDescriptorsPagedResponse listMetricDescriptorsPagedResponse = client - .listMetricDescriptors(listMetricDescriptorsRequest); + .listMetricDescriptors(listMetricDescriptorsRequest); listMetricDescriptorsPagedResponse.iterateAll() - .forEach(metricDescriptor -> verifiedDescriptors.add(metricDescriptor.getType())); + .forEach(metricDescriptor -> verifiedDescriptors.add(metricDescriptor.getType())); logger.trace( "Pre populated verified descriptors for project: {}, with filter: {}, existing metrics: {}", @@ -475,8 +491,8 @@ Distribution distribution(HistogramSnapshot snapshot, boolean timeDomain) { bucketCounts.add(Math.max(0, snapshot.count() - truncatedSum.get())); List bucketBoundaries = Arrays.stream(histogram) - .map(countAtBucket -> timeDomain ? countAtBucket.bucket(getBaseTimeUnit()) : countAtBucket.bucket()) - .collect(toCollection(ArrayList::new)); + .map(countAtBucket -> timeDomain ? countAtBucket.bucket(getBaseTimeUnit()) : countAtBucket.bucket()) + .collect(toCollection(ArrayList::new)); if (bucketBoundaries.size() != bucketCounts.size() - 1) { bucketBoundaries = bucketBoundaries.subList(0, bucketCounts.size() - 1); @@ -487,13 +503,15 @@ Distribution distribution(HistogramSnapshot snapshot, boolean timeDomain) { bucketBoundaries.add(0.0); } - return Distribution.newBuilder().setMean(timeDomain ? snapshot.mean(getBaseTimeUnit()) : snapshot.mean()) - .setCount(snapshot.count()) - .setBucketOptions(Distribution.BucketOptions.newBuilder() - .setExplicitBuckets(Distribution.BucketOptions.Explicit.newBuilder() - .addAllBounds(bucketBoundaries).build()) - .build()) - .addAllBucketCounts(bucketCounts).build(); + return Distribution.newBuilder() + .setMean(timeDomain ? snapshot.mean(getBaseTimeUnit()) : snapshot.mean()) + .setCount(snapshot.count()) + .setBucketOptions(Distribution.BucketOptions.newBuilder() + .setExplicitBuckets( + Distribution.BucketOptions.Explicit.newBuilder().addAllBounds(bucketBoundaries).build()) + .build()) + .addAllBucketCounts(bucketCounts) + .build(); } } diff --git a/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/util/ClearCustomMetricDescriptors.java b/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/util/ClearCustomMetricDescriptors.java index 2c96c9e89c..e9b2310195 100644 --- a/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/util/ClearCustomMetricDescriptors.java +++ b/implementations/micrometer-registry-stackdriver/src/main/java/io/micrometer/stackdriver/util/ClearCustomMetricDescriptors.java @@ -46,9 +46,11 @@ public static void clearCustomMetricDescriptors(MetricServiceSettings settings, MetricServiceClient client = MetricServiceClient.create(settings); Iterable listMetricDescriptorsPages = client - .listMetricDescriptors(ListMetricDescriptorsRequest.newBuilder().setName("projects/" + projectId) - .setFilter("metric.type = starts_with(\"custom.googleapis.com/\")").build()) - .iteratePages(); + .listMetricDescriptors(ListMetricDescriptorsRequest.newBuilder() + .setName("projects/" + projectId) + .setFilter("metric.type = starts_with(\"custom.googleapis.com/\")") + .build()) + .iteratePages(); int deleted = 0; for (MetricServiceClient.ListMetricDescriptorsPage page : listMetricDescriptorsPages) { diff --git a/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/MetricSchemaCompatibilityTest.java b/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/MetricSchemaCompatibilityTest.java index f46f83a26f..54b8e34c7a 100644 --- a/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/MetricSchemaCompatibilityTest.java +++ b/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/MetricSchemaCompatibilityTest.java @@ -63,16 +63,17 @@ void backwardCompatibleMetricTypes() { assertSchemaCompatibility(Collections.singletonList(new Pair(GAUGE, DOUBLE)), registry.createFunctionCounter( batch, FunctionCounter.builder("functionCounter", 1, value -> 1).register(registry))); assertSchemaCompatibility(Collections.singletonList(new Pair(GAUGE, DISTRIBUTION)), - registry.createFunctionTimer(batch, FunctionTimer - .builder("functionTimer", 1, value -> 1, value -> 1, TimeUnit.SECONDS).register(registry))); + registry.createFunctionTimer(batch, + FunctionTimer.builder("functionTimer", 1, value -> 1, value -> 1, TimeUnit.SECONDS) + .register(registry))); assertSchemaCompatibility( - Collections.singletonList(new Pair(GAUGE, DOUBLE)), registry - .createMeter( - batch, Meter - .builder("gauge", Meter.Type.OTHER, - Collections - .singletonList(new Measurement(() -> 1.0, Statistic.UNKNOWN))) - .register(registry))); + Collections.singletonList(new Pair(GAUGE, + DOUBLE)), + registry.createMeter(batch, + Meter + .builder("gauge", Meter.Type.OTHER, + Collections.singletonList(new Measurement(() -> 1.0, Statistic.UNKNOWN))) + .register(registry))); } /** @@ -101,16 +102,17 @@ void semanticMetricTypes() { registry.createFunctionCounter(batch, FunctionCounter.builder("functionCounter", 1, value -> 1).register(registry))); assertSchemaCompatibility(Collections.singletonList(new Pair(GAUGE, DISTRIBUTION)), - registry.createFunctionTimer(batch, FunctionTimer - .builder("functionTimer", 1, value -> 1, value -> 1, TimeUnit.SECONDS).register(registry))); + registry.createFunctionTimer(batch, + FunctionTimer.builder("functionTimer", 1, value -> 1, value -> 1, TimeUnit.SECONDS) + .register(registry))); assertSchemaCompatibility( - Collections.singletonList(new Pair(GAUGE, DOUBLE)), registry - .createMeter( - batch, Meter - .builder("gauge", Meter.Type.OTHER, - Collections - .singletonList(new Measurement(() -> 1.0, Statistic.UNKNOWN))) - .register(registry))); + Collections.singletonList(new Pair(GAUGE, + DOUBLE)), + registry.createMeter(batch, + Meter + .builder("gauge", Meter.Type.OTHER, + Collections.singletonList(new Measurement(() -> 1.0, Statistic.UNKNOWN))) + .register(registry))); } private void assertSchemaCompatibility(List expectedValues, Stream timeSeriesStream) { diff --git a/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/StackdriverConfigTest.java b/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/StackdriverConfigTest.java index fdb2cbe32f..c802903587 100644 --- a/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/StackdriverConfigTest.java +++ b/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/StackdriverConfigTest.java @@ -34,7 +34,7 @@ void invalid() { props.put("stackdriver.credentials", "bad"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsExactlyInAnyOrder("is required", "cannot read credentials file"); + .containsExactlyInAnyOrder("is required", "cannot read credentials file"); } @Test diff --git a/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/StackdriverNamingConventionTest.java b/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/StackdriverNamingConventionTest.java index c9ffdd780b..17a784ee54 100644 --- a/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/StackdriverNamingConventionTest.java +++ b/implementations/micrometer-registry-stackdriver/src/test/java/io/micrometer/stackdriver/StackdriverNamingConventionTest.java @@ -48,8 +48,8 @@ void tagValue() { void tooLongTagValue() { assertThat(namingConvention.tagValue( "thisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolong")) - .isEqualTo( - "thisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistool"); + .isEqualTo( + "thisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistool"); } } diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdFunctionCounter.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdFunctionCounter.java index 7860ba5187..1db878aec2 100644 --- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdFunctionCounter.java +++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdFunctionCounter.java @@ -27,7 +27,7 @@ * @param the type of the state object from which the counter value is extracted * @author Jon Schneider */ -public class StatsdFunctionCounter extends CumulativeFunctionCounter implements StatsdPollable { +public class StatsdFunctionCounterextends CumulativeFunctionCounter implements StatsdPollable { private final StatsdLineBuilder lineBuilder; diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdFunctionTimer.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdFunctionTimer.java index 6f1f5506a4..d94ce3968d 100644 --- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdFunctionTimer.java +++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdFunctionTimer.java @@ -23,7 +23,7 @@ import java.util.function.ToDoubleFunction; import java.util.function.ToLongFunction; -public class StatsdFunctionTimer extends CumulativeFunctionTimer implements StatsdPollable { +public class StatsdFunctionTimerextends CumulativeFunctionTimer implements StatsdPollable { private final StatsdLineBuilder lineBuilder; diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdGauge.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdGauge.java index 58763fe980..d42cf99339 100644 --- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdGauge.java +++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdGauge.java @@ -24,7 +24,7 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.ToDoubleFunction; -public class StatsdGauge extends AbstractMeter implements Gauge, StatsdPollable { +public class StatsdGaugeextends AbstractMeter implements Gauge, StatsdPollable { private final StatsdLineBuilder lineBuilder; diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdMeterRegistry.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdMeterRegistry.java index 3a2af34595..793f3d1440 100644 --- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdMeterRegistry.java +++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdMeterRegistry.java @@ -219,8 +219,10 @@ public void onComplete() { else { final Publisher publisher; if (statsdConfig.buffered()) { - publisher = BufferingFlux.create(Flux.from(this.processor), "\n", statsdConfig.maxPacketLength(), - statsdConfig.pollingFrequency().toMillis()).onBackpressureLatest(); + publisher = BufferingFlux + .create(Flux.from(this.processor), "\n", statsdConfig.maxPacketLength(), + statsdConfig.pollingFrequency().toMillis()) + .onBackpressureLatest(); } else { publisher = this.processor; @@ -241,28 +243,33 @@ else if (statsdConfig.protocol() == StatsdProtocol.TCP) { private void prepareUdpClient(Publisher publisher, Supplier remoteAddress) { AtomicReference udpClientReference = new AtomicReference<>(); - UdpClient udpClient = UdpClient.create().remoteAddress(remoteAddress) - .handle((in, out) -> out.sendString(publisher).neverComplete().retryWhen( - Retry.indefinitely().filter(throwable -> throwable instanceof PortUnreachableException))) - .doOnDisconnected(connection -> { - Boolean connectionDisposed = connection.channel().attr(CONNECTION_DISPOSED).getAndSet(Boolean.TRUE); - if (connectionDisposed == null || !connectionDisposed) { - connectAndSubscribe(udpClientReference.get()); - } - }); + UdpClient udpClient = UdpClient.create() + .remoteAddress(remoteAddress) + .handle((in, out) -> out.sendString(publisher) + .neverComplete() + .retryWhen(Retry.indefinitely().filter(throwable -> throwable instanceof PortUnreachableException))) + .doOnDisconnected(connection -> { + Boolean connectionDisposed = connection.channel().attr(CONNECTION_DISPOSED).getAndSet(Boolean.TRUE); + if (connectionDisposed == null || !connectionDisposed) { + connectAndSubscribe(udpClientReference.get()); + } + }); udpClientReference.set(udpClient); connectAndSubscribe(udpClient); } private void prepareTcpClient(Publisher publisher) { AtomicReference tcpClientReference = new AtomicReference<>(); - TcpClient tcpClient = TcpClient.create().host(statsdConfig.host()).port(statsdConfig.port()) - .handle((in, out) -> out.sendString(publisher).neverComplete()).doOnDisconnected(connection -> { - Boolean connectionDisposed = connection.channel().attr(CONNECTION_DISPOSED).getAndSet(Boolean.TRUE); - if (connectionDisposed == null || !connectionDisposed) { - connectAndSubscribe(tcpClientReference.get()); - } - }); + TcpClient tcpClient = TcpClient.create() + .host(statsdConfig.host()) + .port(statsdConfig.port()) + .handle((in, out) -> out.sendString(publisher).neverComplete()) + .doOnDisconnected(connection -> { + Boolean connectionDisposed = connection.channel().attr(CONNECTION_DISPOSED).getAndSet(Boolean.TRUE); + if (connectionDisposed == null || !connectionDisposed) { + connectAndSubscribe(tcpClientReference.get()); + } + }); tcpClientReference.set(tcpClient); connectAndSubscribe(tcpClient); } @@ -287,13 +294,13 @@ private void connectAndSubscribe(UdpClient udpClient) { private void retryReplaceClient(Mono connectMono) { connectMono.retryWhen(Retry.backoff(Long.MAX_VALUE, Duration.ofSeconds(1)).maxBackoff(Duration.ofMinutes(1))) - .subscribe(connection -> { - this.statsdConnection.replace(connection); + .subscribe(connection -> { + this.statsdConnection.replace(connection); - // now that we're connected, start polling gauges and other pollable - // meter types - startPolling(); - }); + // now that we're connected, start polling gauges and other pollable + // meter types + startPolling(); + }); } private void startPolling() { @@ -353,10 +360,14 @@ private StatsdLineBuilder lineBuilder(Meter.Id id, private DistributionStatisticConfig addInfBucket(DistributionStatisticConfig config) { double[] serviceLevelObjectives = config.getServiceLevelObjectiveBoundaries() == null ? new double[] { Double.POSITIVE_INFINITY } - : DoubleStream.concat(Arrays.stream(config.getServiceLevelObjectiveBoundaries()), - DoubleStream.of(Double.POSITIVE_INFINITY)).toArray(); - return DistributionStatisticConfig.builder().serviceLevelObjectives(serviceLevelObjectives).build() - .merge(config); + : DoubleStream + .concat(Arrays.stream(config.getServiceLevelObjectiveBoundaries()), + DoubleStream.of(Double.POSITIVE_INFINITY)) + .toArray(); + return DistributionStatisticConfig.builder() + .serviceLevelObjectives(serviceLevelObjectives) + .build() + .merge(config); } @Override @@ -448,8 +459,10 @@ protected TimeUnit getBaseTimeUnit() { @Override protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.builder().expiry(statsdConfig.step()).build() - .merge(DistributionStatisticConfig.DEFAULT); + return DistributionStatisticConfig.builder() + .expiry(statsdConfig.step()) + .build() + .merge(DistributionStatisticConfig.DEFAULT); } /** diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/BufferingFlux.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/BufferingFlux.java index 1a9fd4ff5c..e63413531f 100644 --- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/BufferingFlux.java +++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/BufferingFlux.java @@ -51,14 +51,15 @@ public static Flux create(final Flux source, final String delimi final DirectProcessor intervalEnd = DirectProcessor.create(); - final Flux heartbeat = Flux.interval(Duration.ofMillis(maxMillisecondsBetweenEmits)).map(l -> "") - .takeUntilOther(intervalEnd); + final Flux heartbeat = Flux.interval(Duration.ofMillis(maxMillisecondsBetweenEmits)) + .map(l -> "") + .takeUntilOther(intervalEnd); // Create a stream that emits at least once every // $maxMillisecondsBetweenEmits, to avoid long pauses between // buffer flushes when the source doesn't emit for a while. final Flux sourceWithEmptyStringKeepAlive = source.doOnTerminate(intervalEnd::onComplete) - .mergeWith(heartbeat); + .mergeWith(heartbeat); return sourceWithEmptyStringKeepAlive.bufferUntil(line -> { final int bytesLength = line.getBytes().length; @@ -93,7 +94,9 @@ public static Flux create(final Flux source, final String delimi } return false; - }, true).map(lines -> lines.stream().filter(line -> !line.isEmpty()) + }, true) + .map(lines -> lines.stream() + .filter(line -> !line.isEmpty()) .collect(Collectors.joining(delimiter, "", delimiter))); }); } diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/EtsyStatsdLineBuilder.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/EtsyStatsdLineBuilder.java index 880be77c4a..e9d8a5f791 100644 --- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/EtsyStatsdLineBuilder.java +++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/EtsyStatsdLineBuilder.java @@ -70,7 +70,7 @@ private String nameByStatistic(@Nullable Statistic stat) { private String etsyName(@Nullable Statistic stat) { return nameMapper.toHierarchicalName(stat != null ? id.withTag(stat) : id, config.namingConvention()) - .replace(':', '_'); + .replace(':', '_'); } } diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/FlavorStatsdLineBuilder.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/FlavorStatsdLineBuilder.java index be41ab69d6..593b37b2a3 100644 --- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/FlavorStatsdLineBuilder.java +++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/FlavorStatsdLineBuilder.java @@ -71,7 +71,9 @@ public String timing(double timeMs) { protected String tags(@Nullable Statistic stat, @Nullable String otherTags, String keyValueSeparator, String preamble) { String tags = of(stat == null ? null : "statistic" + keyValueSeparator + stat.getTagValueRepresentation(), - otherTags).filter(Objects::nonNull).collect(Collectors.joining(",")); + otherTags) + .filter(Objects::nonNull) + .collect(Collectors.joining(",")); if (!tags.isEmpty()) tags = preamble + tags; diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/SysdigStatsdLineBuilder.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/SysdigStatsdLineBuilder.java index 31ed743d1b..9e9b7e328a 100644 --- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/SysdigStatsdLineBuilder.java +++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/SysdigStatsdLineBuilder.java @@ -62,9 +62,10 @@ private void updateIfNamingConventionChanged() { this.name = sanitize(next.name(id.getName(), id.getType(), id.getBaseUnit())); synchronized (conventionTagsLock) { this.tags.clear(); - this.conventionTags = id.getTagsAsIterable().iterator().hasNext() ? id.getConventionTags(next).stream() - .map(t -> sanitize(t.getKey()) + "=" + sanitize(t.getValue())).collect(Collectors.joining(",")) - : null; + this.conventionTags = id.getTagsAsIterable().iterator().hasNext() ? id.getConventionTags(next) + .stream() + .map(t -> sanitize(t.getKey()) + "=" + sanitize(t.getValue())) + .collect(Collectors.joining(",")) : null; } this.tagsNoStat = tags(null, conventionTags, "=", "#"); this.namingConvention = next; diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/TelegrafStatsdLineBuilder.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/TelegrafStatsdLineBuilder.java index c31e2a4b81..e571c38fb0 100644 --- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/TelegrafStatsdLineBuilder.java +++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/TelegrafStatsdLineBuilder.java @@ -61,9 +61,10 @@ private void updateIfNamingConventionChanged() { return; } this.tags.clear(); - this.conventionTags = id.getTagsAsIterable().iterator().hasNext() ? id.getConventionTags(next).stream() - .map(t -> telegrafEscape(t.getKey()) + "=" + telegrafEscape(t.getValue())) - .collect(Collectors.joining(",")) : null; + this.conventionTags = id.getTagsAsIterable().iterator().hasNext() ? id.getConventionTags(next) + .stream() + .map(t -> telegrafEscape(t.getKey()) + "=" + telegrafEscape(t.getValue())) + .collect(Collectors.joining(",")) : null; } this.name = telegrafEscape(next.name(id.getName(), id.getType(), id.getBaseUnit())); this.tagsNoStat = tags(null, conventionTags, "=", ","); diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdConfigTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdConfigTest.java index aeddbab315..efcc917065 100644 --- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdConfigTest.java +++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdConfigTest.java @@ -37,9 +37,9 @@ void invalid() { props.put("statsd.step", "1w"); assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage)) - .containsOnly("should be one of 'ETSY', 'DATADOG', 'TELEGRAF', 'SYSDIG'", - "should be one of 'UDP', 'UDS_DATAGRAM', 'TCP'", "must contain a valid time unit") - .hasSize(4); + .containsOnly("should be one of 'ETSY', 'DATADOG', 'TELEGRAF', 'SYSDIG'", + "should be one of 'UDP', 'UDS_DATAGRAM', 'TCP'", "must contain a valid time unit") + .hasSize(4); } @Test diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdGaugeTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdGaugeTest.java index 9794c3e8d2..1353e51645 100644 --- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdGaugeTest.java +++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdGaugeTest.java @@ -31,10 +31,11 @@ class StatsdGaugeTest { void shouldAlwaysPublishValue() { AtomicInteger lines = new AtomicInteger(); MeterRegistry registry = StatsdMeterRegistry.builder(StatsdConfig.DEFAULT) - .lineSink(l -> lines.incrementAndGet()).build(); + .lineSink(l -> lines.incrementAndGet()) + .build(); StatsdGauge alwaysPublishingGauge = (StatsdGauge) Gauge.builder("test", value, AtomicInteger::get) - .register(registry); + .register(registry); alwaysPublishingGauge.poll(); alwaysPublishingGauge.poll(); @@ -58,7 +59,7 @@ public boolean publishUnchangedMeters() { }).lineSink(l -> lines.incrementAndGet()).build(); StatsdGauge gaugePublishingOnChange = (StatsdGauge) Gauge.builder("test", value, AtomicInteger::get) - .register(registry); + .register(registry); gaugePublishingOnChange.poll(); gaugePublishingOnChange.poll(); diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdMeterRegistryPublishTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdMeterRegistryPublishTest.java index d0bf284ba4..054d802430 100644 --- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdMeterRegistryPublishTest.java +++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdMeterRegistryPublishTest.java @@ -271,8 +271,9 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) ((Connection) meterRegistry.statsdConnection.get()).removeHandler("writeFailure"); IntStream.range(1, 4).forEach(counter::increment); assertThat(serverLatch.await(3, TimeUnit.SECONDS)).isTrue(); - await().pollDelay(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(3)) - .until(() -> serverMetricReadCount.get() == 3); + await().pollDelay(Duration.ofSeconds(1)) + .atMost(Duration.ofSeconds(3)) + .until(() -> serverMetricReadCount.get() == 3); } @Issue("#2880") @@ -310,15 +311,14 @@ private void trackWritesForUdpClient(StatsdProtocol protocol, AtomicInteger writ if (protocol == StatsdProtocol.UDP) { await().until(() -> meterRegistry.statsdConnection.get() != null); ((Connection) meterRegistry.statsdConnection.get()) - .addHandlerFirst(new LoggingHandler("testudpclient", LogLevel.INFO)) - .addHandlerFirst(new ChannelOutboundHandlerAdapter() { - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) - throws Exception { - writeCount.incrementAndGet(); - super.write(ctx, msg, promise); - } - }); + .addHandlerFirst(new LoggingHandler("testudpclient", LogLevel.INFO)) + .addHandlerFirst(new ChannelOutboundHandlerAdapter() { + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + writeCount.incrementAndGet(); + super.write(ctx, msg, promise); + } + }); } } @@ -334,31 +334,40 @@ private boolean clientIsDisposed() { private DisposableChannel startServer(StatsdProtocol protocol, int port) { if (protocol == StatsdProtocol.UDP || protocol == StatsdProtocol.UDS_DATAGRAM) { return UdpServer.create() - .bindAddress(() -> protocol == StatsdProtocol.UDP - ? InetSocketAddress.createUnresolved("localhost", port) : newDomainSocketAddress()) - .handle((in, out) -> in.receive().asString().flatMap(packet -> { - serverLatch.countDown(); - serverMetricReadCount.getAndIncrement(); - return Flux.never(); - })).doOnBound((server) -> bound = true).doOnUnbound((server) -> bound = false) - .wiretap("udpserver", LogLevel.INFO).bindNow(Duration.ofSeconds(2)); + .bindAddress(() -> protocol == StatsdProtocol.UDP + ? InetSocketAddress.createUnresolved("localhost", port) : newDomainSocketAddress()) + .handle((in, out) -> in.receive().asString().flatMap(packet -> { + serverLatch.countDown(); + serverMetricReadCount.getAndIncrement(); + return Flux.never(); + })) + .doOnBound((server) -> bound = true) + .doOnUnbound((server) -> bound = false) + .wiretap("udpserver", LogLevel.INFO) + .bindNow(Duration.ofSeconds(2)); } else if (protocol == StatsdProtocol.TCP) { AtomicReference channel = new AtomicReference<>(); - return TcpServer.create().host("localhost").port(port) - .handle((in, out) -> in.receive().asString().flatMap(packet -> { - IntStream.range(0, packet.split("my.counter").length - 1).forEach(i -> { - serverLatch.countDown(); - serverMetricReadCount.getAndIncrement(); - }); - in.withConnection(channel::set); - return Flux.never(); - })).doOnBound((server) -> bound = true).doOnUnbound((server) -> { - bound = false; - if (channel.get() != null) { - channel.get().dispose(); - } - }).wiretap("tcpserver", LogLevel.INFO).bindNow(Duration.ofSeconds(5)); + return TcpServer.create() + .host("localhost") + .port(port) + .handle((in, out) -> in.receive().asString().flatMap(packet -> { + IntStream.range(0, packet.split("my.counter").length - 1).forEach(i -> { + serverLatch.countDown(); + serverMetricReadCount.getAndIncrement(); + }); + in.withConnection(channel::set); + return Flux.never(); + })) + .doOnBound((server) -> bound = true) + .doOnUnbound((server) -> { + bound = false; + if (channel.get() != null) { + channel.get().dispose(); + } + }) + .wiretap("tcpserver", LogLevel.INFO) + .bindNow(Duration.ofSeconds(5)); } else { throw new IllegalArgumentException( diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdMeterRegistryTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdMeterRegistryTest.java index 615c836cf8..3d4a2d88d5 100644 --- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdMeterRegistryTest.java +++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/StatsdMeterRegistryTest.java @@ -106,11 +106,15 @@ void counterLineProtocol(StatsdFlavor flavor) { } final Processor lines = lineProcessor(); - registry = StatsdMeterRegistry.builder(configWithFlavor(flavor)).clock(clock).lineSink(toLineSink(lines)) - .build(); + registry = StatsdMeterRegistry.builder(configWithFlavor(flavor)) + .clock(clock) + .lineSink(toLineSink(lines)) + .build(); - StepVerifier.create(lines).then(() -> registry.counter("my.counter", "my.tag", "val").increment(2.1)) - .expectNext(line).verifyComplete(); + StepVerifier.create(lines) + .then(() -> registry.counter("my.counter", "my.tag", "val").increment(2.1)) + .expectNext(line) + .verifyComplete(); } @ParameterizedTest @@ -168,12 +172,15 @@ void timerLineProtocol(StatsdFlavor flavor) { } final Processor lines = lineProcessor(); - registry = StatsdMeterRegistry.builder(configWithFlavor(flavor)).clock(clock).lineSink(toLineSink(lines)) - .build(); + registry = StatsdMeterRegistry.builder(configWithFlavor(flavor)) + .clock(clock) + .lineSink(toLineSink(lines)) + .build(); StepVerifier.create(lines) - .then(() -> registry.timer("my.timer", "my.tag", "val").record(1, TimeUnit.MILLISECONDS)) - .expectNext(line).verifyComplete(); + .then(() -> registry.timer("my.timer", "my.tag", "val").record(1, TimeUnit.MILLISECONDS)) + .expectNext(line) + .verifyComplete(); } @ParameterizedTest @@ -198,11 +205,15 @@ void summaryLineProtocol(StatsdFlavor flavor) { } final Processor lines = lineProcessor(); - registry = StatsdMeterRegistry.builder(configWithFlavor(flavor)).clock(clock).lineSink(toLineSink(lines)) - .build(); + registry = StatsdMeterRegistry.builder(configWithFlavor(flavor)) + .clock(clock) + .lineSink(toLineSink(lines)) + .build(); - StepVerifier.create(lines).then(() -> registry.summary("my.summary", "my.tag", "val").record(1)) - .expectNext(line).verifyComplete(); + StepVerifier.create(lines) + .then(() -> registry.summary("my.summary", "my.tag", "val").record(1)) + .expectNext(line) + .verifyComplete(); } @ParameterizedTest @@ -242,19 +253,28 @@ void longTaskTimerLineProtocol(StatsdFlavor flavor) { ltt.set(registry.more().longTaskTimer("my.long.task", "my.tag", "val")); return lines; - }).then(() -> sample.set(ltt.get().start())).then(() -> clock.add(config.step())).thenAwait(config.step()) - .expectNext(expectLines[0]).expectNext(expectLines[1]).verifyComplete(); + }) + .then(() -> sample.set(ltt.get().start())) + .then(() -> clock.add(config.step())) + .thenAwait(config.step()) + .expectNext(expectLines[0]) + .expectNext(expectLines[1]) + .verifyComplete(); } @Test void customNamingConvention() { final Processor lines = lineProcessor(); registry = StatsdMeterRegistry.builder(configWithFlavor(StatsdFlavor.ETSY)) - .nameMapper((id, convention) -> id.getName().toUpperCase()).clock(clock).lineSink(toLineSink(lines)) - .build(); + .nameMapper((id, convention) -> id.getName().toUpperCase()) + .clock(clock) + .lineSink(toLineSink(lines)) + .build(); - StepVerifier.create(lines).then(() -> registry.counter("my.counter", "my.tag", "val").increment(2.1)) - .expectNext("MY.COUNTER:2|c").verifyComplete(); + StepVerifier.create(lines) + .then(() -> registry.counter("my.counter", "my.tag", "val").increment(2.1)) + .expectNext("MY.COUNTER:2|c") + .verifyComplete(); } @Issue("#411") @@ -277,8 +297,9 @@ void counterIncrementDoesNotCauseStackOverflow() { void serviceLevelObjectivesOnlyNoPercentileHistogram(StatsdFlavor flavor) { StatsdConfig config = configWithFlavor(flavor); registry = new StatsdMeterRegistry(config, clock); - DistributionSummary summary = DistributionSummary.builder("my.summary").serviceLevelObjectives(1.0, 2) - .register(registry); + DistributionSummary summary = DistributionSummary.builder("my.summary") + .serviceLevelObjectives(1.0, 2) + .register(registry); summary.record(1); Timer timer = Timer.builder("my.timer").serviceLevelObjectives(Duration.ofMillis(1)).register(registry); @@ -318,8 +339,9 @@ void timersWithServiceLevelObjectivesHaveInfBucket() { @Test void distributionSummariesWithServiceLevelObjectivesHaveInfBucket() { registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); - DistributionSummary summary = DistributionSummary.builder("my.distribution").serviceLevelObjectives(1.0) - .register(registry); + DistributionSummary summary = DistributionSummary.builder("my.distribution") + .serviceLevelObjectives(1.0) + .register(registry); // A io.micrometer.core.instrument.search.MeterNotFoundException is thrown if the // gauge isn't present @@ -359,8 +381,10 @@ void timerSentAsDatadogDistribution_whenPercentileHistogramEnabled() { StepVerifier.create(lines).then(() -> { Timer.builder("my.timer").publishPercentileHistogram(true).register(registry).record(2, TimeUnit.SECONDS); - Timer.builder("my.timer2").publishPercentileHistogram(false).register(registry).record(20, - TimeUnit.SECONDS); + Timer.builder("my.timer2") + .publishPercentileHistogram(false) + .register(registry) + .record(20, TimeUnit.SECONDS); }).expectNext("my.timer:2000|d").expectNext("my.timer2:20000|ms").verifyComplete(); } @@ -423,7 +447,7 @@ void doNotPublishNanOrInfiniteGaugeValues() { AtomicReference value = new AtomicReference<>(1.0); StatsdGauge gauge = (StatsdGauge) Gauge.builder("my.gauge", value, AtomicReference::get) - .register(registry); + .register(registry); gauge.poll(); assertThat(lineCount.get()).isEqualTo(1); @@ -470,16 +494,16 @@ void stopTrackingMetersThatAreRemoved() { }).build(); Meter custom = Meter - .builder("custom", Meter.Type.COUNTER, singletonList(new Measurement(() -> 1.0, Statistic.COUNT))) - .register(registry); + .builder("custom", Meter.Type.COUNTER, singletonList(new Measurement(() -> 1.0, Statistic.COUNT))) + .register(registry); registry.poll(); registry.remove(custom); registry.poll(); assertThat(lines.get("custom")).isEqualTo(1); AtomicInteger tgObj = new AtomicInteger(1); - registry.more().timeGauge("timegauge", Tags.empty(), tgObj, TimeUnit.MILLISECONDS, - AtomicInteger::incrementAndGet); + registry.more() + .timeGauge("timegauge", Tags.empty(), tgObj, TimeUnit.MILLISECONDS, AtomicInteger::incrementAndGet); registry.poll(); registry.remove(registry.get("timegauge").timeGauge()); registry.poll(); @@ -519,8 +543,9 @@ void stopTrackingMetersThatAreRemoved() { // for each poll AtomicInteger ftObj = new AtomicInteger(1); - registry.more().timer("functiontimer", Tags.empty(), ftObj, AtomicInteger::incrementAndGet, AtomicInteger::get, - TimeUnit.MILLISECONDS); + registry.more() + .timer("functiontimer", Tags.empty(), ftObj, AtomicInteger::incrementAndGet, AtomicInteger::get, + TimeUnit.MILLISECONDS); registry.poll(); registry.remove(registry.get("functiontimer").functionTimer()); registry.poll(); diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/BufferingFluxTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/BufferingFluxTest.java index a8659ac94e..d5e70ca17e 100644 --- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/BufferingFluxTest.java +++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/BufferingFluxTest.java @@ -40,12 +40,16 @@ class BufferingFluxTest { @Test void bufferSingleStrings() { Flux source = Flux.just("twelve bytes", "fourteen bytes", "twelve bytes", "fourteen bytes") - .delayElements(Duration.ofMillis(50)); + .delayElements(Duration.ofMillis(50)); Flux buffered = BufferingFlux.create(source, "\n", 14, 200); - StepVerifier.create(buffered).expectNext("twelve bytes\n").expectNext("fourteen bytes\n") - .expectNext("twelve bytes\n").expectNext("fourteen bytes\n").verifyComplete(); + StepVerifier.create(buffered) + .expectNext("twelve bytes\n") + .expectNext("fourteen bytes\n") + .expectNext("twelve bytes\n") + .expectNext("fourteen bytes\n") + .verifyComplete(); } @Test @@ -54,8 +58,10 @@ void bufferMultipleStrings() { Flux buffered = BufferingFlux.create(source, "\n", 27, 1000); - StepVerifier.create(buffered).expectNext("twelve bytes\nfourteen bytes\n") - .expectNext("twelve bytes\nfourteen bytes\n").verifyComplete(); + StepVerifier.create(buffered) + .expectNext("twelve bytes\nfourteen bytes\n") + .expectNext("twelve bytes\nfourteen bytes\n") + .verifyComplete(); } @Test @@ -73,8 +79,10 @@ void bufferUntilTimeout() { Flux buffered = BufferingFlux.create(source, "\n", Integer.MAX_VALUE, 50); - StepVerifier.create(buffered).expectNext("twelve bytes\nfourteen bytes\ntwelve bytes\n") - .expectNext("fourteen bytes\n").verifyComplete(); + StepVerifier.create(buffered) + .expectNext("twelve bytes\nfourteen bytes\ntwelve bytes\n") + .expectNext("fourteen bytes\n") + .verifyComplete(); } /** diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilderTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilderTest.java index 0f4ec2ed19..988ecbc22c 100644 --- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilderTest.java +++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilderTest.java @@ -89,7 +89,7 @@ void appendDdEntityIdTag() { registry.config().namingConvention(NamingConvention.dot); assertThat(lb.line("1", Statistic.COUNT, "c")) - .isEqualTo("my_counter:1|c|#statistic:count,mytag:myvalue,dd.internal.entity_id:test-entity-id"); + .isEqualTo("my_counter:1|c|#statistic:count,mytag:myvalue,dd.internal.entity_id:test-entity-id"); } @Issue("#1998") diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/SysdigStatsdLineBuilderTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/SysdigStatsdLineBuilderTest.java index 7c932cd732..cb08a3f3a8 100644 --- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/SysdigStatsdLineBuilderTest.java +++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/SysdigStatsdLineBuilderTest.java @@ -63,8 +63,8 @@ void sanitizeAllNonAlphaNumericCharacters() { registry.config().namingConvention(NamingConvention.dot); StringBuilder expected = new StringBuilder(); expected.append("___________.__a_counter__with123_weirdChars") - .append("#statistic=count,___________.__a_tag__with123_weirdChars") - .append("=___________.__a_value__with123_weirdChars:1|c"); + .append("#statistic=count,___________.__a_tag__with123_weirdChars") + .append("=___________.__a_value__with123_weirdChars:1|c"); assertThat(lb.line("1", Statistic.COUNT, "c")).isEqualTo(expected.toString()); } diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/TelegrafStatsdLineBuilderTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/TelegrafStatsdLineBuilderTest.java index 15da4175be..667136a308 100644 --- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/TelegrafStatsdLineBuilderTest.java +++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/TelegrafStatsdLineBuilderTest.java @@ -35,7 +35,7 @@ void escapeCharactersForTelegraf() { Counter c = registry.counter("hikari.pools", "pool", "poolname = abc,::hikari"); TelegrafStatsdLineBuilder lineBuilder = new TelegrafStatsdLineBuilder(c.getId(), registry.config()); assertThat(lineBuilder.count(1, Statistic.COUNT)) - .isEqualTo("hikari_pools,statistic=count,pool=poolname_=_abc___hikari:1|c"); + .isEqualTo("hikari_pools,statistic=count,pool=poolname_=_abc___hikari:1|c"); } @Test diff --git a/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontConfig.java b/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontConfig.java index 0e948fbc5e..406146379a 100644 --- a/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontConfig.java +++ b/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontConfig.java @@ -119,9 +119,9 @@ default String source() { @Nullable default String apiToken() { return getSecret(this, "apiToken") - .invalidateWhen(token -> token == null && WavefrontMeterRegistry.isDirectToApi(this), - "must be set whenever publishing directly to the Wavefront API", InvalidReason.MISSING) - .orElse(null); + .invalidateWhen(token -> token == null && WavefrontMeterRegistry.isDirectToApi(this), + "must be set whenever publishing directly to the Wavefront API", InvalidReason.MISSING) + .orElse(null); } /** @@ -169,9 +169,9 @@ default Validated validate() { default Validated validateSenderConfiguration() { return checkAll(this, c -> validate(), checkRequired("uri", WavefrontConfig::uri), - check("apiToken", WavefrontConfig::apiToken).andThen(v -> v.invalidateWhen( - token -> token == null && WavefrontMeterRegistry.isDirectToApi(this), - "must be set whenever publishing directly to the Wavefront API", InvalidReason.MISSING))); + check("apiToken", WavefrontConfig::apiToken) + .andThen(v -> v.invalidateWhen(token -> token == null && WavefrontMeterRegistry.isDirectToApi(this), + "must be set whenever publishing directly to the Wavefront API", InvalidReason.MISSING))); } } diff --git a/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontMeterRegistry.java b/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontMeterRegistry.java index e2637933c0..7759f56475 100644 --- a/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontMeterRegistry.java +++ b/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontMeterRegistry.java @@ -305,7 +305,7 @@ void publishDistribution(Meter.Id id, List private Map getTagsAsMap(Meter.Id id) { return getConventionTags(id).stream() - .collect(Collectors.toMap(Tag::getKey, Tag::getValue, (tag1, tag2) -> tag2)); + .collect(Collectors.toMap(Tag::getKey, Tag::getValue, (tag1, tag2) -> tag2)); } private Meter.Id idWithSuffix(Meter.Id id, String suffix) { @@ -319,8 +319,10 @@ protected TimeUnit getBaseTimeUnit() { @Override protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.builder().expiry(config.step()).build() - .merge(DistributionStatisticConfig.DEFAULT); + return DistributionStatisticConfig.builder() + .expiry(config.step()) + .build() + .merge(DistributionStatisticConfig.DEFAULT); } @Override @@ -352,7 +354,8 @@ static String getWavefrontReportingUri(WavefrontConfig wavefrontConfig) { */ public static WavefrontClient.Builder getDefaultSenderBuilder(WavefrontConfig config) { return new WavefrontClient.Builder(getWavefrontReportingUri(config), config.apiToken()) - .batchSize(config.batchSize()).flushInterval((int) config.step().toMillis(), TimeUnit.MILLISECONDS); + .batchSize(config.batchSize()) + .flushInterval((int) config.step().toMillis(), TimeUnit.MILLISECONDS); } public static Builder builder(WavefrontConfig config) { diff --git a/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontNamingConvention.java b/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontNamingConvention.java index da4022cd53..17dc7ba367 100644 --- a/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontNamingConvention.java +++ b/implementations/micrometer-registry-wavefront/src/main/java/io/micrometer/wavefront/WavefrontNamingConvention.java @@ -81,8 +81,8 @@ public String tagKey(String key) { @Override public String tagValue(String value) { String sanitized = delegate.tagValue(value); - return StringEscapeUtils.escapeJson( - sanitized.endsWith("\\") ? sanitized.substring(0, sanitized.length() - 1) + "_" : sanitized); + return StringEscapeUtils + .escapeJson(sanitized.endsWith("\\") ? sanitized.substring(0, sanitized.length() - 1) + "_" : sanitized); } } diff --git a/implementations/micrometer-registry-wavefront/src/test/java/io/micrometer/wavefront/WavefrontMeterRegistryTest.java b/implementations/micrometer-registry-wavefront/src/test/java/io/micrometer/wavefront/WavefrontMeterRegistryTest.java index 2afd2238cb..341e806709 100644 --- a/implementations/micrometer-registry-wavefront/src/test/java/io/micrometer/wavefront/WavefrontMeterRegistryTest.java +++ b/implementations/micrometer-registry-wavefront/src/test/java/io/micrometer/wavefront/WavefrontMeterRegistryTest.java @@ -73,8 +73,10 @@ public String source() { private final WavefrontSender wavefrontSender = spy(WavefrontSender.class); - private final WavefrontMeterRegistry registry = WavefrontMeterRegistry.builder(config).clock(clock) - .wavefrontSender(wavefrontSender).build(); + private final WavefrontMeterRegistry registry = WavefrontMeterRegistry.builder(config) + .clock(clock) + .wavefrontSender(wavefrontSender) + .build(); @Test void publishMetric() throws IOException { @@ -128,7 +130,7 @@ void publishDistribution() throws IOException { long time = System.currentTimeMillis(); List> centroids = Arrays.asList(new Pair<>(1d, 1)); List distributions = Arrays - .asList(new WavefrontHistogramImpl.Distribution(time, centroids)); + .asList(new WavefrontHistogramImpl.Distribution(time, centroids)); registry.publishDistribution(id, distributions); verify(wavefrontSender, times(1)).sendDistribution("name", centroids, Collections.singleton(HistogramGranularity.MINUTE), time, "host", Collections.emptyMap()); @@ -176,8 +178,8 @@ public Duration step() { assertThat(builder).hasFieldOrPropertyWithValue("flushInterval", 15_000L); assertThat(builder).hasFieldOrPropertyWithValue("flushIntervalTimeUnit", TimeUnit.MILLISECONDS); assertThat(sender).extracting("metricsReportingService") - .hasFieldOrPropertyWithValue("uri", URI.create("https://example.com")) - .hasFieldOrPropertyWithValue("token", "apiToken"); + .hasFieldOrPropertyWithValue("uri", URI.create("https://example.com")) + .hasFieldOrPropertyWithValue("token", "apiToken"); assertThat(sender).hasFieldOrPropertyWithValue("batchSize", 20); } @@ -196,7 +198,7 @@ public String apiToken() { }; assertThatExceptionOfType(ValidationException.class) - .isThrownBy(() -> WavefrontMeterRegistry.builder(missingUriConfig).build()); + .isThrownBy(() -> WavefrontMeterRegistry.builder(missingUriConfig).build()); } @Test @@ -204,7 +206,7 @@ void failsWithDefaultSenderWhenApiTokenMissingAndDirectToApi() { WavefrontConfig missingApiTokenDirectConfig = WavefrontConfig.DEFAULT_DIRECT; assertThatExceptionOfType(ValidationException.class) - .isThrownBy(() -> WavefrontMeterRegistry.builder(missingApiTokenDirectConfig).build()); + .isThrownBy(() -> WavefrontMeterRegistry.builder(missingApiTokenDirectConfig).build()); } @Test @@ -222,7 +224,8 @@ public String apiToken() { }; assertThatCode(() -> WavefrontMeterRegistry.builder(missingUriConfig) - .wavefrontSender(mock(WavefrontSender.class)).build()).doesNotThrowAnyException(); + .wavefrontSender(mock(WavefrontSender.class)) + .build()).doesNotThrowAnyException(); } @Test @@ -230,7 +233,8 @@ void customSenderDoesNotNeedApiToken() { WavefrontConfig missingApiTokenDirectConfig = WavefrontConfig.DEFAULT_DIRECT; assertThatCode(() -> WavefrontMeterRegistry.builder(missingApiTokenDirectConfig) - .wavefrontSender(mock(WavefrontSender.class)).build()).doesNotThrowAnyException(); + .wavefrontSender(mock(WavefrontSender.class)) + .build()).doesNotThrowAnyException(); } @Test @@ -238,19 +242,19 @@ void proxyConfigDoesNotNeedApiToken() { WavefrontConfig missingApiTokenProxyConfig = WavefrontConfig.DEFAULT_PROXY; assertThatCode(() -> WavefrontMeterRegistry.builder(missingApiTokenProxyConfig).build()) - .doesNotThrowAnyException(); + .doesNotThrowAnyException(); } @Test void proxyUriConvertedToHttp() { assertThat(WavefrontMeterRegistry.getWavefrontReportingUri(WavefrontConfig.DEFAULT_PROXY)) - .startsWith("http://"); + .startsWith("http://"); } @Test void directApiUriUnchanged() { assertThat(WavefrontMeterRegistry.getWavefrontReportingUri(WavefrontConfig.DEFAULT_DIRECT)) - .isEqualTo(WavefrontConfig.DEFAULT_DIRECT.uri()); + .isEqualTo(WavefrontConfig.DEFAULT_DIRECT.uri()); } @Test diff --git a/micrometer-core/src/main/java/io/micrometer/core/aop/CountedAspect.java b/micrometer-core/src/main/java/io/micrometer/core/aop/CountedAspect.java index c86a1dec21..2c57b6aeb0 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/aop/CountedAspect.java +++ b/micrometer-core/src/main/java/io/micrometer/core/aop/CountedAspect.java @@ -194,7 +194,7 @@ public Object interceptAndRecord(ProceedingJoinPoint pjp, Counted counted) throw if (stopWhenCompleted) { try { return ((CompletionStage) pjp.proceed()) - .whenComplete((result, throwable) -> recordCompletionResult(pjp, counted, throwable)); + .whenComplete((result, throwable) -> recordCompletionResult(pjp, counted, throwable)); } catch (Throwable e) { record(pjp, counted, e.getClass().getSimpleName(), RESULT_TAG_FAILURE_VALUE); @@ -229,8 +229,11 @@ else if (!counted.recordFailuresOnly()) { } private void record(ProceedingJoinPoint pjp, Counted counted, String exception, String result) { - counter(pjp, counted).tag(EXCEPTION_TAG, exception).tag(RESULT_TAG, result).tags(counted.extraTags()) - .register(registry).increment(); + counter(pjp, counted).tag(EXCEPTION_TAG, exception) + .tag(RESULT_TAG, result) + .tags(counted.extraTags()) + .register(registry) + .increment(); } private Counter.Builder counter(ProceedingJoinPoint pjp, Counted counted) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/aop/TimedAspect.java b/micrometer-core/src/main/java/io/micrometer/core/aop/TimedAspect.java index 0d340b13c6..95f657c494 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/aop/TimedAspect.java +++ b/micrometer-core/src/main/java/io/micrometer/core/aop/TimedAspect.java @@ -232,12 +232,14 @@ private Object processWithTimer(ProceedingJoinPoint pjp, Timed timed, String met private void record(ProceedingJoinPoint pjp, Timed timed, String metricName, Timer.Sample sample, String exceptionClass) { try { - sample.stop( - Timer.builder(metricName).description(timed.description().isEmpty() ? null : timed.description()) - .tags(timed.extraTags()).tags(EXCEPTION_TAG, exceptionClass) - .tags(tagsBasedOnJoinPoint.apply(pjp)).publishPercentileHistogram(timed.histogram()) - .publishPercentiles(timed.percentiles().length == 0 ? null : timed.percentiles()) - .register(registry)); + sample.stop(Timer.builder(metricName) + .description(timed.description().isEmpty() ? null : timed.description()) + .tags(timed.extraTags()) + .tags(EXCEPTION_TAG, exceptionClass) + .tags(tagsBasedOnJoinPoint.apply(pjp)) + .publishPercentileHistogram(timed.histogram()) + .publishPercentiles(timed.percentiles().length == 0 ? null : timed.percentiles()) + .register(registry)); } catch (Exception e) { // ignoring on purpose @@ -265,7 +267,7 @@ private Object processWithLongTaskTimer(ProceedingJoinPoint pjp, Timed timed, St if (stopWhenCompleted) { try { return ((CompletionStage) pjp.proceed()) - .whenComplete((result, throwable) -> sample.ifPresent(this::stopTimer)); + .whenComplete((result, throwable) -> sample.ifPresent(this::stopTimer)); } catch (Exception ex) { sample.ifPresent(this::stopTimer); @@ -297,8 +299,10 @@ private void stopTimer(LongTaskTimer.Sample sample) { private Optional buildLongTaskTimer(ProceedingJoinPoint pjp, Timed timed, String metricName) { try { return Optional.of(LongTaskTimer.builder(metricName) - .description(timed.description().isEmpty() ? null : timed.description()).tags(timed.extraTags()) - .tags(tagsBasedOnJoinPoint.apply(pjp)).register(registry)); + .description(timed.description().isEmpty() ? null : timed.description()) + .tags(timed.extraTags()) + .tags(tagsBasedOnJoinPoint.apply(pjp)) + .register(registry)); } catch (Exception e) { return Optional.empty(); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/AbstractTimerBuilder.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/AbstractTimerBuilder.java index c310a071d8..490cf31090 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/AbstractTimerBuilder.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/AbstractTimerBuilder.java @@ -163,7 +163,7 @@ public B sla(@Nullable Duration... sla) { public B serviceLevelObjectives(@Nullable Duration... slos) { if (slos != null) { this.distributionConfigBuilder - .serviceLevelObjectives(Arrays.stream(slos).mapToDouble(Duration::toNanos).toArray()); + .serviceLevelObjectives(Arrays.stream(slos).mapToDouble(Duration::toNanos).toArray()); } return (B) this; } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/FunctionTimer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/FunctionTimer.java index ce873a7608..2d5fdc28ae 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/FunctionTimer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/FunctionTimer.java @@ -147,8 +147,9 @@ public Builder description(@Nullable String description) { * @return A new or existing function timer. */ public FunctionTimer register(MeterRegistry registry) { - return registry.more().timer(new Meter.Id(name, tags, null, description, Type.TIMER), obj, countFunction, - totalTimeFunction, totalTimeFunctionUnit); + return registry.more() + .timer(new Meter.Id(name, tags, null, description, Type.TIMER), obj, countFunction, totalTimeFunction, + totalTimeFunctionUnit); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/LongTaskTimer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/LongTaskTimer.java index 1498353851..63ff704feb 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/LongTaskTimer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/LongTaskTimer.java @@ -55,8 +55,9 @@ static Builder builder(Timed timed) { "Long tasks instrumented with @Timed require the value attribute to be non-empty"); } - return new Builder(timed.value()).tags(timed.extraTags()).publishPercentileHistogram(timed.histogram()) - .description(timed.description().isEmpty() ? null : timed.description()); + return new Builder(timed.value()).tags(timed.extraTags()) + .publishPercentileHistogram(timed.histogram()) + .description(timed.description().isEmpty() ? null : timed.description()); } /** @@ -288,7 +289,7 @@ public Builder description(@Nullable String description) { public Builder serviceLevelObjectives(@Nullable Duration... slos) { if (slos != null) { this.distributionConfigBuilder - .serviceLevelObjectives(Arrays.stream(slos).mapToDouble(Duration::toNanos).toArray()); + .serviceLevelObjectives(Arrays.stream(slos).mapToDouble(Duration::toNanos).toArray()); } return this; } @@ -418,8 +419,9 @@ public Builder publishPercentileHistogram(@Nullable Boolean enabled) { * @return A new or existing long task timer. */ public LongTaskTimer register(MeterRegistry registry) { - return registry.more().longTaskTimer(new Meter.Id(name, tags, null, description, Type.LONG_TASK_TIMER), - distributionConfigBuilder.build()); + return registry.more() + .longTaskTimer(new Meter.Id(name, tags, null, description, Type.LONG_TASK_TIMER), + distributionConfigBuilder.build()); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/Meter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/Meter.java index 96afcad06e..d497a92f69 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/Meter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/Meter.java @@ -330,8 +330,8 @@ public String getConventionName(NamingConvention namingConvention) { */ public List getConventionTags(NamingConvention namingConvention) { return StreamSupport.stream(tags.spliterator(), false) - .map(t -> Tag.of(namingConvention.tagKey(t.getKey()), namingConvention.tagValue(t.getValue()))) - .collect(Collectors.toList()); + .map(t -> Tag.of(namingConvention.tagKey(t.getKey()), namingConvention.tagValue(t.getValue()))) + .collect(Collectors.toList()); } /** diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java index 0cd4b5435b..d016131cca 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java @@ -945,8 +945,9 @@ FunctionCounter counter(Meter.Id id, T obj, ToDoubleFunction countFunctio */ public FunctionTimer timer(String name, Iterable tags, T obj, ToLongFunction countFunction, ToDoubleFunction totalTimeFunction, TimeUnit totalTimeFunctionUnit) { - return FunctionTimer.builder(name, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit).tags(tags) - .register(MeterRegistry.this); + return FunctionTimer.builder(name, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit) + .tags(tags) + .register(MeterRegistry.this); } /** diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/Metrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/Metrics.java index 4bbbc90368..a556387afa 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/Metrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/Metrics.java @@ -321,8 +321,8 @@ public TimeGauge timeGauge(String name, Iterable tags, T obj, TimeUnit */ public FunctionTimer timer(String name, Iterable tags, T obj, ToLongFunction countFunction, ToDoubleFunction totalTimeFunction, TimeUnit totalTimeFunctionUnit) { - return globalRegistry.more().timer(name, tags, obj, countFunction, totalTimeFunction, - totalTimeFunctionUnit); + return globalRegistry.more() + .timer(name, tags, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/TimeGauge.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/TimeGauge.java index 7358b37092..bbd788998d 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/TimeGauge.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/TimeGauge.java @@ -158,8 +158,9 @@ public Builder strongReference(boolean strong) { * @return A new or existing time gauge. */ public TimeGauge register(MeterRegistry registry) { - return registry.more().timeGauge(new Meter.Id(name, tags, null, description, Type.GAUGE), obj, fUnits, - strongReference ? new StrongReferenceGaugeFunction<>(obj, f) : f); + return registry.more() + .timeGauge(new Meter.Id(name, tags, null, description, Type.GAUGE), obj, fUnits, + strongReference ? new StrongReferenceGaugeFunction<>(obj, f) : f); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/Timer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/Timer.java index f42b5f53f4..e660bce862 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/Timer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/Timer.java @@ -97,9 +97,9 @@ static Builder builder(Timed timed, String defaultName) { } return new Builder(timed.value().isEmpty() ? defaultName : timed.value()).tags(timed.extraTags()) - .description(timed.description().isEmpty() ? null : timed.description()) - .publishPercentileHistogram(timed.histogram()) - .publishPercentiles(timed.percentiles().length > 0 ? timed.percentiles() : null); + .description(timed.description().isEmpty() ? null : timed.description()) + .publishPercentileHistogram(timed.histogram()) + .publishPercentiles(timed.percentiles().length > 0 ? timed.percentiles() : null); } /** @@ -293,9 +293,10 @@ class ResourceSample extends AbstractTimerBuilder implements Aut @Override public void close() { long durationNs = registry.config().clock().monotonicTime() - startTime; - registry.timer(new Meter.Id(name, tags, null, description, Type.TIMER), distributionConfigBuilder.build(), - pauseDetector == null ? registry.config().pauseDetector() : pauseDetector) - .record(durationNs, TimeUnit.NANOSECONDS); + registry + .timer(new Meter.Id(name, tags, null, description, Type.TIMER), distributionConfigBuilder.build(), + pauseDetector == null ? registry.config().pauseDetector() : pauseDetector) + .record(durationNs, TimeUnit.NANOSECONDS); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CacheMeterBinder.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CacheMeterBinder.java index 6e471b0c9c..d8b2d76ffe 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CacheMeterBinder.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CacheMeterBinder.java @@ -61,9 +61,11 @@ public final void bindTo(MeterRegistry registry) { Gauge.builder("cache.size", cache, c -> { Long size = size(); return size == null ? 0 : size; - }).tags(tags).description( - "The number of entries in this cache. This may be an approximation, depending on the type of cache.") - .register(registry); + }) + .tags(tags) + .description( + "The number of entries in this cache. This may be an approximation, depending on the type of cache.") + .register(registry); } if (missCount() != null) { @@ -73,11 +75,16 @@ public final void bindTo(MeterRegistry registry) { }).tags(tags).tag("result", "miss").description(DESCRIPTION_CACHE_GETS).register(registry); } - FunctionCounter.builder("cache.gets", cache, c -> hitCount()).tags(tags).tag("result", "hit") - .description(DESCRIPTION_CACHE_GETS).register(registry); + FunctionCounter.builder("cache.gets", cache, c -> hitCount()) + .tags(tags) + .tag("result", "hit") + .description(DESCRIPTION_CACHE_GETS) + .register(registry); - FunctionCounter.builder("cache.puts", cache, c -> putCount()).tags(tags) - .description("The number of entries added to the cache").register(registry); + FunctionCounter.builder("cache.puts", cache, c -> putCount()) + .tags(tags) + .description("The number of entries added to the cache") + .register(registry); if (evictionCount() != null) { FunctionCounter.builder("cache.evictions", cache, c -> { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineCacheMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineCacheMetrics.java index 3d581cf258..91ed765950 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineCacheMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineCacheMetrics.java @@ -44,7 +44,7 @@ */ @NonNullApi @NonNullFields -public class CaffeineCacheMetrics> extends CacheMeterBinder { +public class CaffeineCacheMetrics>extends CacheMeterBinder { private static final String DESCRIPTION_CACHE_LOAD = "The number of times cache lookup methods have successfully loaded a new value or failed to load a new value, either because no value was found or an exception was thrown while loading"; @@ -167,21 +167,28 @@ protected long putCount() { protected void bindImplementationSpecificMetrics(MeterRegistry registry) { C cache = getCache(); FunctionCounter.builder("cache.eviction.weight", cache, c -> c.stats().evictionWeight()) - .tags(getTagsWithCacheName()) - .description("The sum of weights of evicted entries. This total does not include manual invalidations.") - .register(registry); + .tags(getTagsWithCacheName()) + .description("The sum of weights of evicted entries. This total does not include manual invalidations.") + .register(registry); if (cache instanceof LoadingCache) { // dividing these gives you a measure of load latency TimeGauge.builder("cache.load.duration", cache, TimeUnit.NANOSECONDS, c -> c.stats().totalLoadTime()) - .tags(getTagsWithCacheName()).description("The time the cache has spent loading new values") - .register(registry); + .tags(getTagsWithCacheName()) + .description("The time the cache has spent loading new values") + .register(registry); - FunctionCounter.builder("cache.load", cache, c -> c.stats().loadSuccessCount()).tags(getTagsWithCacheName()) - .tags("result", "success").description(DESCRIPTION_CACHE_LOAD).register(registry); + FunctionCounter.builder("cache.load", cache, c -> c.stats().loadSuccessCount()) + .tags(getTagsWithCacheName()) + .tags("result", "success") + .description(DESCRIPTION_CACHE_LOAD) + .register(registry); - FunctionCounter.builder("cache.load", cache, c -> c.stats().loadFailureCount()).tags(getTagsWithCacheName()) - .tags("result", "failure").description(DESCRIPTION_CACHE_LOAD).register(registry); + FunctionCounter.builder("cache.load", cache, c -> c.stats().loadFailureCount()) + .tags(getTagsWithCacheName()) + .tags("result", "failure") + .description(DESCRIPTION_CACHE_LOAD) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineStatsCounter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineStatsCounter.java index 47289a6b65..383016634f 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineStatsCounter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineStatsCounter.java @@ -95,20 +95,35 @@ public CaffeineStatsCounter(MeterRegistry registry, String cacheName, Iterable(RemovalCause.class); Arrays.stream(RemovalCause.values()) - .forEach(cause -> evictionMetrics.put(cause, - DistributionSummary.builder("cache.evictions").tag("cause", cause.name()).tags(tags) - .description("The number of times the cache was evicted.").register(registry))); + .forEach(cause -> evictionMetrics.put(cause, + DistributionSummary.builder("cache.evictions") + .tag("cause", cause.name()) + .tags(tags) + .description("The number of times the cache was evicted.") + .register(registry))); } /** @@ -116,8 +131,10 @@ public CaffeineStatsCounter(MeterRegistry registry, String cacheName, Iterable cache) { - Gauge.builder("cache.size", cache, Cache::estimatedSize).tags(tags) - .description("The approximate number of entries in this cache.").register(registry); + Gauge.builder("cache.size", cache, Cache::estimatedSize) + .tags(tags) + .description("The approximate number of entries in this cache.") + .register(registry); } @Override diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/EhCache2Metrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/EhCache2Metrics.java index ca9a150b43..a42e745083 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/EhCache2Metrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/EhCache2Metrics.java @@ -104,19 +104,27 @@ protected long putCount() { @Override protected void bindImplementationSpecificMetrics(MeterRegistry registry) { StatisticsGateway stats = getStats(); - Gauge.builder("cache.remoteSize", stats, StatisticsGateway::getRemoteSize).tags(getTagsWithCacheName()) - .description("The number of entries held remotely in this cache").register(registry); + Gauge.builder("cache.remoteSize", stats, StatisticsGateway::getRemoteSize) + .tags(getTagsWithCacheName()) + .description("The number of entries held remotely in this cache") + .register(registry); FunctionCounter.builder("cache.removals", stats, StatisticsGateway::cacheRemoveCount) - .tags(getTagsWithCacheName()).description("Cache removals").register(registry); + .tags(getTagsWithCacheName()) + .description("Cache removals") + .register(registry); FunctionCounter.builder("cache.puts.added", stats, StatisticsGateway::cachePutAddedCount) - .tags(getTagsWithCacheName()).tags("result", "added").description(DESCRIPTION_CACHE_PUTS_ADDED) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "added") + .description(DESCRIPTION_CACHE_PUTS_ADDED) + .register(registry); FunctionCounter.builder("cache.puts.added", stats, StatisticsGateway::cachePutUpdatedCount) - .tags(getTagsWithCacheName()).tags("result", "updated").description(DESCRIPTION_CACHE_PUTS_ADDED) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "updated") + .description(DESCRIPTION_CACHE_PUTS_ADDED) + .register(registry); missMetrics(registry); commitTransactionMetrics(registry); @@ -124,16 +132,22 @@ protected void bindImplementationSpecificMetrics(MeterRegistry registry) { recoveryTransactionMetrics(registry); Gauge.builder("cache.local.offheap.size", stats, StatisticsGateway::getLocalOffHeapSizeInBytes) - .tags(getTagsWithCacheName()).description("Local off-heap size").baseUnit(BaseUnits.BYTES) - .register(registry); + .tags(getTagsWithCacheName()) + .description("Local off-heap size") + .baseUnit(BaseUnits.BYTES) + .register(registry); Gauge.builder("cache.local.heap.size", stats, StatisticsGateway::getLocalHeapSizeInBytes) - .tags(getTagsWithCacheName()).description("Local heap size").baseUnit(BaseUnits.BYTES) - .register(registry); + .tags(getTagsWithCacheName()) + .description("Local heap size") + .baseUnit(BaseUnits.BYTES) + .register(registry); Gauge.builder("cache.local.disk.size", stats, StatisticsGateway::getLocalDiskSizeInBytes) - .tags(getTagsWithCacheName()).description("Local disk size").baseUnit(BaseUnits.BYTES) - .register(registry); + .tags(getTagsWithCacheName()) + .description("Local disk size") + .baseUnit(BaseUnits.BYTES) + .register(registry); } @Nullable @@ -145,49 +159,67 @@ private StatisticsGateway getStats() { private void missMetrics(MeterRegistry registry) { StatisticsGateway stats = getStats(); FunctionCounter.builder("cache.misses", stats, StatisticsGateway::cacheMissExpiredCount) - .tags(getTagsWithCacheName()).tags("reason", "expired").description(DESCRIPTION_CACHE_MISSES) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("reason", "expired") + .description(DESCRIPTION_CACHE_MISSES) + .register(registry); FunctionCounter.builder("cache.misses", stats, StatisticsGateway::cacheMissNotFoundCount) - .tags(getTagsWithCacheName()).tags("reason", "notFound").description(DESCRIPTION_CACHE_MISSES) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("reason", "notFound") + .description(DESCRIPTION_CACHE_MISSES) + .register(registry); } private void commitTransactionMetrics(MeterRegistry registry) { StatisticsGateway stats = getStats(); FunctionCounter.builder("cache.xa.commits", stats, StatisticsGateway::xaCommitReadOnlyCount) - .tags(getTagsWithCacheName()).tags("result", "readOnly").description(DESCRIPTION_CACHE_XA_COMMITS) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "readOnly") + .description(DESCRIPTION_CACHE_XA_COMMITS) + .register(registry); FunctionCounter.builder("cache.xa.commits", stats, StatisticsGateway::xaCommitExceptionCount) - .tags(getTagsWithCacheName()).tags("result", "exception").description(DESCRIPTION_CACHE_XA_COMMITS) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "exception") + .description(DESCRIPTION_CACHE_XA_COMMITS) + .register(registry); FunctionCounter.builder("cache.xa.commits", stats, StatisticsGateway::xaCommitCommittedCount) - .tags(getTagsWithCacheName()).tags("result", "committed").description(DESCRIPTION_CACHE_XA_COMMITS) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "committed") + .description(DESCRIPTION_CACHE_XA_COMMITS) + .register(registry); } private void rollbackTransactionMetrics(MeterRegistry registry) { StatisticsGateway stats = getStats(); FunctionCounter.builder("cache.xa.rollbacks", stats, StatisticsGateway::xaRollbackExceptionCount) - .tags(getTagsWithCacheName()).tags("result", "exception").description(DESCRIPTION_CACHE_XA_ROLLBACKS) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "exception") + .description(DESCRIPTION_CACHE_XA_ROLLBACKS) + .register(registry); FunctionCounter.builder("cache.xa.rollbacks", stats, StatisticsGateway::xaRollbackSuccessCount) - .tags(getTagsWithCacheName()).tags("result", "success").description(DESCRIPTION_CACHE_XA_ROLLBACKS) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "success") + .description(DESCRIPTION_CACHE_XA_ROLLBACKS) + .register(registry); } private void recoveryTransactionMetrics(MeterRegistry registry) { StatisticsGateway stats = getStats(); FunctionCounter.builder("cache.xa.recoveries", stats, StatisticsGateway::xaRecoveryNothingCount) - .tags(getTagsWithCacheName()).tags("result", "nothing").description(DESCRIPTION_CACHE_XA_RECOVERIES) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "nothing") + .description(DESCRIPTION_CACHE_XA_RECOVERIES) + .register(registry); FunctionCounter.builder("cache.xa.recoveries", stats, StatisticsGateway::xaRecoveryRecoveredCount) - .tags(getTagsWithCacheName()).tags("result", "success").description(DESCRIPTION_CACHE_XA_RECOVERIES) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "success") + .description(DESCRIPTION_CACHE_XA_RECOVERIES) + .register(registry); } @Nullable diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/GuavaCacheMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/GuavaCacheMetrics.java index d21691e268..023a058731 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/GuavaCacheMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/GuavaCacheMetrics.java @@ -32,7 +32,7 @@ */ @NonNullApi @NonNullFields -public class GuavaCacheMetrics> extends CacheMeterBinder { +public class GuavaCacheMetrics>extends CacheMeterBinder { private static final String DESCRIPTION_CACHE_LOAD = "The number of times cache lookup methods have successfully loaded a new value or failed to load a new value because an exception was thrown while loading"; @@ -111,15 +111,21 @@ protected void bindImplementationSpecificMetrics(MeterRegistry registry) { if (cache instanceof LoadingCache) { // dividing these gives you a measure of load latency TimeGauge.builder("cache.load.duration", cache, TimeUnit.NANOSECONDS, c -> c.stats().totalLoadTime()) - .tags(getTagsWithCacheName()).description("The time the cache has spent loading new values") - .register(registry); + .tags(getTagsWithCacheName()) + .description("The time the cache has spent loading new values") + .register(registry); - FunctionCounter.builder("cache.load", cache, c -> c.stats().loadSuccessCount()).tags(getTagsWithCacheName()) - .tags("result", "success").description(DESCRIPTION_CACHE_LOAD).register(registry); + FunctionCounter.builder("cache.load", cache, c -> c.stats().loadSuccessCount()) + .tags(getTagsWithCacheName()) + .tags("result", "success") + .description(DESCRIPTION_CACHE_LOAD) + .register(registry); FunctionCounter.builder("cache.load", cache, c -> c.stats().loadExceptionCount()) - .tags(getTagsWithCacheName()).tags("result", "failure").description(DESCRIPTION_CACHE_LOAD) - .register(registry); + .tags(getTagsWithCacheName()) + .tags("result", "failure") + .description(DESCRIPTION_CACHE_LOAD) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetrics.java index 41506e6469..9d7c0f4f56 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetrics.java @@ -133,31 +133,46 @@ protected long putCount() { @Override protected void bindImplementationSpecificMetrics(MeterRegistry registry) { - Gauge.builder("cache.entries", cache, - cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getBackupEntryCount)) - .tags(getTagsWithCacheName()).tag("ownership", "backup").description(DESCRIPTION_CACHE_ENTRIES) - .register(registry); - - Gauge.builder("cache.entries", cache, - cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getOwnedEntryCount)) - .tags(getTagsWithCacheName()).tag("ownership", "owned").description(DESCRIPTION_CACHE_ENTRIES) - .register(registry); - - Gauge.builder("cache.entry.memory", cache, - cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getBackupEntryMemoryCost)) - .tags(getTagsWithCacheName()).tag("ownership", "backup").description(DESCRIPTION_CACHE_ENTRY_MEMORY) - .baseUnit(BaseUnits.BYTES).register(registry); - - Gauge.builder("cache.entry.memory", cache, - cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getOwnedEntryMemoryCost)) - .tags(getTagsWithCacheName()).tag("ownership", "owned").description(DESCRIPTION_CACHE_ENTRY_MEMORY) - .baseUnit(BaseUnits.BYTES).register(registry); + Gauge + .builder("cache.entries", cache, + cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getBackupEntryCount)) + .tags(getTagsWithCacheName()) + .tag("ownership", "backup") + .description(DESCRIPTION_CACHE_ENTRIES) + .register(registry); + + Gauge + .builder("cache.entries", cache, + cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getOwnedEntryCount)) + .tags(getTagsWithCacheName()) + .tag("ownership", "owned") + .description(DESCRIPTION_CACHE_ENTRIES) + .register(registry); + + Gauge + .builder("cache.entry.memory", cache, + cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getBackupEntryMemoryCost)) + .tags(getTagsWithCacheName()) + .tag("ownership", "backup") + .description(DESCRIPTION_CACHE_ENTRY_MEMORY) + .baseUnit(BaseUnits.BYTES) + .register(registry); + + Gauge + .builder("cache.entry.memory", cache, + cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getOwnedEntryMemoryCost)) + .tags(getTagsWithCacheName()) + .tag("ownership", "owned") + .description(DESCRIPTION_CACHE_ENTRY_MEMORY) + .baseUnit(BaseUnits.BYTES) + .register(registry); FunctionCounter - .builder("cache.partition.gets", cache, - cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getGetOperationCount)) - .tags(getTagsWithCacheName()) - .description("The total number of get operations executed against this partition").register(registry); + .builder("cache.partition.gets", cache, + cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getGetOperationCount)) + .tags(getTagsWithCacheName()) + .description("The total number of get operations executed against this partition") + .register(registry); timings(registry); nearCacheMetrics(registry); @@ -170,28 +185,37 @@ private double getDouble(LocalMapStats localMapStats, ToDoubleFunction getDouble(cache.getLocalMapStats(), (stats) -> stats.getNearCacheStats().getHits())) - .tags(getTagsWithCacheName()).tag("result", "hit").description(DESCRIPTION_CACHE_NEAR_REQUESTS) - .register(registry); - - Gauge.builder("cache.near.requests", cache, - cache -> getDouble(cache.getLocalMapStats(), (stats) -> stats.getNearCacheStats().getMisses())) - .tags(getTagsWithCacheName()).tag("result", "miss").description(DESCRIPTION_CACHE_NEAR_REQUESTS) - .register(registry); - - Gauge.builder("cache.near.evictions", cache, - cache -> getDouble(cache.getLocalMapStats(), (stats) -> stats.getNearCacheStats().getEvictions())) - .tags(getTagsWithCacheName()) - .description("The number of evictions of near cache entries owned by this member") - .register(registry); - - Gauge.builder("cache.near.persistences", cache, - cache -> getDouble(cache.getLocalMapStats(), - (stats) -> stats.getNearCacheStats().getPersistenceCount())) - .tags(getTagsWithCacheName()) - .description("The number of near cache key persistences (when the pre-load feature is enabled)") - .register(registry); + Gauge + .builder("cache.near.requests", cache, + cache -> getDouble(cache.getLocalMapStats(), (stats) -> stats.getNearCacheStats().getHits())) + .tags(getTagsWithCacheName()) + .tag("result", "hit") + .description(DESCRIPTION_CACHE_NEAR_REQUESTS) + .register(registry); + + Gauge + .builder("cache.near.requests", cache, + cache -> getDouble(cache.getLocalMapStats(), (stats) -> stats.getNearCacheStats().getMisses())) + .tags(getTagsWithCacheName()) + .tag("result", "miss") + .description(DESCRIPTION_CACHE_NEAR_REQUESTS) + .register(registry); + + Gauge + .builder("cache.near.evictions", cache, + cache -> getDouble(cache.getLocalMapStats(), + (stats) -> stats.getNearCacheStats().getEvictions())) + .tags(getTagsWithCacheName()) + .description("The number of evictions of near cache entries owned by this member") + .register(registry); + + Gauge + .builder("cache.near.persistences", cache, + cache -> getDouble(cache.getLocalMapStats(), + (stats) -> stats.getNearCacheStats().getPersistenceCount())) + .tags(getTagsWithCacheName()) + .description("The number of near cache key persistences (when the pre-load feature is enabled)") + .register(registry); } } @@ -199,19 +223,25 @@ private void timings(MeterRegistry registry) { FunctionTimer.builder("cache.gets.latency", cache, cache -> getLong(cache.getLocalMapStats(), LocalMapStats::getGetOperationCount), cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getTotalGetLatency), TimeUnit.MILLISECONDS) - .tags(getTagsWithCacheName()).description("Cache gets").register(registry); + .tags(getTagsWithCacheName()) + .description("Cache gets") + .register(registry); FunctionTimer.builder("cache.puts.latency", cache, cache -> getLong(cache.getLocalMapStats(), LocalMapStats::getPutOperationCount), cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getTotalPutLatency), TimeUnit.MILLISECONDS) - .tags(getTagsWithCacheName()).description("Cache puts").register(registry); + .tags(getTagsWithCacheName()) + .description("Cache puts") + .register(registry); FunctionTimer - .builder("cache.removals.latency", cache, - cache -> getLong(cache.getLocalMapStats(), LocalMapStats::getRemoveOperationCount), - cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getTotalRemoveLatency), - TimeUnit.MILLISECONDS) - .tags(getTagsWithCacheName()).description("Cache removals").register(registry); + .builder("cache.removals.latency", cache, + cache -> getLong(cache.getLocalMapStats(), LocalMapStats::getRemoveOperationCount), + cache -> getDouble(cache.getLocalMapStats(), LocalMapStats::getTotalRemoveLatency), + TimeUnit.MILLISECONDS) + .tags(getTagsWithCacheName()) + .description("Cache removals") + .register(registry); } private long getLong(LocalMapStats localMapStats, ToLongFunction function) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/JCacheMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/JCacheMetrics.java index 5da098e394..e442e03adb 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/JCacheMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/JCacheMetrics.java @@ -41,7 +41,7 @@ */ @NonNullApi @NonNullFields -public class JCacheMetrics> extends CacheMeterBinder { +public class JCacheMetrics>extends CacheMeterBinder { // VisibleForTesting @Nullable @@ -131,7 +131,9 @@ protected long putCount() { protected void bindImplementationSpecificMetrics(MeterRegistry registry) { if (objectName != null) { Gauge.builder("cache.removals", objectName, objectName -> lookupStatistic("CacheRemovals")) - .tags(getTagsWithCacheName()).description("Cache removals").register(registry); + .tags(getTagsWithCacheName()) + .description("Cache removals") + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/commonspool2/CommonsObjectPool2Metrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/commonspool2/CommonsObjectPool2Metrics.java index 4c3156b4b4..0eb5a16b17 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/commonspool2/CommonsObjectPool2Metrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/commonspool2/CommonsObjectPool2Metrics.java @@ -54,7 +54,7 @@ public class CommonsObjectPool2Metrics implements MeterBinder, AutoCloseable { private static final String[] TYPES = new String[] { "GenericObjectPool", "GenericKeyedObjectPool" }; private final ExecutorService executor = Executors - .newSingleThreadExecutor(new NamedThreadFactory("commons-pool-metrics-updater")); + .newSingleThreadExecutor(new NamedThreadFactory("commons-pool-metrics-updater")); private final MBeanServer mBeanServer; @@ -231,27 +231,33 @@ private void registerGaugeForObject(MeterRegistry registry, ObjectName o, String Tags allTags, String description, @Nullable String baseUnit) { final AtomicReference gauge = new AtomicReference<>(); gauge.set(Gauge - .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, - getJmxAttribute(registry, gauge, o, jmxMetricName)) - .description(description).baseUnit(baseUnit).tags(allTags).register(registry)); + .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, getJmxAttribute(registry, gauge, o, jmxMetricName)) + .description(description) + .baseUnit(baseUnit) + .tags(allTags) + .register(registry)); } private void registerFunctionCounterForObject(MeterRegistry registry, ObjectName o, String jmxMetricName, String meterName, Tags allTags, String description, @Nullable String baseUnit) { final AtomicReference counter = new AtomicReference<>(); counter.set(FunctionCounter - .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, - getJmxAttribute(registry, counter, o, jmxMetricName)) - .description(description).baseUnit(baseUnit).tags(allTags).register(registry)); + .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, getJmxAttribute(registry, counter, o, jmxMetricName)) + .description(description) + .baseUnit(baseUnit) + .tags(allTags) + .register(registry)); } private void registerTimeGaugeForObject(MeterRegistry registry, ObjectName o, String jmxMetricName, String meterName, Tags allTags, String description) { final AtomicReference timeGauge = new AtomicReference<>(); timeGauge.set(TimeGauge - .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, TimeUnit.MILLISECONDS, - getJmxAttribute(registry, timeGauge, o, jmxMetricName)) - .description(description).tags(allTags).register(registry)); + .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, TimeUnit.MILLISECONDS, + getJmxAttribute(registry, timeGauge, o, jmxMetricName)) + .description(description) + .tags(allTags) + .register(registry)); } private ToDoubleFunction getJmxAttribute(MeterRegistry registry, diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/DatabaseTableMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/DatabaseTableMetrics.java index aa9a93c533..afab13223e 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/DatabaseTableMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/DatabaseTableMetrics.java @@ -118,9 +118,13 @@ public void bindTo(MeterRegistry registry) { } }; - Gauge.builder("db.table.size", dataSource, totalRows).tags(tags).tag("db", dataSourceName) - .tag("table", tableName).description("Number of rows in a database table").baseUnit(BaseUnits.ROWS) - .register(registry); + Gauge.builder("db.table.size", dataSource, totalRows) + .tags(tags) + .tag("db", dataSourceName) + .tag("table", tableName) + .description("Number of rows in a database table") + .baseUnit(BaseUnits.ROWS) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/JooqExecuteListener.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/JooqExecuteListener.java index aa36831b92..fcb3d48cc5 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/JooqExecuteListener.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/JooqExecuteListener.java @@ -104,9 +104,14 @@ private void stopTimerIfStillRunning(ExecuteContext ctx) { } // noinspection unchecked - sample.stop(Timer.builder("jooq.query").description("Execution time of a SQL query performed with JOOQ") - .tags(queryTags).tag("type", ctx.type().name().toLowerCase()).tag("exception", exceptionName) - .tag("exception.subclass", exceptionSubclass).tags(tags).register(registry)); + sample.stop(Timer.builder("jooq.query") + .description("Execution time of a SQL query performed with JOOQ") + .tags(queryTags) + .tag("type", ctx.type().name().toLowerCase()) + .tag("exception", exceptionName) + .tag("exception.subclass", exceptionSubclass) + .tags(tags) + .register(registry)); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetrics.java index dccdb227ff..f54c5e71f9 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetrics.java @@ -113,36 +113,47 @@ private static Tag createDbTag(String database) { @Override public void bindTo(MeterRegistry registry) { - Gauge.builder(Names.SIZE, postgresDataSource, dataSource -> getDatabaseSize()).tags(tags) - .description("The database size").register(registry); - Gauge.builder(Names.CONNECTIONS, postgresDataSource, dataSource -> getConnectionCount()).tags(tags) - .description("Number of active connections to the given db").register(registry); + Gauge.builder(Names.SIZE, postgresDataSource, dataSource -> getDatabaseSize()) + .tags(tags) + .description("The database size") + .register(registry); + Gauge.builder(Names.CONNECTIONS, postgresDataSource, dataSource -> getConnectionCount()) + .tags(tags) + .description("Number of active connections to the given db") + .register(registry); // Hit ratio can be derived from dividing hits/reads FunctionCounter - .builder(Names.BLOCKS_HITS, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.BLOCKS_HITS, this::getBlockHits)) - .tags(tags) - .description( - "Number of times disk blocks were found already in the buffer cache, so that a read was not necessary") - .register(registry); + .builder(Names.BLOCKS_HITS, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.BLOCKS_HITS, this::getBlockHits)) + .tags(tags) + .description( + "Number of times disk blocks were found already in the buffer cache, so that a read was not necessary") + .register(registry); FunctionCounter - .builder(Names.BLOCKS_READS, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.BLOCKS_READS, this::getBlockReads)) - .tags(tags).description("Number of disk blocks read in this database").register(registry); + .builder(Names.BLOCKS_READS, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.BLOCKS_READS, this::getBlockReads)) + .tags(tags) + .description("Number of disk blocks read in this database") + .register(registry); FunctionCounter - .builder(Names.TRANSACTIONS, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.TRANSACTIONS, this::getTransactionCount)) - .tags(tags).description("Total number of transactions executed (commits + rollbacks)") - .register(registry); - Gauge.builder(Names.LOCKS, postgresDataSource, dataSource -> getLockCount()).tags(tags) - .description("Number of locks on the given db").register(registry); + .builder(Names.TRANSACTIONS, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.TRANSACTIONS, this::getTransactionCount)) + .tags(tags) + .description("Total number of transactions executed (commits + rollbacks)") + .register(registry); + Gauge.builder(Names.LOCKS, postgresDataSource, dataSource -> getLockCount()) + .tags(tags) + .description("Number of locks on the given db") + .register(registry); FunctionCounter - .builder(Names.TEMP_WRITES, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.TEMP_WRITES, this::getTempBytes)) - .tags(tags).description("The total amount of temporary writes to disk to execute queries") - .baseUnit(BaseUnits.BYTES).register(registry); + .builder(Names.TEMP_WRITES, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.TEMP_WRITES, this::getTempBytes)) + .tags(tags) + .description("The total amount of temporary writes to disk to execute queries") + .baseUnit(BaseUnits.BYTES) + .register(registry); registerRowCountMetrics(registry); registerCheckpointMetrics(registry); @@ -150,49 +161,68 @@ public void bindTo(MeterRegistry registry) { private void registerRowCountMetrics(MeterRegistry registry) { FunctionCounter - .builder(Names.ROWS_FETCHED, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.ROWS_FETCHED, this::getReadCount)) - .tags(tags).description("Number of rows fetched from the db").register(registry); + .builder(Names.ROWS_FETCHED, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.ROWS_FETCHED, this::getReadCount)) + .tags(tags) + .description("Number of rows fetched from the db") + .register(registry); FunctionCounter - .builder(Names.ROWS_INSERTED, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.ROWS_INSERTED, this::getInsertCount)) - .tags(tags).description("Number of rows inserted from the db").register(registry); + .builder(Names.ROWS_INSERTED, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.ROWS_INSERTED, this::getInsertCount)) + .tags(tags) + .description("Number of rows inserted from the db") + .register(registry); FunctionCounter - .builder(Names.ROWS_UPDATED, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.ROWS_UPDATED, this::getUpdateCount)) - .tags(tags).description("Number of rows updated from the db").register(registry); + .builder(Names.ROWS_UPDATED, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.ROWS_UPDATED, this::getUpdateCount)) + .tags(tags) + .description("Number of rows updated from the db") + .register(registry); FunctionCounter - .builder(Names.ROWS_DELETED, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.ROWS_DELETED, this::getDeleteCount)) - .tags(tags).description("Number of rows deleted from the db").register(registry); - Gauge.builder(Names.ROWS_DEAD, postgresDataSource, dataSource -> getDeadTupleCount()).tags(tags) - .description("Total number of dead rows in the current database").register(registry); + .builder(Names.ROWS_DELETED, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.ROWS_DELETED, this::getDeleteCount)) + .tags(tags) + .description("Number of rows deleted from the db") + .register(registry); + Gauge.builder(Names.ROWS_DEAD, postgresDataSource, dataSource -> getDeadTupleCount()) + .tags(tags) + .description("Total number of dead rows in the current database") + .register(registry); } private void registerCheckpointMetrics(MeterRegistry registry) { FunctionCounter - .builder(Names.CHECKPOINTS_TIMED, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.CHECKPOINTS_TIMED, - this::getTimedCheckpointsCount)) - .tags(tags).description("Number of checkpoints timed").register(registry); + .builder(Names.CHECKPOINTS_TIMED, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.CHECKPOINTS_TIMED, this::getTimedCheckpointsCount)) + .tags(tags) + .description("Number of checkpoints timed") + .register(registry); FunctionCounter - .builder(Names.CHECKPOINTS_REQUESTED, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.CHECKPOINTS_REQUESTED, - this::getRequestedCheckpointsCount)) - .tags(tags).description("Number of checkpoints requested").register(registry); + .builder(Names.CHECKPOINTS_REQUESTED, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.CHECKPOINTS_REQUESTED, + this::getRequestedCheckpointsCount)) + .tags(tags) + .description("Number of checkpoints requested") + .register(registry); FunctionCounter - .builder(Names.BUFFERS_CHECKPOINT, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.BUFFERS_CHECKPOINT, this::getBuffersCheckpoint)) - .tags(tags).description("Number of buffers written during checkpoints").register(registry); + .builder(Names.BUFFERS_CHECKPOINT, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.BUFFERS_CHECKPOINT, this::getBuffersCheckpoint)) + .tags(tags) + .description("Number of buffers written during checkpoints") + .register(registry); FunctionCounter - .builder(Names.BUFFERS_CLEAN, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.BUFFERS_CLEAN, this::getBuffersClean)) - .tags(tags).description("Number of buffers written by the background writer").register(registry); + .builder(Names.BUFFERS_CLEAN, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.BUFFERS_CLEAN, this::getBuffersClean)) + .tags(tags) + .description("Number of buffers written by the background writer") + .register(registry); FunctionCounter - .builder(Names.BUFFERS_BACKEND, postgresDataSource, - dataSource -> resettableFunctionalCounter(Names.BUFFERS_BACKEND, this::getBuffersBackend)) - .tags(tags).description("Number of buffers written directly by a backend").register(registry); + .builder(Names.BUFFERS_BACKEND, postgresDataSource, + dataSource -> resettableFunctionalCounter(Names.BUFFERS_BACKEND, this::getBuffersBackend)) + .tags(tags) + .description("Number of buffers written directly by a backend") + .register(registry); } private Long getDatabaseSize() { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/AbstractMetricCollectingInterceptor.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/AbstractMetricCollectingInterceptor.java index 262e504d5d..3d755bf92d 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/AbstractMetricCollectingInterceptor.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/AbstractMetricCollectingInterceptor.java @@ -203,8 +203,9 @@ protected MetricSet newMetricsFor(final MethodDescriptor method) { */ protected Function asTimerFunction(final Supplier timerTemplate) { final Map cache = new EnumMap<>(Code.class); - final Function creator = code -> timerTemplate.get().tag(TAG_STATUS_CODE, code.name()) - .register(this.registry); + final Function creator = code -> timerTemplate.get() + .tag(TAG_STATUS_CODE, code.name()) + .register(this.registry); final Function cacheResolver = code -> cache.computeIfAbsent(code, creator); // Eager initialize for (final Code code : this.eagerInitializedCodes) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientCall.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientCall.java index 047ca3ca54..1bf15d6902 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientCall.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientCall.java @@ -30,7 +30,7 @@ * @param The type of message received one or more times from the server. * @author Daniel Theuke (daniel.theuke@heuboe.de) */ -class MetricCollectingClientCall extends SimpleForwardingClientCall { +class MetricCollectingClientCallextends SimpleForwardingClientCall { private final Counter requestCounter; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientCallListener.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientCallListener.java index bc757d3955..74c954ed2f 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientCallListener.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientCallListener.java @@ -29,7 +29,7 @@ * @param The type of message received one or more times from the server. * @author Daniel Theuke (daniel.theuke@heuboe.de) */ -class MetricCollectingClientCallListener extends SimpleForwardingClientCallListener { +class MetricCollectingClientCallListenerextends SimpleForwardingClientCallListener { private final Counter responseCounter; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientInterceptor.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientInterceptor.java index 3f181533e2..e3ebc4279b 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientInterceptor.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingClientInterceptor.java @@ -91,14 +91,16 @@ public MetricCollectingClientInterceptor(final MeterRegistry registry, @Override protected Counter newRequestCounterFor(final MethodDescriptor method) { return this.counterCustomizer - .apply(prepareCounterFor(method, METRIC_NAME_CLIENT_REQUESTS_SENT, "The total number of requests sent")) - .register(this.registry); + .apply(prepareCounterFor(method, METRIC_NAME_CLIENT_REQUESTS_SENT, "The total number of requests sent")) + .register(this.registry); } @Override protected Counter newResponseCounterFor(final MethodDescriptor method) { - return this.counterCustomizer.apply(prepareCounterFor(method, METRIC_NAME_CLIENT_RESPONSES_RECEIVED, - "The total number of responses received")).register(this.registry); + return this.counterCustomizer + .apply(prepareCounterFor(method, METRIC_NAME_CLIENT_RESPONSES_RECEIVED, + "The total number of responses received")) + .register(this.registry); } @Override diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerCall.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerCall.java index bc8c5580ea..a89bc8c998 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerCall.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerCall.java @@ -29,7 +29,7 @@ * @param The type of message sent one or more times to the client. * @author Daniel Theuke (daniel.theuke@heuboe.de) */ -class MetricCollectingServerCall extends SimpleForwardingServerCall { +class MetricCollectingServerCallextends SimpleForwardingServerCall { private final Counter responseCounter; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerCallListener.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerCallListener.java index 2d7196050d..6bec37d1c5 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerCallListener.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerCallListener.java @@ -30,7 +30,7 @@ * @param The type of message received one or more times from the client. * @author Daniel Theuke (daniel.theuke@heuboe.de) */ -class MetricCollectingServerCallListener extends SimpleForwardingServerCallListener { +class MetricCollectingServerCallListenerextends SimpleForwardingServerCallListener { private final Counter requestCounter; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerInterceptor.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerInterceptor.java index 36aa0ad5b8..6403b98af0 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerInterceptor.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/grpc/MetricCollectingServerInterceptor.java @@ -110,15 +110,17 @@ public void preregisterService(final ServerServiceDefinition serviceDefinition) @Override protected Counter newRequestCounterFor(final MethodDescriptor method) { - return this.counterCustomizer.apply(prepareCounterFor(method, METRIC_NAME_SERVER_REQUESTS_RECEIVED, - "The total number of requests received")).register(this.registry); + return this.counterCustomizer + .apply(prepareCounterFor(method, METRIC_NAME_SERVER_REQUESTS_RECEIVED, + "The total number of requests received")) + .register(this.registry); } @Override protected Counter newResponseCounterFor(final MethodDescriptor method) { - return this.counterCustomizer.apply( - prepareCounterFor(method, METRIC_NAME_SERVER_RESPONSES_SENT, "The total number of responses sent")) - .register(this.registry); + return this.counterCustomizer + .apply(prepareCounterFor(method, METRIC_NAME_SERVER_RESPONSES_SENT, "The total number of responses sent")) + .register(this.registry); } @Override diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpClientInterceptor.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpClientInterceptor.java index 2b63ed90f3..25742c7faa 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpClientInterceptor.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpClientInterceptor.java @@ -68,13 +68,15 @@ public class MicrometerHttpClientInterceptor { public MicrometerHttpClientInterceptor(MeterRegistry meterRegistry, Function uriMapper, Iterable extraTags, boolean exportTagsForRoute) { this.requestInterceptor = (request, context) -> timerByHttpContext.put(context, - Timer.resource(meterRegistry, METER_NAME).tags("method", request.getRequestLine().getMethod(), "uri", - uriMapper.apply(request))); + Timer.resource(meterRegistry, METER_NAME) + .tags("method", request.getRequestLine().getMethod(), "uri", uriMapper.apply(request))); this.responseInterceptor = (response, context) -> { - timerByHttpContext.remove(context).tag("status", Integer.toString(response.getStatusLine().getStatusCode())) - .tags(exportTagsForRoute ? HttpContextUtils.generateTagsForRoute(context) : Tags.empty()) - .tags(extraTags).close(); + timerByHttpContext.remove(context) + .tag("status", Integer.toString(response.getStatusLine().getStatusCode())) + .tags(exportTagsForRoute ? HttpContextUtils.generateTagsForRoute(context) : Tags.empty()) + .tags(extraTags) + .close(); }; } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpRequestExecutor.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpRequestExecutor.java index 0279ad8715..963b597a4f 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpRequestExecutor.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpRequestExecutor.java @@ -81,10 +81,11 @@ public class MicrometerHttpRequestExecutor extends HttpRequestExecutor { private MicrometerHttpRequestExecutor(int waitForContinue, MeterRegistry registry, Function uriMapper, Iterable extraTags, boolean exportTagsForRoute) { super(waitForContinue); - this.registry = Optional.ofNullable(registry).orElseThrow( - () -> new IllegalArgumentException("registry is required but has been initialized with null")); - this.uriMapper = Optional.ofNullable(uriMapper).orElseThrow( - () -> new IllegalArgumentException("uriMapper is required but has been initialized with null")); + this.registry = Optional.ofNullable(registry) + .orElseThrow(() -> new IllegalArgumentException("registry is required but has been initialized with null")); + this.uriMapper = Optional.ofNullable(uriMapper) + .orElseThrow( + () -> new IllegalArgumentException("uriMapper is required but has been initialized with null")); this.extraTags = Optional.ofNullable(extraTags).orElse(Collections.emptyList()); this.exportTagsForRoute = exportTagsForRoute; } @@ -123,8 +124,10 @@ public HttpResponse execute(HttpRequest request, HttpClientConnection conn, Http finally { Iterable tags = Tags.of(extraTags).and(routeTags).and(uri, method, status); - timerSample.stop(Timer.builder(METER_NAME).description("Duration of Apache HttpClient request execution") - .tags(tags).register(registry)); + timerSample.stop(Timer.builder(METER_NAME) + .description("Duration of Apache HttpClient request execution") + .tags(tags) + .register(registry)); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/PoolingHttpClientConnectionManagerMetricsBinder.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/PoolingHttpClientConnectionManagerMetricsBinder.java index 5a9004d834..39fbae0fd3 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/PoolingHttpClientConnectionManagerMetricsBinder.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/httpcomponents/PoolingHttpClientConnectionManagerMetricsBinder.java @@ -80,27 +80,38 @@ public void bindTo(@NonNull MeterRegistry registry) { } private void registerTotalMetrics(MeterRegistry registry) { - Gauge.builder("httpcomponents.httpclient.pool.total.max", connPoolControl, - (connPoolControl) -> connPoolControl.getTotalStats().getMax()) - .description("The configured maximum number of allowed persistent connections for all routes.") - .tags(tags).register(registry); - Gauge.builder("httpcomponents.httpclient.pool.total.connections", connPoolControl, - (connPoolControl) -> connPoolControl.getTotalStats().getAvailable()) - .description("The number of persistent and available connections for all routes.").tags(tags) - .tag("state", "available").register(registry); - Gauge.builder("httpcomponents.httpclient.pool.total.connections", connPoolControl, - (connPoolControl) -> connPoolControl.getTotalStats().getLeased()) - .description("The number of persistent and leased connections for all routes.").tags(tags) - .tag("state", "leased").register(registry); - Gauge.builder("httpcomponents.httpclient.pool.total.pending", connPoolControl, - (connPoolControl) -> connPoolControl.getTotalStats().getPending()) - .description( - "The number of connection requests being blocked awaiting a free connection for all routes.") - .tags(tags).register(registry); - Gauge.builder("httpcomponents.httpclient.pool.route.max.default", connPoolControl, - ConnPoolControl::getDefaultMaxPerRoute) - .description("The configured default maximum number of allowed persistent connections per route.") - .tags(tags).register(registry); + Gauge + .builder("httpcomponents.httpclient.pool.total.max", connPoolControl, + (connPoolControl) -> connPoolControl.getTotalStats().getMax()) + .description("The configured maximum number of allowed persistent connections for all routes.") + .tags(tags) + .register(registry); + Gauge + .builder("httpcomponents.httpclient.pool.total.connections", connPoolControl, + (connPoolControl) -> connPoolControl.getTotalStats().getAvailable()) + .description("The number of persistent and available connections for all routes.") + .tags(tags) + .tag("state", "available") + .register(registry); + Gauge + .builder("httpcomponents.httpclient.pool.total.connections", connPoolControl, + (connPoolControl) -> connPoolControl.getTotalStats().getLeased()) + .description("The number of persistent and leased connections for all routes.") + .tags(tags) + .tag("state", "leased") + .register(registry); + Gauge + .builder("httpcomponents.httpclient.pool.total.pending", connPoolControl, + (connPoolControl) -> connPoolControl.getTotalStats().getPending()) + .description("The number of connection requests being blocked awaiting a free connection for all routes.") + .tags(tags) + .register(registry); + Gauge + .builder("httpcomponents.httpclient.pool.route.max.default", connPoolControl, + ConnPoolControl::getDefaultMaxPerRoute) + .description("The configured default maximum number of allowed persistent connections per route.") + .tags(tags) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/HystrixMetricsBinder.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/HystrixMetricsBinder.java index d7c7470fe3..7c9b6b6dd1 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/HystrixMetricsBinder.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/HystrixMetricsBinder.java @@ -43,7 +43,7 @@ public void bindTo(MeterRegistry registry) { // Registers existing plugins except the new MicroMeter Strategy plugin. HystrixPlugins.getInstance() - .registerMetricsPublisher(new MicrometerMetricsPublisher(registry, metricsPublisher)); + .registerMetricsPublisher(new MicrometerMetricsPublisher(registry, metricsPublisher)); HystrixPlugins.getInstance().registerConcurrencyStrategy(concurrencyStrategy); HystrixPlugins.getInstance().registerEventNotifier(eventNotifier); HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisher.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisher.java index 765766b9b8..2b9300794b 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisher.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisher.java @@ -44,7 +44,7 @@ public MicrometerMetricsPublisher(MeterRegistry registry, HystrixMetricsPublishe public HystrixMetricsPublisherThreadPool getMetricsPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) { final HystrixMetricsPublisherThreadPool metricsPublisherForThreadPool = metricsPublisher - .getMetricsPublisherForThreadPool(threadPoolKey, metrics, properties); + .getMetricsPublisherForThreadPool(threadPoolKey, metrics, properties); return new MicrometerMetricsPublisherThreadPool(registry, threadPoolKey, metrics, properties, metricsPublisherForThreadPool); } @@ -60,7 +60,7 @@ public HystrixMetricsPublisherCommand getMetricsPublisherForCommand(HystrixComma HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) { HystrixMetricsPublisherCommand metricsPublisherForCommand = metricsPublisher - .getMetricsPublisherForCommand(commandKey, commandGroupKey, metrics, circuitBreaker, properties); + .getMetricsPublisherForCommand(commandKey, commandGroupKey, metrics, circuitBreaker, properties); return new MicrometerMetricsPublisherCommand(registry, commandKey, commandGroupKey, metrics, circuitBreaker, metricsPublisherForCommand); } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherCommand.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherCommand.java index 0a86fd3375..244a405961 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherCommand.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherCommand.java @@ -37,7 +37,7 @@ public class MicrometerMetricsPublisherCommand implements HystrixMetricsPublisherCommand { private static final InternalLogger LOG = InternalLoggerFactory - .getInstance(MicrometerMetricsPublisherCommand.class); + .getInstance(MicrometerMetricsPublisherCommand.class); private static final String NAME_HYSTRIX_CIRCUIT_BREAKER_OPEN = "hystrix.circuit.breaker.open"; @@ -84,8 +84,9 @@ public MicrometerMetricsPublisherCommand(MeterRegistry meterRegistry, HystrixCom @Override public void initialize() { metricsPublisherForCommand.initialize(); - Gauge.builder(NAME_HYSTRIX_CIRCUIT_BREAKER_OPEN, circuitBreaker, c -> c.isOpen() ? 1 : 0).tags(tags) - .register(meterRegistry); + Gauge.builder(NAME_HYSTRIX_CIRCUIT_BREAKER_OPEN, circuitBreaker, c -> c.isOpen() ? 1 : 0) + .tags(tags) + .register(meterRegistry); // initialize all commands counters and timers with zero final Map eventCounters = new HashMap<>(); @@ -94,8 +95,9 @@ public void initialize() { }); Counter terminalEventCounterTotal = Counter.builder(NAME_HYSTRIX_EXECUTION_TERMINAL_TOTAL) - .description(DESCRIPTION_HYSTRIX_EXECUTION_TERMINAL_TOTAL).tags(Tags.concat(tags)) - .register(meterRegistry); + .description(DESCRIPTION_HYSTRIX_EXECUTION_TERMINAL_TOTAL) + .tags(Tags.concat(tags)) + .register(meterRegistry); final Timer latencyExecution = Timer.builder(NAME_HYSTRIX_LATENCY_EXECUTION).tags(tags).register(meterRegistry); final Timer latencyTotal = Timer.builder(NAME_HYSTRIX_LATENCY_TOTAL).tags(tags).register(meterRegistry); @@ -141,18 +143,25 @@ else if (executionLatency < -1) { } }); - Gauge.builder(NAME_HYSTRIX_CONCURRENT_EXECUTION_CURRENT, metrics, - HystrixCommandMetrics::getCurrentConcurrentExecutionCount).tags(tags).register(meterRegistry); - - Gauge.builder(NAME_HYSTRIX_CONCURRENT_EXECUTION_ROLLING_MAX, metrics, - HystrixCommandMetrics::getRollingMaxConcurrentExecutions).tags(tags).register(meterRegistry); + Gauge + .builder(NAME_HYSTRIX_CONCURRENT_EXECUTION_CURRENT, metrics, + HystrixCommandMetrics::getCurrentConcurrentExecutionCount) + .tags(tags) + .register(meterRegistry); + + Gauge + .builder(NAME_HYSTRIX_CONCURRENT_EXECUTION_ROLLING_MAX, metrics, + HystrixCommandMetrics::getRollingMaxConcurrentExecutions) + .tags(tags) + .register(meterRegistry); } private Counter getCounter(HystrixEventType hystrixEventType) { - return Counter.builder(NAME_HYSTRIX_EXECUTION).description(DESCRIPTION_HYSTRIX_EXECUTION) - .tags(Tags.concat(tags, "event", hystrixEventType.name().toLowerCase(), "terminal", - Boolean.toString(hystrixEventType.isTerminal()))) - .register(meterRegistry); + return Counter.builder(NAME_HYSTRIX_EXECUTION) + .description(DESCRIPTION_HYSTRIX_EXECUTION) + .tags(Tags.concat(tags, "event", hystrixEventType.name().toLowerCase(), "terminal", + Boolean.toString(hystrixEventType.isTerminal()))) + .register(meterRegistry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherThreadPool.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherThreadPool.java index 9b9d59f522..1b1b9c4d9b 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherThreadPool.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherThreadPool.java @@ -61,56 +61,71 @@ public void initialize() { metricsPublisherForThreadPool.initialize(); Gauge.builder(metricName("threads.active.current.count"), metrics::getCurrentActiveCount) - .description("The approximate number of threads that are actively executing tasks.").tags(tags) - .register(meterRegistry); + .description("The approximate number of threads that are actively executing tasks.") + .tags(tags) + .register(meterRegistry); FunctionCounter - .builder(metricName("threads.cumulative.count"), metrics, - HystrixThreadPoolMetrics::getCumulativeCountThreadsExecuted) - .description("Cumulative count of number of threads since the start of the application.") - .tags(tags.and(Tag.of("type", "executed"))).register(meterRegistry); + .builder(metricName("threads.cumulative.count"), metrics, + HystrixThreadPoolMetrics::getCumulativeCountThreadsExecuted) + .description("Cumulative count of number of threads since the start of the application.") + .tags(tags.and(Tag.of("type", "executed"))) + .register(meterRegistry); FunctionCounter - .builder(metricName("threads.cumulative.count"), metrics, - HystrixThreadPoolMetrics::getCumulativeCountThreadsRejected) - .description("Cumulative count of number of threads since the start of the application.") - .tags(tags.and(Tag.of("type", "rejected"))).register(meterRegistry); + .builder(metricName("threads.cumulative.count"), metrics, + HystrixThreadPoolMetrics::getCumulativeCountThreadsRejected) + .description("Cumulative count of number of threads since the start of the application.") + .tags(tags.and(Tag.of("type", "rejected"))) + .register(meterRegistry); Gauge.builder(metricName("threads.pool.current.size"), metrics::getCurrentPoolSize) - .description("The current number of threads in the pool.").tags(tags).register(meterRegistry); + .description("The current number of threads in the pool.") + .tags(tags) + .register(meterRegistry); Gauge.builder(metricName("threads.largest.pool.current.size"), metrics::getCurrentLargestPoolSize) - .description("The largest number of threads that have ever simultaneously been in the pool.").tags(tags) - .register(meterRegistry); + .description("The largest number of threads that have ever simultaneously been in the pool.") + .tags(tags) + .register(meterRegistry); Gauge.builder(metricName("threads.max.pool.current.size"), metrics::getCurrentMaximumPoolSize) - .description("The maximum allowed number of threads.").tags(tags).register(meterRegistry); + .description("The maximum allowed number of threads.") + .tags(tags) + .register(meterRegistry); Gauge.builder(metricName("threads.core.pool.current.size"), metrics::getCurrentCorePoolSize) - .description("The core number of threads.").tags(tags).register(meterRegistry); + .description("The core number of threads.") + .tags(tags) + .register(meterRegistry); FunctionCounter - .builder(metricName("tasks.cumulative.count"), metrics, - m -> m.getCurrentCompletedTaskCount().longValue()) - .description("The approximate total number of tasks since the start of the application.") - .tags(tags.and(Tag.of("type", "completed"))).register(meterRegistry); + .builder(metricName("tasks.cumulative.count"), metrics, m -> m.getCurrentCompletedTaskCount().longValue()) + .description("The approximate total number of tasks since the start of the application.") + .tags(tags.and(Tag.of("type", "completed"))) + .register(meterRegistry); FunctionCounter.builder(metricName("tasks.cumulative.count"), metrics, m -> m.getCurrentTaskCount().longValue()) - .description("The approximate total number of tasks since the start of the application.") - .tags(tags.and(Tag.of("type", "scheduled"))).register(meterRegistry); + .description("The approximate total number of tasks since the start of the application.") + .tags(tags.and(Tag.of("type", "scheduled"))) + .register(meterRegistry); Gauge.builder(metricName("queue.current.size"), metrics::getCurrentQueueSize) - .description("Current size of BlockingQueue used by the thread-pool.").tags(tags) - .register(meterRegistry); + .description("Current size of BlockingQueue used by the thread-pool.") + .tags(tags) + .register(meterRegistry); Gauge.builder(metricName("queue.max.size"), () -> properties.maxQueueSize().get()) - .description("Max size of BlockingQueue used by the thread-pool.").tags(tags).register(meterRegistry); - - Gauge.builder(metricName("queue.rejection.threshold.size"), - () -> properties.queueSizeRejectionThreshold().get()) - .description( - "Artificial max size at which rejections will occur even if maxQueueSize has not been reached.") - .tags(tags).register(meterRegistry); + .description("Max size of BlockingQueue used by the thread-pool.") + .tags(tags) + .register(meterRegistry); + + Gauge + .builder(metricName("queue.rejection.threshold.size"), () -> properties.queueSizeRejectionThreshold().get()) + .description( + "Artificial max size at which rejections will occur even if maxQueueSize has not been reached.") + .tags(tags) + .register(meterRegistry); } private static String metricName(String name) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListener.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListener.java index ce9d8f2efe..6652b8caa4 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListener.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListener.java @@ -39,13 +39,13 @@ public class MetricsRequestEventListener implements RequestEventListener { private final Map shortTaskSample = Collections - .synchronizedMap(new IdentityHashMap<>()); + .synchronizedMap(new IdentityHashMap<>()); private final Map> longTaskSamples = Collections - .synchronizedMap(new IdentityHashMap<>()); + .synchronizedMap(new IdentityHashMap<>()); private final Map> timedAnnotationsOnRequest = Collections - .synchronizedMap(new IdentityHashMap<>()); + .synchronizedMap(new IdentityHashMap<>()); private final MeterRegistry registry; @@ -83,7 +83,8 @@ public void onEvent(RequestEvent event) { shortTaskSample.put(containerRequest, Timer.start(registry)); List longTaskSamples = longTaskTimers(timedAnnotations, event).stream() - .map(LongTaskTimer::start).collect(Collectors.toList()); + .map(LongTaskTimer::start) + .collect(Collectors.toList()); if (!longTaskSamples.isEmpty()) { this.longTaskSamples.put(containerRequest, longTaskSamples); } @@ -130,15 +131,18 @@ private Set shortTimers(Set timed, RequestEvent event) { return Collections.emptySet(); } - return timed.stream().filter(annotation -> !annotation.longTask()) - .map(t -> Timer.builder(t, metricName).tags(tagsProvider.httpRequestTags(event)).register(registry)) - .collect(Collectors.toSet()); + return timed.stream() + .filter(annotation -> !annotation.longTask()) + .map(t -> Timer.builder(t, metricName).tags(tagsProvider.httpRequestTags(event)).register(registry)) + .collect(Collectors.toSet()); } private Set longTaskTimers(Set timed, RequestEvent event) { - return timed.stream().filter(Timed::longTask).map(LongTaskTimer::builder) - .map(b -> b.tags(tagsProvider.httpLongRequestTags(event)).register(registry)) - .collect(Collectors.toSet()); + return timed.stream() + .filter(Timed::longTask) + .map(LongTaskTimer::builder) + .map(b -> b.tags(tagsProvider.httpLongRequestTags(event)).register(registry)) + .collect(Collectors.toSet()); } private Set annotations(RequestEvent event) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyClientMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyClientMetrics.java index d0fbb1bc98..1985b5cb9e 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyClientMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyClientMetrics.java @@ -58,10 +58,10 @@ protected JettyClientMetrics(MeterRegistry registry, JettyClientTagsProvider tag MeterFilter contentSizeMetricDenyFilter = new OnlyOnceLoggingDenyMeterFilter( () -> String.format("Reached the maximum number of URI tags for '%s'.", contentSizeMetricName)); registry.config() - .meterFilter(MeterFilter.maximumAllowableTags(this.timingMetricName, "uri", maxUriTags, - timingMetricDenyFilter)) - .meterFilter(MeterFilter.maximumAllowableTags(this.contentSizeMetricName, "uri", maxUriTags, - contentSizeMetricDenyFilter)); + .meterFilter( + MeterFilter.maximumAllowableTags(this.timingMetricName, "uri", maxUriTags, timingMetricDenyFilter)) + .meterFilter(MeterFilter.maximumAllowableTags(this.contentSizeMetricName, "uri", maxUriTags, + contentSizeMetricDenyFilter)); } @Override @@ -69,17 +69,22 @@ public void onQueued(Request request) { Timer.Sample sample = Timer.start(registry); request.onComplete(result -> { - long requestLength = Optional.ofNullable(result.getRequest().getContent()).map(ContentProvider::getLength) - .orElse(0L); + long requestLength = Optional.ofNullable(result.getRequest().getContent()) + .map(ContentProvider::getLength) + .orElse(0L); Iterable httpRequestTags = tagsProvider.httpRequestTags(result); if (requestLength >= 0) { DistributionSummary.builder(contentSizeMetricName) - .description("Content sizes for Jetty HTTP client requests").tags(httpRequestTags) - .register(registry).record(requestLength); + .description("Content sizes for Jetty HTTP client requests") + .tags(httpRequestTags) + .register(registry) + .record(requestLength); } - sample.stop(Timer.builder(timingMetricName).description("Jetty HTTP client request timing") - .tags(httpRequestTags).register(registry)); + sample.stop(Timer.builder(timingMetricName) + .description("Jetty HTTP client request timing") + .tags(httpRequestTags) + .register(registry)); }); } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyConnectionMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyConnectionMetrics.java index 11675070f1..9478d5be57 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyConnectionMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyConnectionMetrics.java @@ -76,28 +76,45 @@ public JettyConnectionMetrics(MeterRegistry registry, Iterable tags) { this.registry = registry; this.tags = tags; - this.messagesIn = Counter.builder("jetty.connections.messages.in").baseUnit(BaseUnits.MESSAGES) - .description("Messages received by tracked connections").tags(tags).register(registry); - - this.messagesOut = Counter.builder("jetty.connections.messages.out").baseUnit(BaseUnits.MESSAGES) - .description("Messages sent by tracked connections").tags(tags).register(registry); - - this.bytesIn = DistributionSummary.builder("jetty.connections.bytes.in").baseUnit(BaseUnits.BYTES) - .description("Bytes received by tracked connections").tags(tags).register(registry); - - this.bytesOut = DistributionSummary.builder("jetty.connections.bytes.out").baseUnit(BaseUnits.BYTES) - .description("Bytes sent by tracked connections").tags(tags).register(registry); + this.messagesIn = Counter.builder("jetty.connections.messages.in") + .baseUnit(BaseUnits.MESSAGES) + .description("Messages received by tracked connections") + .tags(tags) + .register(registry); + + this.messagesOut = Counter.builder("jetty.connections.messages.out") + .baseUnit(BaseUnits.MESSAGES) + .description("Messages sent by tracked connections") + .tags(tags) + .register(registry); + + this.bytesIn = DistributionSummary.builder("jetty.connections.bytes.in") + .baseUnit(BaseUnits.BYTES) + .description("Bytes received by tracked connections") + .tags(tags) + .register(registry); + + this.bytesOut = DistributionSummary.builder("jetty.connections.bytes.out") + .baseUnit(BaseUnits.BYTES) + .description("Bytes sent by tracked connections") + .tags(tags) + .register(registry); this.maxConnections = new TimeWindowMax(registry.config().clock(), DistributionStatisticConfig.DEFAULT); - Gauge.builder("jetty.connections.max", this, jcm -> jcm.maxConnections.poll()).strongReference(true) - .baseUnit(BaseUnits.CONNECTIONS) - .description("The maximum number of observed connections over a rolling 2-minute interval").tags(tags) - .register(registry); - - Gauge.builder("jetty.connections.current", this, jcm -> jcm.connectionSamples.size()).strongReference(true) - .baseUnit(BaseUnits.CONNECTIONS).description("The current number of open Jetty connections").tags(tags) - .register(registry); + Gauge.builder("jetty.connections.max", this, jcm -> jcm.maxConnections.poll()) + .strongReference(true) + .baseUnit(BaseUnits.CONNECTIONS) + .description("The maximum number of observed connections over a rolling 2-minute interval") + .tags(tags) + .register(registry); + + Gauge.builder("jetty.connections.current", this, jcm -> jcm.connectionSamples.size()) + .strongReference(true) + .baseUnit(BaseUnits.CONNECTIONS) + .description("The current number of open Jetty connections") + .tags(tags) + .register(registry); } /** @@ -146,8 +163,11 @@ public void onClosed(Connection connection) { if (sample != null) { String serverOrClient = connection instanceof HttpConnection ? "server" : "client"; - sample.stop(Timer.builder("jetty.connections.request").description("Jetty client or server requests") - .tag("type", serverOrClient).tags(tags).register(registry)); + sample.stop(Timer.builder("jetty.connections.request") + .description("Jetty client or server requests") + .tag("type", serverOrClient) + .tags(tags) + .register(registry)); } messagesIn.increment(connection.getMessagesIn()); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyServerThreadPoolMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyServerThreadPoolMetrics.java index aba2839d8a..9178e2864f 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyServerThreadPoolMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyServerThreadPoolMetrics.java @@ -57,21 +57,33 @@ public void bindTo(MeterRegistry registry) { if (threadPool instanceof SizedThreadPool) { SizedThreadPool sizedThreadPool = (SizedThreadPool) threadPool; Gauge.builder("jetty.threads.config.min", sizedThreadPool, SizedThreadPool::getMinThreads) - .description("The minimum number of threads in the pool").tags(tags).register(registry); + .description("The minimum number of threads in the pool") + .tags(tags) + .register(registry); Gauge.builder("jetty.threads.config.max", sizedThreadPool, SizedThreadPool::getMaxThreads) - .description("The maximum number of threads in the pool").tags(tags).register(registry); + .description("The maximum number of threads in the pool") + .tags(tags) + .register(registry); if (threadPool instanceof QueuedThreadPool) { QueuedThreadPool queuedThreadPool = (QueuedThreadPool) threadPool; Gauge.builder("jetty.threads.busy", queuedThreadPool, QueuedThreadPool::getBusyThreads) - .description("The number of busy threads in the pool").tags(tags).register(registry); + .description("The number of busy threads in the pool") + .tags(tags) + .register(registry); Gauge.builder("jetty.threads.jobs", queuedThreadPool, QueuedThreadPool::getQueueSize) - .description("Number of jobs queued waiting for a thread").tags(tags).register(registry); + .description("Number of jobs queued waiting for a thread") + .tags(tags) + .register(registry); } } Gauge.builder("jetty.threads.current", threadPool, ThreadPool::getThreads) - .description("The total number of threads in the pool").tags(tags).register(registry); + .description("The total number of threads in the pool") + .tags(tags) + .register(registry); Gauge.builder("jetty.threads.idle", threadPool, ThreadPool::getIdleThreads) - .description("The number of idle threads in the pool").tags(tags).register(registry); + .description("The number of idle threads in the pool") + .tags(tags) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettySslHandshakeMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettySslHandshakeMetrics.java index fb36e44505..ffe132c6fb 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettySslHandshakeMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettySslHandshakeMetrics.java @@ -75,9 +75,14 @@ public JettySslHandshakeMetrics(MeterRegistry registry, Iterable tags) { this.registry = registry; this.tags = tags; - this.handshakesFailed = Counter.builder(METER_NAME).baseUnit(BaseUnits.EVENTS).description(DESCRIPTION) - .tag(TAG_RESULT, "failed").tag(TAG_PROTOCOL, TAG_VALUE_UNKNOWN).tag(TAG_CIPHER_SUITE, TAG_VALUE_UNKNOWN) - .tags(tags).register(registry); + this.handshakesFailed = Counter.builder(METER_NAME) + .baseUnit(BaseUnits.EVENTS) + .description(DESCRIPTION) + .tag(TAG_RESULT, "failed") + .tag(TAG_PROTOCOL, TAG_VALUE_UNKNOWN) + .tag(TAG_CIPHER_SUITE, TAG_VALUE_UNKNOWN) + .tags(tags) + .register(registry); } /** @@ -111,9 +116,15 @@ private static Tags getConnectorNameTag(Connector connector) { @Override public void handshakeSucceeded(Event event) { SSLSession session = event.getSSLEngine().getSession(); - Counter.builder(METER_NAME).baseUnit(BaseUnits.EVENTS).description(DESCRIPTION).tag(TAG_RESULT, "succeeded") - .tag(TAG_PROTOCOL, session.getProtocol()).tag(TAG_CIPHER_SUITE, session.getCipherSuite()).tags(tags) - .register(registry).increment(); + Counter.builder(METER_NAME) + .baseUnit(BaseUnits.EVENTS) + .description(DESCRIPTION) + .tag(TAG_RESULT, "succeeded") + .tag(TAG_PROTOCOL, session.getProtocol()) + .tag(TAG_CIPHER_SUITE, session.getCipherSuite()) + .tags(tags) + .register(registry) + .increment(); } @Override diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyStatisticsMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyStatisticsMetrics.java index 9353aca806..0d2cbafcda 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyStatisticsMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/JettyStatisticsMetrics.java @@ -66,8 +66,10 @@ public void bindTo(MeterRegistry registry) { bindCounter(registry, "jetty.async.expires", "Total number of async requests that have expired", StatisticsHandler::getExpires); FunctionCounter.builder("jetty.responses.size", statisticsHandler, StatisticsHandler::getResponsesBytesTotal) - .description("Total number of bytes across all responses").baseUnit(BaseUnits.BYTES).tags(tags) - .register(registry); + .description("Total number of bytes across all responses") + .baseUnit(BaseUnits.BYTES) + .tags(tags) + .register(registry); bindGauge(registry, "jetty.requests.active", "Number of requests currently active", StatisticsHandler::getRequestsActive); @@ -106,14 +108,18 @@ private void bindGauge(MeterRegistry registry, String name, String description, private void bindTimer(MeterRegistry registry, String name, String desc, ToLongFunction countFunc, ToDoubleFunction consumer) { - FunctionTimer.builder(name, statisticsHandler, countFunc, consumer, TimeUnit.MILLISECONDS).tags(tags) - .description(desc).register(registry); + FunctionTimer.builder(name, statisticsHandler, countFunc, consumer, TimeUnit.MILLISECONDS) + .tags(tags) + .description(desc) + .register(registry); } private void bindTimeGauge(MeterRegistry registry, String name, String desc, ToDoubleFunction consumer) { - TimeGauge.builder(name, statisticsHandler, TimeUnit.MILLISECONDS, consumer).tags(tags).description(desc) - .register(registry); + TimeGauge.builder(name, statisticsHandler, TimeUnit.MILLISECONDS, consumer) + .tags(tags) + .description(desc) + .register(registry); } private void bindCounter(MeterRegistry registry, String name, String desc, @@ -123,8 +129,11 @@ private void bindCounter(MeterRegistry registry, String name, String desc, private void buildStatusCounter(MeterRegistry registry, String status, ToDoubleFunction consumer) { - FunctionCounter.builder("jetty.responses", statisticsHandler, consumer).tags(tags) - .description("Number of requests with response status").tags("status", status).register(registry); + FunctionCounter.builder("jetty.responses", statisticsHandler, consumer) + .tags(tags) + .description("Number of requests with response status") + .tags("status", status) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/TimedHandler.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/TimedHandler.java index 361ae1aa08..43bc0d7577 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/TimedHandler.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jetty/TimedHandler.java @@ -85,17 +85,25 @@ public TimedHandler(MeterRegistry registry, Iterable tags, HttpServletReque this.tagsProvider = tagsProvider; this.openRequests = LongTaskTimer.builder("jetty.server.dispatches.open") - .description("Jetty dispatches that are currently in progress").tags(tags).register(registry); + .description("Jetty dispatches that are currently in progress") + .tags(tags) + .register(registry); - this.asyncDispatches = Counter.builder("jetty.server.async.dispatches").description("Asynchronous dispatches") - .tags(tags).register(registry); + this.asyncDispatches = Counter.builder("jetty.server.async.dispatches") + .description("Asynchronous dispatches") + .tags(tags) + .register(registry); this.asyncExpires = Counter.builder("jetty.server.async.expires") - .description("Asynchronous operations that timed out before completing").tags(tags).register(registry); + .description("Asynchronous operations that timed out before completing") + .tags(tags) + .register(registry); Gauge.builder("jetty.server.async.waits", asyncWaits, AtomicInteger::doubleValue) - .description("Pending asynchronous wait operations").baseUnit(BaseUnits.OPERATIONS).tags(tags) - .register(registry); + .description("Pending asynchronous wait operations") + .baseUnit(BaseUnits.OPERATIONS) + .tags(tags) + .register(registry); } @Override @@ -138,8 +146,11 @@ public void handle(String path, Request baseRequest, HttpServletRequest request, } } else if (state.isInitial()) { - sample.stop(Timer.builder("jetty.server.requests").description("HTTP requests to the Jetty server") - .tags(tagsProvider.getTags(request, response)).tags(tags).register(registry)); + sample.stop(Timer.builder("jetty.server.requests") + .description("HTTP requests to the Jetty server") + .tags(tagsProvider.getTags(request, response)) + .tags(tags) + .register(registry)); requestSample.stop(); @@ -187,7 +198,7 @@ void onAsyncTimeout(AsyncEvent event) { Request request = state.getBaseRequest(); LongTaskTimer.Sample lttSample = (LongTaskTimer.Sample) request - .getAttribute(SAMPLE_REQUEST_LONG_TASK_TIMER_ATTRIBUTE); + .getAttribute(SAMPLE_REQUEST_LONG_TASK_TIMER_ATTRIBUTE); lttSample.stop(); } @@ -197,11 +208,14 @@ void onAsyncComplete(AsyncEvent event) { Request request = state.getBaseRequest(); Timer.Sample sample = (Timer.Sample) request.getAttribute(SAMPLE_REQUEST_TIMER_ATTRIBUTE); LongTaskTimer.Sample lttSample = (LongTaskTimer.Sample) request - .getAttribute(SAMPLE_REQUEST_LONG_TASK_TIMER_ATTRIBUTE); + .getAttribute(SAMPLE_REQUEST_LONG_TASK_TIMER_ATTRIBUTE); if (sample != null) { - sample.stop(Timer.builder("jetty.server.requests").description("HTTP requests to the Jetty server") - .tags(tagsProvider.getTags(request, request.getResponse())).tags(tags).register(registry)); + sample.stop(Timer.builder("jetty.server.requests") + .description("HTTP requests to the Jetty server") + .tags(tagsProvider.getTags(request, request.getResponse())) + .tags(tags) + .register(registry)); lttSample.stop(); } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jpa/HibernateMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jpa/HibernateMetrics.java index cd8e839084..f51b6cb4c1 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jpa/HibernateMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jpa/HibernateMetrics.java @@ -147,8 +147,11 @@ private void counter(MeterRegistry registry, String name, String description, To return; } - FunctionCounter.builder(name, statistics, f).tags(tags).tags(extraTags).description(description) - .register(registry); + FunctionCounter.builder(name, statistics, f) + .tags(tags) + .tags(extraTags) + .description(description) + .register(registry); } @Override @@ -186,21 +189,21 @@ public void bindTo(MeterRegistry registry) { // Second Level Caching - Arrays.stream(statistics.getSecondLevelCacheRegionNames()).filter(this::hasDomainDataRegionStatistics) - .forEach(regionName -> { - counter(registry, "hibernate.second.level.cache.requests", - "The number of cacheable entities/collections successfully retrieved from the cache", - stats -> stats.getDomainDataRegionStatistics(regionName).getHitCount(), "region", - regionName, "result", "hit"); - counter(registry, "hibernate.second.level.cache.requests", - "The number of cacheable entities/collections not found in the cache and loaded from the database", - stats -> stats.getDomainDataRegionStatistics(regionName).getMissCount(), "region", - regionName, "result", "miss"); - counter(registry, "hibernate.second.level.cache.puts", - "The number of cacheable entities/collections put in the cache", - stats -> stats.getDomainDataRegionStatistics(regionName).getPutCount(), "region", - regionName); - }); + Arrays.stream(statistics.getSecondLevelCacheRegionNames()) + .filter(this::hasDomainDataRegionStatistics) + .forEach(regionName -> { + counter(registry, "hibernate.second.level.cache.requests", + "The number of cacheable entities/collections successfully retrieved from the cache", + stats -> stats.getDomainDataRegionStatistics(regionName).getHitCount(), "region", regionName, + "result", "hit"); + counter(registry, "hibernate.second.level.cache.requests", + "The number of cacheable entities/collections not found in the cache and loaded from the database", + stats -> stats.getDomainDataRegionStatistics(regionName).getMissCount(), "region", regionName, + "result", "miss"); + counter(registry, "hibernate.second.level.cache.puts", + "The number of cacheable entities/collections put in the cache", + stats -> stats.getDomainDataRegionStatistics(regionName).getPutCount(), "region", regionName); + }); // Entity information counter(registry, "hibernate.entities.deletes", "The number of entity deletes", @@ -240,19 +243,22 @@ public void bindTo(MeterRegistry registry) { Statistics::getNaturalIdQueryExecutionCount); TimeGauge - .builder("hibernate.query.natural.id.executions.max", statistics, TimeUnit.MILLISECONDS, - Statistics::getNaturalIdQueryExecutionMaxTime) - .description("The maximum query time for naturalId queries executed against the database").tags(tags) - .register(registry); + .builder("hibernate.query.natural.id.executions.max", statistics, TimeUnit.MILLISECONDS, + Statistics::getNaturalIdQueryExecutionMaxTime) + .description("The maximum query time for naturalId queries executed against the database") + .tags(tags) + .register(registry); // Query statistics counter(registry, "hibernate.query.executions", "The number of executed queries", Statistics::getQueryExecutionCount); TimeGauge - .builder("hibernate.query.executions.max", statistics, TimeUnit.MILLISECONDS, - Statistics::getQueryExecutionMaxTime) - .description("The time of the slowest query").tags(tags).register(registry); + .builder("hibernate.query.executions.max", statistics, TimeUnit.MILLISECONDS, + Statistics::getQueryExecutionMaxTime) + .description("The time of the slowest query") + .tags(tags) + .register(registry); // Update timestamp cache counter(registry, "hibernate.cache.update.timestamps.requests", diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jpa/HibernateQueryMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jpa/HibernateQueryMetrics.java index 160dfd679e..3e59e0e414 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jpa/HibernateQueryMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jpa/HibernateQueryMetrics.java @@ -95,7 +95,8 @@ public HibernateQueryMetrics(SessionFactory sessionFactory, String sessionFactor public void bindTo(MeterRegistry meterRegistry) { if (sessionFactory instanceof SessionFactoryImplementor) { EventListenerRegistry eventListenerRegistry = ((SessionFactoryImplementor) sessionFactory) - .getServiceRegistry().getService(EventListenerRegistry.class); + .getServiceRegistry() + .getService(EventListenerRegistry.class); MetricsEventHandler metricsEventHandler = new MetricsEventHandler(meterRegistry); eventListenerRegistry.appendListeners(EventType.POST_LOAD, metricsEventHandler); } @@ -119,42 +120,56 @@ void registerQueryMetric(Statistics statistics) { QueryStatistics queryStatistics = statistics.getQueryStatistics(query); FunctionCounter - .builder("hibernate.query.cache.requests", queryStatistics, QueryStatistics::getCacheHitCount) - .tags(tags).tags("result", "hit", "query", query).description("Number of query cache hits") - .register(meterRegistry); + .builder("hibernate.query.cache.requests", queryStatistics, QueryStatistics::getCacheHitCount) + .tags(tags) + .tags("result", "hit", "query", query) + .description("Number of query cache hits") + .register(meterRegistry); FunctionCounter - .builder("hibernate.query.cache.requests", queryStatistics, QueryStatistics::getCacheMissCount) - .tags(tags).tags("result", "miss", "query", query).description("Number of query cache misses") - .register(meterRegistry); + .builder("hibernate.query.cache.requests", queryStatistics, QueryStatistics::getCacheMissCount) + .tags(tags) + .tags("result", "miss", "query", query) + .description("Number of query cache misses") + .register(meterRegistry); FunctionCounter - .builder("hibernate.query.cache.puts", queryStatistics, QueryStatistics::getCachePutCount) - .tags(tags).tags("query", query).description("Number of cache puts for a query") - .register(meterRegistry); + .builder("hibernate.query.cache.puts", queryStatistics, QueryStatistics::getCachePutCount) + .tags(tags) + .tags("query", query) + .description("Number of cache puts for a query") + .register(meterRegistry); FunctionTimer - .builder("hibernate.query.execution.total", queryStatistics, QueryStatistics::getExecutionCount, - QueryStatistics::getExecutionTotalTime, TimeUnit.MILLISECONDS) - .tags(tags).tags("query", query).description("Query executions").register(meterRegistry); + .builder("hibernate.query.execution.total", queryStatistics, QueryStatistics::getExecutionCount, + QueryStatistics::getExecutionTotalTime, TimeUnit.MILLISECONDS) + .tags(tags) + .tags("query", query) + .description("Query executions") + .register(meterRegistry); TimeGauge - .builder("hibernate.query.execution.max", queryStatistics, TimeUnit.MILLISECONDS, - QueryStatistics::getExecutionMaxTime) - .tags(tags).tags("query", query).description("Query maximum execution time") - .register(meterRegistry); + .builder("hibernate.query.execution.max", queryStatistics, TimeUnit.MILLISECONDS, + QueryStatistics::getExecutionMaxTime) + .tags(tags) + .tags("query", query) + .description("Query maximum execution time") + .register(meterRegistry); TimeGauge - .builder("hibernate.query.execution.min", queryStatistics, TimeUnit.MILLISECONDS, - QueryStatistics::getExecutionMinTime) - .tags(tags).tags("query", query).description("Query minimum execution time") - .register(meterRegistry); + .builder("hibernate.query.execution.min", queryStatistics, TimeUnit.MILLISECONDS, + QueryStatistics::getExecutionMinTime) + .tags(tags) + .tags("query", query) + .description("Query minimum execution time") + .register(meterRegistry); FunctionCounter - .builder("hibernate.query.execution.rows", queryStatistics, - QueryStatistics::getExecutionRowCount) - .tags(tags).tags("query", query).description("Number of rows processed for a query") - .register(meterRegistry); + .builder("hibernate.query.execution.rows", queryStatistics, QueryStatistics::getExecutionRowCount) + .tags(tags) + .tags("query", query) + .description("Number of rows processed for a query") + .register(meterRegistry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ClassLoaderMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ClassLoaderMetrics.java index d09ce275cc..973f27b32c 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ClassLoaderMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ClassLoaderMetrics.java @@ -47,15 +47,17 @@ public ClassLoaderMetrics(Iterable tags) { public void bindTo(MeterRegistry registry) { ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean(); - Gauge.builder("jvm.classes.loaded", classLoadingBean, ClassLoadingMXBean::getLoadedClassCount).tags(tags) - .description("The number of classes that are currently loaded in the Java virtual machine") - .baseUnit(BaseUnits.CLASSES).register(registry); + Gauge.builder("jvm.classes.loaded", classLoadingBean, ClassLoadingMXBean::getLoadedClassCount) + .tags(tags) + .description("The number of classes that are currently loaded in the Java virtual machine") + .baseUnit(BaseUnits.CLASSES) + .register(registry); FunctionCounter.builder("jvm.classes.unloaded", classLoadingBean, ClassLoadingMXBean::getUnloadedClassCount) - .tags(tags) - .description( - "The total number of classes unloaded since the Java virtual machine has started execution") - .baseUnit(BaseUnits.CLASSES).register(registry); + .tags(tags) + .description("The total number of classes unloaded since the Java virtual machine has started execution") + .baseUnit(BaseUnits.CLASSES) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/DiskSpaceMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/DiskSpaceMetrics.java index 1616e9992e..5b6b3cfd55 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/DiskSpaceMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/DiskSpaceMetrics.java @@ -62,10 +62,18 @@ public DiskSpaceMetrics(File path, Iterable tags) { @Override public void bindTo(MeterRegistry registry) { Iterable tagsWithPath = Tags.concat(tags, "path", absolutePath); - Gauge.builder("disk.free", path, File::getUsableSpace).tags(tagsWithPath).description("Usable space for path") - .baseUnit(BaseUnits.BYTES).strongReference(true).register(registry); - Gauge.builder("disk.total", path, File::getTotalSpace).tags(tagsWithPath).description("Total space for path") - .baseUnit(BaseUnits.BYTES).strongReference(true).register(registry); + Gauge.builder("disk.free", path, File::getUsableSpace) + .tags(tagsWithPath) + .description("Usable space for path") + .baseUnit(BaseUnits.BYTES) + .strongReference(true) + .register(registry); + Gauge.builder("disk.total", path, File::getTotalSpace) + .tags(tagsWithPath) + .description("Total space for path") + .baseUnit(BaseUnits.BYTES) + .strongReference(true) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java index 1f51e02439..a5a32116a5 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java @@ -337,53 +337,71 @@ private void monitor(MeterRegistry registry, @Nullable ThreadPoolExecutor tp) { } FunctionCounter.builder(metricPrefix + "executor.completed", tp, ThreadPoolExecutor::getCompletedTaskCount) - .tags(tags).description("The approximate total number of tasks that have completed execution") - .baseUnit(BaseUnits.TASKS).register(registry); - - Gauge.builder(metricPrefix + "executor.active", tp, ThreadPoolExecutor::getActiveCount).tags(tags) - .description("The approximate number of threads that are actively executing tasks") - .baseUnit(BaseUnits.THREADS).register(registry); - - Gauge.builder(metricPrefix + "executor.queued", tp, tpRef -> tpRef.getQueue().size()).tags(tags) - .description("The approximate number of tasks that are queued for execution").baseUnit(BaseUnits.TASKS) - .register(registry); + .tags(tags) + .description("The approximate total number of tasks that have completed execution") + .baseUnit(BaseUnits.TASKS) + .register(registry); + + Gauge.builder(metricPrefix + "executor.active", tp, ThreadPoolExecutor::getActiveCount) + .tags(tags) + .description("The approximate number of threads that are actively executing tasks") + .baseUnit(BaseUnits.THREADS) + .register(registry); + + Gauge.builder(metricPrefix + "executor.queued", tp, tpRef -> tpRef.getQueue().size()) + .tags(tags) + .description("The approximate number of tasks that are queued for execution") + .baseUnit(BaseUnits.TASKS) + .register(registry); Gauge.builder(metricPrefix + "executor.queue.remaining", tp, tpRef -> tpRef.getQueue().remainingCapacity()) - .tags(tags) - .description("The number of additional elements that this queue can ideally accept without blocking") - .baseUnit(BaseUnits.TASKS).register(registry); - - Gauge.builder(metricPrefix + "executor.pool.size", tp, ThreadPoolExecutor::getPoolSize).tags(tags) - .description("The current number of threads in the pool").baseUnit(BaseUnits.THREADS) - .register(registry); - - Gauge.builder(metricPrefix + "executor.pool.core", tp, ThreadPoolExecutor::getCorePoolSize).tags(tags) - .description("The core number of threads for the pool").baseUnit(BaseUnits.THREADS).register(registry); - - Gauge.builder(metricPrefix + "executor.pool.max", tp, ThreadPoolExecutor::getMaximumPoolSize).tags(tags) - .description("The maximum allowed number of threads in the pool").baseUnit(BaseUnits.THREADS) - .register(registry); + .tags(tags) + .description("The number of additional elements that this queue can ideally accept without blocking") + .baseUnit(BaseUnits.TASKS) + .register(registry); + + Gauge.builder(metricPrefix + "executor.pool.size", tp, ThreadPoolExecutor::getPoolSize) + .tags(tags) + .description("The current number of threads in the pool") + .baseUnit(BaseUnits.THREADS) + .register(registry); + + Gauge.builder(metricPrefix + "executor.pool.core", tp, ThreadPoolExecutor::getCorePoolSize) + .tags(tags) + .description("The core number of threads for the pool") + .baseUnit(BaseUnits.THREADS) + .register(registry); + + Gauge.builder(metricPrefix + "executor.pool.max", tp, ThreadPoolExecutor::getMaximumPoolSize) + .tags(tags) + .description("The maximum allowed number of threads in the pool") + .baseUnit(BaseUnits.THREADS) + .register(registry); } private void monitor(MeterRegistry registry, ForkJoinPool fj) { - FunctionCounter.builder(metricPrefix + "executor.steals", fj, ForkJoinPool::getStealCount).tags(tags) - .description("Estimate of the total number of tasks stolen from " - + "one thread's work queue by another. The reported value " - + "underestimates the actual total number of steals when the pool " + "is not quiescent") - .register(registry); - - Gauge.builder(metricPrefix + "executor.queued", fj, ForkJoinPool::getQueuedTaskCount).tags(tags) - .description("An estimate of the total number of tasks currently held in queues by worker threads") - .register(registry); - - Gauge.builder(metricPrefix + "executor.active", fj, ForkJoinPool::getActiveThreadCount).tags(tags) - .description("An estimate of the number of threads that are currently stealing or executing tasks") - .register(registry); - - Gauge.builder(metricPrefix + "executor.running", fj, ForkJoinPool::getRunningThreadCount).tags(tags) - .description( - "An estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization threads") - .register(registry); + FunctionCounter.builder(metricPrefix + "executor.steals", fj, ForkJoinPool::getStealCount) + .tags(tags) + .description("Estimate of the total number of tasks stolen from " + + "one thread's work queue by another. The reported value " + + "underestimates the actual total number of steals when the pool " + "is not quiescent") + .register(registry); + + Gauge.builder(metricPrefix + "executor.queued", fj, ForkJoinPool::getQueuedTaskCount) + .tags(tags) + .description("An estimate of the total number of tasks currently held in queues by worker threads") + .register(registry); + + Gauge.builder(metricPrefix + "executor.active", fj, ForkJoinPool::getActiveThreadCount) + .tags(tags) + .description("An estimate of the number of threads that are currently stealing or executing tasks") + .register(registry); + + Gauge.builder(metricPrefix + "executor.running", fj, ForkJoinPool::getRunningThreadCount) + .tags(tags) + .description( + "An estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization threads") + .register(registry); } /** diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmCompilationMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmCompilationMetrics.java index cc05917d2a..704a7cb2c5 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmCompilationMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmCompilationMetrics.java @@ -53,9 +53,10 @@ public void bindTo(MeterRegistry registry) { CompilationMXBean compilationBean = ManagementFactory.getCompilationMXBean(); if (compilationBean != null && compilationBean.isCompilationTimeMonitoringSupported()) { FunctionCounter.builder("jvm.compilation.time", compilationBean, CompilationMXBean::getTotalCompilationTime) - .tags(Tags.concat(tags, "compiler", compilationBean.getName())) - .description("The approximate accumulated elapsed time spent in compilation") - .baseUnit(BaseUnits.MILLISECONDS).register(registry); + .tags(Tags.concat(tags, "compiler", compilationBean.getName())) + .description("The approximate accumulated elapsed time spent in compilation") + .baseUnit(BaseUnits.MILLISECONDS) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmGcMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmGcMetrics.java index 6f07778180..9e3bc046ab 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmGcMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmGcMetrics.java @@ -116,27 +116,37 @@ public void bindTo(MeterRegistry registry) { gcNotificationListener = new GcMetricsNotificationListener(registry); double maxLongLivedPoolBytes = getLongLivedHeapPools() - .mapToDouble(mem -> getUsageValue(mem, MemoryUsage::getMax)).sum(); + .mapToDouble(mem -> getUsageValue(mem, MemoryUsage::getMax)) + .sum(); maxDataSize = new AtomicLong((long) maxLongLivedPoolBytes); - Gauge.builder("jvm.gc.max.data.size", maxDataSize, AtomicLong::get).tags(tags) - .description("Max size of long-lived heap memory pool").baseUnit(BaseUnits.BYTES).register(registry); + Gauge.builder("jvm.gc.max.data.size", maxDataSize, AtomicLong::get) + .tags(tags) + .description("Max size of long-lived heap memory pool") + .baseUnit(BaseUnits.BYTES) + .register(registry); liveDataSize = new AtomicLong(); - Gauge.builder("jvm.gc.live.data.size", liveDataSize, AtomicLong::get).tags(tags) - .description("Size of long-lived heap memory pool after reclamation").baseUnit(BaseUnits.BYTES) - .register(registry); - - allocatedBytes = Counter.builder("jvm.gc.memory.allocated").tags(tags).baseUnit(BaseUnits.BYTES).description( - "Incremented for an increase in the size of the (young) heap memory pool after one GC to before the next") - .register(registry); - - promotedBytes = (isGenerationalGc) ? Counter.builder("jvm.gc.memory.promoted").tags(tags) - .baseUnit(BaseUnits.BYTES) - .description( - "Count of positive increases in the size of the old generation memory pool before GC to after GC") - .register(registry) : null; + Gauge.builder("jvm.gc.live.data.size", liveDataSize, AtomicLong::get) + .tags(tags) + .description("Size of long-lived heap memory pool after reclamation") + .baseUnit(BaseUnits.BYTES) + .register(registry); + + allocatedBytes = Counter.builder("jvm.gc.memory.allocated") + .tags(tags) + .baseUnit(BaseUnits.BYTES) + .description( + "Incremented for an increase in the size of the (young) heap memory pool after one GC to before the next") + .register(registry); + + promotedBytes = (isGenerationalGc) ? Counter.builder("jvm.gc.memory.promoted") + .tags(tags) + .baseUnit(BaseUnits.BYTES) + .description( + "Count of positive increases in the size of the old generation memory pool before GC to after GC") + .register(registry) : null; allocationPoolSizeAfter = new AtomicLong(0L); @@ -146,7 +156,7 @@ public void bindTo(MeterRegistry registry) { } NotificationEmitter notificationEmitter = (NotificationEmitter) gcBean; notificationEmitter.addNotificationListener(gcNotificationListener, notification -> notification.getType() - .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION), null); + .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION), null); notificationListenerCleanUpRunnables.add(() -> { try { notificationEmitter.removeNotificationListener(gcNotificationListener); @@ -175,14 +185,20 @@ public void handleNotification(Notification notification, Object ref) { GcInfo gcInfo = notificationInfo.getGcInfo(); long duration = gcInfo.getDuration(); if (isConcurrentPhase(gcCause, notificationInfo.getGcName())) { - Timer.builder("jvm.gc.concurrent.phase.time").tags(tags).tags("action", gcAction, "cause", gcCause) - .description("Time spent in concurrent phase").register(registry) - .record(duration, TimeUnit.MILLISECONDS); + Timer.builder("jvm.gc.concurrent.phase.time") + .tags(tags) + .tags("action", gcAction, "cause", gcCause) + .description("Time spent in concurrent phase") + .register(registry) + .record(duration, TimeUnit.MILLISECONDS); } else { - Timer.builder("jvm.gc.pause").tags(tags).tags("action", gcAction, "cause", gcCause) - .description("Time spent in GC pause").register(registry) - .record(duration, TimeUnit.MILLISECONDS); + Timer.builder("jvm.gc.pause") + .tags(tags) + .tags("action", gcAction, "cause", gcCause) + .description("Time spent in GC pause") + .register(registry) + .record(duration, TimeUnit.MILLISECONDS); } final Map before = gcInfo.getMemoryUsageBeforeGc(); @@ -190,8 +206,9 @@ public void handleNotification(Notification notification, Object ref) { countPoolSizeDelta(before, after); - final long longLivedBefore = longLivedPoolNames.stream().mapToLong(pool -> before.get(pool).getUsed()) - .sum(); + final long longLivedBefore = longLivedPoolNames.stream() + .mapToLong(pool -> before.get(pool).getUsed()) + .sum(); final long longLivedAfter = longLivedPoolNames.stream().mapToLong(pool -> after.get(pool).getUsed()).sum(); if (isGenerationalGc) { final long delta = longLivedAfter - longLivedBefore; @@ -242,8 +259,12 @@ private boolean nonGenerationalGcShouldUpdateDataSize(String gcName) { } private boolean isGenerationalGcConfigured() { - return ManagementFactory.getMemoryPoolMXBeans().stream().filter(JvmMemory::isHeap) - .map(MemoryPoolMXBean::getName).filter(name -> !name.contains("tenured")).count() > 1; + return ManagementFactory.getMemoryPoolMXBeans() + .stream() + .filter(JvmMemory::isHeap) + .map(MemoryPoolMXBean::getName) + .filter(name -> !name.contains("tenured")) + .count() > 1; } private static boolean isManagementExtensionsPresent() { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmHeapPressureMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmHeapPressureMetrics.java index 089901a27a..9c913fd86c 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmHeapPressureMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmHeapPressureMetrics.java @@ -77,8 +77,9 @@ public JvmHeapPressureMetrics(Iterable tags, Duration lookback, Duration te this.lookback = lookback; this.gcPauseSum = new TimeWindowSum((int) lookback.dividedBy(testEvery.toMillis()).toMillis(), testEvery); - longLivedPoolNames = JvmMemory.getLongLivedHeapPools().map(MemoryPoolMXBean::getName) - .collect(Collectors.toSet()); + longLivedPoolNames = JvmMemory.getLongLivedHeapPools() + .map(MemoryPoolMXBean::getName) + .collect(Collectors.toSet()); monitor(); } @@ -86,19 +87,24 @@ public JvmHeapPressureMetrics(Iterable tags, Duration lookback, Duration te @Override public void bindTo(@NonNull MeterRegistry registry) { if (!longLivedPoolNames.isEmpty()) { - Gauge.builder("jvm.memory.usage.after.gc", lastLongLivedPoolUsageAfterGc, AtomicReference::get).tags(tags) - .tag("area", "heap").tag("pool", "long-lived") - .description( - "The percentage of long-lived heap pool used after the last GC event, in the range [0..1]") - .baseUnit(BaseUnits.PERCENT).register(registry); + Gauge.builder("jvm.memory.usage.after.gc", lastLongLivedPoolUsageAfterGc, AtomicReference::get) + .tags(tags) + .tag("area", "heap") + .tag("pool", "long-lived") + .description("The percentage of long-lived heap pool used after the last GC event, in the range [0..1]") + .baseUnit(BaseUnits.PERCENT) + .register(registry); } Gauge.builder("jvm.gc.overhead", gcPauseSum, pauseSum -> { double overIntervalMillis = Math.min(System.nanoTime() - startOfMonitoring, lookback.toNanos()) / 1e6; return gcPauseSum.poll() / overIntervalMillis; - }).tags(tags).description( - "An approximation of the percent of CPU time used by GC activities over the last lookback period or since monitoring began, whichever is shorter, in the range [0..1]") - .baseUnit(BaseUnits.PERCENT).register(registry); + }) + .tags(tags) + .description( + "An approximation of the percent of CPU time used by GC activities over the last lookback period or since monitoring began, whichever is shorter, in the range [0..1]") + .baseUnit(BaseUnits.PERCENT) + .register(registry); } private void monitor() { @@ -121,15 +127,16 @@ private void monitor() { Map after = gcInfo.getMemoryUsageAfterGc(); if (!longLivedPoolNames.isEmpty()) { - final long usedAfter = longLivedPoolNames.stream().mapToLong(pool -> after.get(pool).getUsed()) - .sum(); + final long usedAfter = longLivedPoolNames.stream() + .mapToLong(pool -> after.get(pool).getUsed()) + .sum(); double maxAfter = longLivedPoolNames.stream().mapToLong(pool -> after.get(pool).getMax()).sum(); lastLongLivedPoolUsageAfterGc.set(usedAfter / maxAfter); } }; NotificationEmitter notificationEmitter = (NotificationEmitter) mbean; notificationEmitter.addNotificationListener(notificationListener, notification -> notification.getType() - .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION), null); + .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION), null); notificationListenerCleanUpRunnables.add(() -> { try { notificationEmitter.removeNotificationListener(notificationListener); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmInfoMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmInfoMetrics.java index d99daa3b1b..74bbfe4994 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmInfoMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmInfoMetrics.java @@ -29,11 +29,13 @@ public class JvmInfoMetrics implements MeterBinder { @Override public void bindTo(MeterRegistry registry) { - Gauge.builder("jvm.info", () -> 1L).description("JVM version info") - .tags("version", System.getProperty("java.runtime.version", "unknown"), "vendor", - System.getProperty("java.vm.vendor", "unknown"), "runtime", - System.getProperty("java.runtime.name", "unknown")) - .strongReference(true).register(registry); + Gauge.builder("jvm.info", () -> 1L) + .description("JVM version info") + .tags("version", System.getProperty("java.runtime.version", "unknown"), "vendor", + System.getProperty("java.vm.vendor", "unknown"), "runtime", + System.getProperty("java.runtime.name", "unknown")) + .strongReference(true) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmMemory.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmMemory.java index 6a95fafd68..2bf87e1131 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmMemory.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmMemory.java @@ -30,8 +30,10 @@ private JvmMemory() { } static Stream getLongLivedHeapPools() { - return ManagementFactory.getMemoryPoolMXBeans().stream().filter(JvmMemory::isHeap) - .filter(mem -> isLongLivedPool(mem.getName())); + return ManagementFactory.getMemoryPoolMXBeans() + .stream() + .filter(JvmMemory::isHeap) + .filter(mem -> isLongLivedPool(mem.getName())); } static boolean isConcurrentPhase(String cause, String name) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmMemoryMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmMemoryMetrics.java index c92cb74339..f6d561dfd2 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmMemoryMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmMemoryMetrics.java @@ -56,18 +56,23 @@ public void bindTo(MeterRegistry registry) { for (BufferPoolMXBean bufferPoolBean : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) { Iterable tagsWithId = Tags.concat(tags, "id", bufferPoolBean.getName()); - Gauge.builder("jvm.buffer.count", bufferPoolBean, BufferPoolMXBean::getCount).tags(tagsWithId) - .description("An estimate of the number of buffers in the pool").baseUnit(BaseUnits.BUFFERS) - .register(registry); - - Gauge.builder("jvm.buffer.memory.used", bufferPoolBean, BufferPoolMXBean::getMemoryUsed).tags(tagsWithId) - .description( - "An estimate of the memory that the Java virtual machine is using for this buffer pool") - .baseUnit(BaseUnits.BYTES).register(registry); + Gauge.builder("jvm.buffer.count", bufferPoolBean, BufferPoolMXBean::getCount) + .tags(tagsWithId) + .description("An estimate of the number of buffers in the pool") + .baseUnit(BaseUnits.BUFFERS) + .register(registry); + + Gauge.builder("jvm.buffer.memory.used", bufferPoolBean, BufferPoolMXBean::getMemoryUsed) + .tags(tagsWithId) + .description("An estimate of the memory that the Java virtual machine is using for this buffer pool") + .baseUnit(BaseUnits.BYTES) + .register(registry); Gauge.builder("jvm.buffer.total.capacity", bufferPoolBean, BufferPoolMXBean::getTotalCapacity) - .tags(tagsWithId).description("An estimate of the total capacity of the buffers in this pool") - .baseUnit(BaseUnits.BYTES).register(registry); + .tags(tagsWithId) + .description("An estimate of the total capacity of the buffers in this pool") + .baseUnit(BaseUnits.BYTES) + .register(registry); } for (MemoryPoolMXBean memoryPoolBean : ManagementFactory.getPlatformMXBeans(MemoryPoolMXBean.class)) { @@ -75,18 +80,23 @@ public void bindTo(MeterRegistry registry) { Iterable tagsWithId = Tags.concat(tags, "id", memoryPoolBean.getName(), "area", area); Gauge.builder("jvm.memory.used", memoryPoolBean, (mem) -> getUsageValue(mem, MemoryUsage::getUsed)) - .tags(tagsWithId).description("The amount of used memory").baseUnit(BaseUnits.BYTES) - .register(registry); - - Gauge.builder("jvm.memory.committed", memoryPoolBean, - (mem) -> getUsageValue(mem, MemoryUsage::getCommitted)).tags(tagsWithId) - .description("The amount of memory in bytes that is committed for the Java virtual machine to use") - .baseUnit(BaseUnits.BYTES).register(registry); + .tags(tagsWithId) + .description("The amount of used memory") + .baseUnit(BaseUnits.BYTES) + .register(registry); + + Gauge + .builder("jvm.memory.committed", memoryPoolBean, (mem) -> getUsageValue(mem, MemoryUsage::getCommitted)) + .tags(tagsWithId) + .description("The amount of memory in bytes that is committed for the Java virtual machine to use") + .baseUnit(BaseUnits.BYTES) + .register(registry); Gauge.builder("jvm.memory.max", memoryPoolBean, (mem) -> getUsageValue(mem, MemoryUsage::getMax)) - .tags(tagsWithId) - .description("The maximum amount of memory in bytes that can be used for memory management") - .baseUnit(BaseUnits.BYTES).register(registry); + .tags(tagsWithId) + .description("The maximum amount of memory in bytes that can be used for memory management") + .baseUnit(BaseUnits.BYTES) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmThreadMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmThreadMetrics.java index d4ba251798..9c90fa06f6 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmThreadMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/JvmThreadMetrics.java @@ -54,24 +54,32 @@ public JvmThreadMetrics(Iterable tags) { public void bindTo(MeterRegistry registry) { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); - Gauge.builder("jvm.threads.peak", threadBean, ThreadMXBean::getPeakThreadCount).tags(tags) - .description("The peak live thread count since the Java virtual machine started or peak was reset") - .baseUnit(BaseUnits.THREADS).register(registry); + Gauge.builder("jvm.threads.peak", threadBean, ThreadMXBean::getPeakThreadCount) + .tags(tags) + .description("The peak live thread count since the Java virtual machine started or peak was reset") + .baseUnit(BaseUnits.THREADS) + .register(registry); - Gauge.builder("jvm.threads.daemon", threadBean, ThreadMXBean::getDaemonThreadCount).tags(tags) - .description("The current number of live daemon threads").baseUnit(BaseUnits.THREADS) - .register(registry); + Gauge.builder("jvm.threads.daemon", threadBean, ThreadMXBean::getDaemonThreadCount) + .tags(tags) + .description("The current number of live daemon threads") + .baseUnit(BaseUnits.THREADS) + .register(registry); - Gauge.builder("jvm.threads.live", threadBean, ThreadMXBean::getThreadCount).tags(tags) - .description("The current number of live threads including both daemon and non-daemon threads") - .baseUnit(BaseUnits.THREADS).register(registry); + Gauge.builder("jvm.threads.live", threadBean, ThreadMXBean::getThreadCount) + .tags(tags) + .description("The current number of live threads including both daemon and non-daemon threads") + .baseUnit(BaseUnits.THREADS) + .register(registry); try { threadBean.getAllThreadIds(); for (Thread.State state : Thread.State.values()) { Gauge.builder("jvm.threads.states", threadBean, (bean) -> getThreadStateCount(bean, state)) - .tags(Tags.concat(tags, "state", getStateTagValue(state))) - .description("The current number of threads").baseUnit(BaseUnits.THREADS).register(registry); + .tags(Tags.concat(tags, "state", getStateTagValue(state))) + .description("The current number of threads") + .baseUnit(BaseUnits.THREADS) + .register(registry); } } catch (Error error) { @@ -83,7 +91,8 @@ public void bindTo(MeterRegistry registry) { // VisibleForTesting static long getThreadStateCount(ThreadMXBean threadBean, Thread.State state) { return Arrays.stream(threadBean.getThreadInfo(threadBean.getAllThreadIds())) - .filter(threadInfo -> threadInfo != null && threadInfo.getThreadState() == state).count(); + .filter(threadInfo -> threadInfo != null && threadInfo.getThreadState() == state) + .count(); } private static String getStateTagValue(Thread.State state) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetrics.java index 0f58dcb79d..7040365fb1 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetrics.java @@ -231,9 +231,12 @@ private Gauge registerGaugeForObject(MeterRegistry registry, ObjectName o, Strin Tags allTags, String description, @Nullable String baseUnit) { final AtomicReference gaugeReference = new AtomicReference<>(); Gauge gauge = Gauge - .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, - getJmxAttribute(registry, gaugeReference, o, jmxMetricName)) - .description(description).baseUnit(baseUnit).tags(allTags).register(registry); + .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, + getJmxAttribute(registry, gaugeReference, o, jmxMetricName)) + .description(description) + .baseUnit(baseUnit) + .tags(allTags) + .register(registry); gaugeReference.set(gauge); return gauge; } @@ -248,9 +251,12 @@ private FunctionCounter registerFunctionCounterForObject(MeterRegistry registry, Tags allTags, String description, @Nullable String baseUnit) { final AtomicReference counterReference = new AtomicReference<>(); FunctionCounter counter = FunctionCounter - .builder(METRIC_NAME_PREFIX + sanitize(jmxMetricName), mBeanServer, - getJmxAttribute(registry, counterReference, o, jmxMetricName)) - .description(description).baseUnit(baseUnit).tags(allTags).register(registry); + .builder(METRIC_NAME_PREFIX + sanitize(jmxMetricName), mBeanServer, + getJmxAttribute(registry, counterReference, o, jmxMetricName)) + .description(description) + .baseUnit(baseUnit) + .tags(allTags) + .register(registry); counterReference.set(counter); return counter; } @@ -259,9 +265,11 @@ private TimeGauge registerTimeGaugeForObject(MeterRegistry registry, ObjectName String meterName, Tags allTags, String description, TimeUnit timeUnit) { final AtomicReference timeGaugeReference = new AtomicReference<>(); TimeGauge timeGauge = TimeGauge - .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, timeUnit, - getJmxAttribute(registry, timeGaugeReference, o, jmxMetricName)) - .description(description).tags(allTags).register(registry); + .builder(METRIC_NAME_PREFIX + meterName, mBeanServer, timeUnit, + getJmxAttribute(registry, timeGaugeReference, o, jmxMetricName)) + .description(description) + .tags(allTags) + .register(registry); timeGaugeReference.set(timeGauge); return timeGauge; } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaMetrics.java index c6eb001dd2..cffd5d59e1 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaMetrics.java @@ -97,7 +97,7 @@ class KafkaMetrics implements MeterBinder, AutoCloseable { private final Duration refreshInterval; private final ScheduledExecutorService scheduler = Executors - .newSingleThreadScheduledExecutor(new NamedThreadFactory("micrometer-kafka-metrics")); + .newSingleThreadScheduledExecutor(new NamedThreadFactory("micrometer-kafka-metrics")); @Nullable private Iterable commonTags; @@ -191,7 +191,8 @@ void checkAndBindMetrics(MeterRegistry registry) { if (!currentMeters.equals(currentMetrics.keySet())) { Set metricsToRemove = currentMeters.stream() - .filter(metricName -> !currentMetrics.containsKey(metricName)).collect(Collectors.toSet()); + .filter(metricName -> !currentMetrics.containsKey(metricName)) + .collect(Collectors.toSet()); for (MetricName metricName : metricsToRemove) { Meter.Id id = meterIdForComparison(metricName); @@ -201,8 +202,9 @@ void checkAndBindMetrics(MeterRegistry registry) { currentMeters = new HashSet<>(currentMetrics.keySet()); - Map> registryMetersByNames = registry.getMeters().stream() - .collect(Collectors.groupingBy(meter -> meter.getId().getName())); + Map> registryMetersByNames = registry.getMeters() + .stream() + .collect(Collectors.groupingBy(meter -> meter.getId().getName())); currentMetrics.forEach((name, metric) -> { // Filter out non-numeric values @@ -294,14 +296,18 @@ private static Class getMeasurableClass(Metric metric) { } private Gauge registerGauge(MeterRegistry registry, MetricName metricName, String meterName, Iterable tags) { - return Gauge.builder(meterName, this.metrics, toMetricValue(metricName)).tags(tags) - .description(metricName.description()).register(registry); + return Gauge.builder(meterName, this.metrics, toMetricValue(metricName)) + .tags(tags) + .description(metricName.description()) + .register(registry); } private FunctionCounter registerCounter(MeterRegistry registry, MetricName metricName, String meterName, Iterable tags) { - return FunctionCounter.builder(meterName, this.metrics, toMetricValue(metricName)).tags(tags) - .description(metricName.description()).register(registry); + return FunctionCounter.builder(meterName, this.metrics, toMetricValue(metricName)) + .tags(tags) + .description(metricName.description()) + .register(registry); } private ToDoubleFunction>> toMetricValue(MetricName metricName) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/logging/Log4j2Metrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/logging/Log4j2Metrics.java index b62926f4d6..2dafb60be4 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/logging/Log4j2Metrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/logging/Log4j2Metrics.java @@ -77,24 +77,28 @@ public void bindTo(MeterRegistry registry) { LoggerConfig rootLoggerConfig = configuration.getRootLogger(); rootLoggerConfig.addFilter(createMetricsFilterAndStart(registry, rootLoggerConfig)); - loggerContext.getConfiguration().getLoggers().values().stream() - .filter(loggerConfig -> !loggerConfig.isAdditive()).forEach(loggerConfig -> { - if (loggerConfig == rootLoggerConfig) { - return; - } - Filter logFilter = loggerConfig.getFilter(); - - if ((logFilter instanceof CompositeFilter - && Arrays.stream(((CompositeFilter) logFilter).getFiltersArray()) - .anyMatch(innerFilter -> innerFilter instanceof MetricsFilter))) { - return; - } - - if (logFilter instanceof MetricsFilter) { - return; - } - loggerConfig.addFilter(createMetricsFilterAndStart(registry, loggerConfig)); - }); + loggerContext.getConfiguration() + .getLoggers() + .values() + .stream() + .filter(loggerConfig -> !loggerConfig.isAdditive()) + .forEach(loggerConfig -> { + if (loggerConfig == rootLoggerConfig) { + return; + } + Filter logFilter = loggerConfig.getFilter(); + + if ((logFilter instanceof CompositeFilter + && Arrays.stream(((CompositeFilter) logFilter).getFiltersArray()) + .anyMatch(innerFilter -> innerFilter instanceof MetricsFilter))) { + return; + } + + if (logFilter instanceof MetricsFilter) { + return; + } + loggerConfig.addFilter(createMetricsFilterAndStart(registry, loggerConfig)); + }); loggerContext.updateLoggers(configuration); } @@ -113,12 +117,16 @@ public void close() { LoggerConfig rootLoggerConfig = configuration.getRootLogger(); metricsFilters.forEach(rootLoggerConfig::removeFilter); - loggerContext.getConfiguration().getLoggers().values().stream() - .filter(loggerConfig -> !loggerConfig.isAdditive()).forEach(loggerConfig -> { - if (loggerConfig != rootLoggerConfig) { - metricsFilters.forEach(loggerConfig::removeFilter); - } - }); + loggerContext.getConfiguration() + .getLoggers() + .values() + .stream() + .filter(loggerConfig -> !loggerConfig.isAdditive()) + .forEach(loggerConfig -> { + if (loggerConfig != rootLoggerConfig) { + metricsFilters.forEach(loggerConfig::removeFilter); + } + }); loggerContext.updateLoggers(configuration); metricsFilters.forEach(MetricsFilter::stop); @@ -145,23 +153,47 @@ class MetricsFilter extends AbstractFilter { MetricsFilter(MeterRegistry registry, Iterable tags, boolean isAsyncLogger) { this.isAsyncLogger = isAsyncLogger; - fatalCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "fatal") - .description("Number of fatal level log events").baseUnit(BaseUnits.EVENTS).register(registry); - - errorCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "error") - .description("Number of error level log events").baseUnit(BaseUnits.EVENTS).register(registry); - - warnCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "warn") - .description("Number of warn level log events").baseUnit(BaseUnits.EVENTS).register(registry); - - infoCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "info") - .description("Number of info level log events").baseUnit(BaseUnits.EVENTS).register(registry); - - debugCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "debug") - .description("Number of debug level log events").baseUnit(BaseUnits.EVENTS).register(registry); - - traceCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "trace") - .description("Number of trace level log events").baseUnit(BaseUnits.EVENTS).register(registry); + fatalCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "fatal") + .description("Number of fatal level log events") + .baseUnit(BaseUnits.EVENTS) + .register(registry); + + errorCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "error") + .description("Number of error level log events") + .baseUnit(BaseUnits.EVENTS) + .register(registry); + + warnCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "warn") + .description("Number of warn level log events") + .baseUnit(BaseUnits.EVENTS) + .register(registry); + + infoCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "info") + .description("Number of info level log events") + .baseUnit(BaseUnits.EVENTS) + .register(registry); + + debugCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "debug") + .description("Number of debug level log events") + .baseUnit(BaseUnits.EVENTS) + .register(registry); + + traceCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "trace") + .description("Number of trace level log events") + .baseUnit(BaseUnits.EVENTS) + .register(registry); } @Override diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/logging/LogbackMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/logging/LogbackMetrics.java index edf3041722..20d50161b3 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/logging/LogbackMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/logging/LogbackMetrics.java @@ -152,20 +152,40 @@ class MetricsTurboFilter extends TurboFilter { private final Counter traceCounter; MetricsTurboFilter(MeterRegistry registry, Iterable tags) { - errorCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "error").description(METER_DESCRIPTION) - .baseUnit(BaseUnits.EVENTS).register(registry); - - warnCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "warn").description(METER_DESCRIPTION) - .baseUnit(BaseUnits.EVENTS).register(registry); - - infoCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "info").description(METER_DESCRIPTION) - .baseUnit(BaseUnits.EVENTS).register(registry); - - debugCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "debug").description(METER_DESCRIPTION) - .baseUnit(BaseUnits.EVENTS).register(registry); - - traceCounter = Counter.builder(METER_NAME).tags(tags).tags("level", "trace").description(METER_DESCRIPTION) - .baseUnit(BaseUnits.EVENTS).register(registry); + errorCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "error") + .description(METER_DESCRIPTION) + .baseUnit(BaseUnits.EVENTS) + .register(registry); + + warnCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "warn") + .description(METER_DESCRIPTION) + .baseUnit(BaseUnits.EVENTS) + .register(registry); + + infoCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "info") + .description(METER_DESCRIPTION) + .baseUnit(BaseUnits.EVENTS) + .register(registry); + + debugCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "debug") + .description(METER_DESCRIPTION) + .baseUnit(BaseUnits.EVENTS) + .register(registry); + + traceCounter = Counter.builder(METER_NAME) + .tags(tags) + .tags("level", "trace") + .description(METER_DESCRIPTION) + .baseUnit(BaseUnits.EVENTS) + .register(registry); } @Override diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/DefaultMongoCommandTagsProvider.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/DefaultMongoCommandTagsProvider.java index fce31924f0..2b8f33638d 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/DefaultMongoCommandTagsProvider.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/DefaultMongoCommandTagsProvider.java @@ -65,7 +65,7 @@ public Iterable commandTags(CommandEvent event) { @Override public void commandStarted(CommandStartedEvent event) { determineCollectionName(event.getCommandName(), event.getCommand()) - .ifPresent(collectionName -> addCollectionNameForCommand(event, collectionName)); + .ifPresent(collectionName -> addCollectionNameForCommand(event, collectionName)); } private void addCollectionNameForCommand(CommandEvent event, String collectionName) { @@ -118,8 +118,12 @@ protected Optional determineCollectionName(String commandName, BsonDocum * value was not a non-empty string */ private Optional getNonEmptyBsonString(BsonValue bsonValue) { - return Optional.ofNullable(bsonValue).filter(BsonValue::isString).map(BsonValue::asString) - .map(BsonString::getValue).map(String::trim).filter(StringUtils::isNotEmpty); + return Optional.ofNullable(bsonValue) + .filter(BsonValue::isString) + .map(BsonValue::asString) + .map(BsonString::getValue) + .map(String::trim) + .filter(StringUtils::isNotEmpty); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsCommandListener.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsCommandListener.java index 44462feb34..0f2debc8c0 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsCommandListener.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsCommandListener.java @@ -77,9 +77,11 @@ public void commandFailed(CommandFailedEvent event) { } private void timeCommand(CommandEvent event, long elapsedTimeInNanoseconds) { - Timer.builder("mongodb.driver.commands").description("Timer of mongodb commands") - .tags(tagsProvider.commandTags(event)).register(registry) - .record(elapsedTimeInNanoseconds, TimeUnit.NANOSECONDS); + Timer.builder("mongodb.driver.commands") + .description("Timer of mongodb commands") + .tags(tagsProvider.commandTags(event)) + .register(registry) + .record(elapsedTimeInNanoseconds, TimeUnit.NANOSECONDS); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsConnectionPoolListener.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsConnectionPoolListener.java index c97d9e50c1..8634980746 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsConnectionPoolListener.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsConnectionPoolListener.java @@ -159,8 +159,10 @@ private Gauge registerGauge(ConnectionPoolCreatedEvent event, String metricName, Map metrics) { AtomicInteger value = new AtomicInteger(); metrics.put(event.getServerId(), value); - return Gauge.builder(metricName, value, AtomicInteger::doubleValue).description(description) - .tags(tagsProvider.connectionPoolTags(event)).register(registry); + return Gauge.builder(metricName, value, AtomicInteger::doubleValue) + .description(description) + .tags(tagsProvider.connectionPoolTags(event)) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetrics.java index 32c74d5a7b..836a71964a 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetrics.java @@ -122,22 +122,29 @@ public void bindTo(@NonNull MeterRegistry registry) { cs.set(new ConnectionPoolConnectionStats()); } return cs.get().getActiveCount(); - }).baseUnit(BaseUnits.CONNECTIONS).description("The state of connections in the OkHttp connection pool") - .tags(Tags.of(tags).and(TAG_STATE, "active")).register(registry); + }) + .baseUnit(BaseUnits.CONNECTIONS) + .description("The state of connections in the OkHttp connection pool") + .tags(Tags.of(tags).and(TAG_STATE, "active")) + .register(registry); Gauge.builder(connectionCountName, connectionStats, cs -> { if (cs.get() == null) { cs.set(new ConnectionPoolConnectionStats()); } return cs.get().getIdleConnectionCount(); - }).baseUnit(BaseUnits.CONNECTIONS).description("The state of connections in the OkHttp connection pool") - .tags(Tags.of(tags).and(TAG_STATE, "idle")).register(registry); + }) + .baseUnit(BaseUnits.CONNECTIONS) + .description("The state of connections in the OkHttp connection pool") + .tags(Tags.of(tags).and(TAG_STATE, "idle")) + .register(registry); if (this.maxIdleConnectionCount != null) { Gauge.builder(namePrefix + ".connection.limit", () -> this.maxIdleConnectionCount) - .baseUnit(BaseUnits.CONNECTIONS) - .description("The maximum idle connection count in an OkHttp connection pool.") - .tags(Tags.concat(tags)).register(registry); + .baseUnit(BaseUnits.CONNECTIONS) + .description("The maximum idle connection count in an OkHttp connection pool.") + .tags(Tags.concat(tags)) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpMetricsEventListener.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpMetricsEventListener.java index c780b69e35..0beaad7803 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpMetricsEventListener.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpMetricsEventListener.java @@ -166,19 +166,24 @@ void time(CallState state) { boolean requestAvailable = request != null; Iterable tags = Tags - .of("method", requestAvailable ? request.method() : TAG_VALUE_UNKNOWN, "uri", getUriTag(state, request), - "status", getStatusMessage(state.response, state.exception)) - .and(extraTags) - .and(stream(contextSpecificTags.spliterator(), false) - .map(contextTag -> contextTag.apply(request, state.response)).collect(toList())) - .and(getRequestTags(request)).and(generateTagsForRoute(request)); + .of("method", requestAvailable ? request.method() : TAG_VALUE_UNKNOWN, "uri", getUriTag(state, request), + "status", getStatusMessage(state.response, state.exception)) + .and(extraTags) + .and(stream(contextSpecificTags.spliterator(), false) + .map(contextTag -> contextTag.apply(request, state.response)) + .collect(toList())) + .and(getRequestTags(request)) + .and(generateTagsForRoute(request)); if (includeHostTag) { tags = Tags.of(tags).and("host", requestAvailable ? request.url().host() : TAG_VALUE_UNKNOWN); } - Timer.builder(this.requestsMetricName).tags(tags).description("Timer of OkHttp operation").register(registry) - .record(registry.config().clock().monotonicTime() - state.startTime, TimeUnit.NANOSECONDS); + Timer.builder(this.requestsMetricName) + .tags(tags) + .description("Timer of OkHttp operation") + .register(registry) + .record(registry.config().clock().monotonicTime() - state.startTime, TimeUnit.NANOSECONDS); } private Tags generateTagsForRoute(@Nullable Request request) { @@ -254,7 +259,7 @@ public static class Builder { private final String name; private Function uriMapper = (request) -> Optional.ofNullable(request.header(URI_PATTERN)) - .orElse("none"); + .orElse("none"); private Tags tags = Tags.empty(); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/DiskSpaceMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/DiskSpaceMetrics.java index 09c09a3110..0a91a028d0 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/DiskSpaceMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/DiskSpaceMetrics.java @@ -58,10 +58,18 @@ public DiskSpaceMetrics(File path, Iterable tags) { @Override public void bindTo(MeterRegistry registry) { Iterable tagsWithPath = Tags.concat(tags, "path", absolutePath); - Gauge.builder("disk.free", path, File::getUsableSpace).tags(tagsWithPath).description("Usable space for path") - .baseUnit(BaseUnits.BYTES).strongReference(true).register(registry); - Gauge.builder("disk.total", path, File::getTotalSpace).tags(tagsWithPath).description("Total space for path") - .baseUnit(BaseUnits.BYTES).strongReference(true).register(registry); + Gauge.builder("disk.free", path, File::getUsableSpace) + .tags(tagsWithPath) + .description("Usable space for path") + .baseUnit(BaseUnits.BYTES) + .strongReference(true) + .register(registry); + Gauge.builder("disk.total", path, File::getTotalSpace) + .tags(tagsWithPath) + .description("Total space for path") + .baseUnit(BaseUnits.BYTES) + .strongReference(true) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/FileDescriptorMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/FileDescriptorMetrics.java index 0cd4d47694..a62d8adec0 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/FileDescriptorMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/FileDescriptorMetrics.java @@ -91,13 +91,19 @@ public FileDescriptorMetrics(Iterable tags) { @Override public void bindTo(MeterRegistry registry) { if (openFilesMethod != null) { - Gauge.builder("process.files.open", osBean, x -> invoke(openFilesMethod)).tags(tags) - .description("The open file descriptor count").baseUnit(BaseUnits.FILES).register(registry); + Gauge.builder("process.files.open", osBean, x -> invoke(openFilesMethod)) + .tags(tags) + .description("The open file descriptor count") + .baseUnit(BaseUnits.FILES) + .register(registry); } if (maxFilesMethod != null) { - Gauge.builder("process.files.max", osBean, x -> invoke(maxFilesMethod)).tags(tags) - .description("The maximum file descriptor count").baseUnit(BaseUnits.FILES).register(registry); + Gauge.builder("process.files.max", osBean, x -> invoke(maxFilesMethod)) + .tags(tags) + .description("The maximum file descriptor count") + .baseUnit(BaseUnits.FILES) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/ProcessorMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/ProcessorMetrics.java index 5eb177a018..39b14e187a 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/ProcessorMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/ProcessorMetrics.java @@ -88,27 +88,31 @@ public ProcessorMetrics(Iterable tags) { @Override public void bindTo(MeterRegistry registry) { Runtime runtime = Runtime.getRuntime(); - Gauge.builder("system.cpu.count", runtime, Runtime::availableProcessors).tags(tags) - .description("The number of processors available to the Java virtual machine").register(registry); + Gauge.builder("system.cpu.count", runtime, Runtime::availableProcessors) + .tags(tags) + .description("The number of processors available to the Java virtual machine") + .register(registry); if (operatingSystemBean.getSystemLoadAverage() >= 0) { Gauge.builder("system.load.average.1m", operatingSystemBean, OperatingSystemMXBean::getSystemLoadAverage) - .tags(tags) - .description( - "The sum of the number of runnable entities queued to available processors and the number " - + "of runnable entities running on the available processors averaged over a period of time") - .register(registry); + .tags(tags) + .description("The sum of the number of runnable entities queued to available processors and the number " + + "of runnable entities running on the available processors averaged over a period of time") + .register(registry); } if (systemCpuUsage != null) { - Gauge.builder("system.cpu.usage", operatingSystemBean, x -> invoke(systemCpuUsage)).tags(tags) - .description("The \"recent cpu usage\" of the system the application is running in") - .register(registry); + Gauge.builder("system.cpu.usage", operatingSystemBean, x -> invoke(systemCpuUsage)) + .tags(tags) + .description("The \"recent cpu usage\" of the system the application is running in") + .register(registry); } if (processCpuUsage != null) { - Gauge.builder("process.cpu.usage", operatingSystemBean, x -> invoke(processCpuUsage)).tags(tags) - .description("The \"recent cpu usage\" for the Java Virtual Machine process").register(registry); + Gauge.builder("process.cpu.usage", operatingSystemBean, x -> invoke(processCpuUsage)) + .tags(tags) + .description("The \"recent cpu usage\" for the Java Virtual Machine process") + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/UptimeMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/UptimeMetrics.java index c5d07bf4af..848eeb39a9 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/UptimeMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/UptimeMetrics.java @@ -57,11 +57,15 @@ public UptimeMetrics(Iterable tags) { @Override public void bindTo(MeterRegistry registry) { - TimeGauge.builder("process.uptime", runtimeMXBean, TimeUnit.MILLISECONDS, RuntimeMXBean::getUptime).tags(tags) - .description("The uptime of the Java virtual machine").register(registry); + TimeGauge.builder("process.uptime", runtimeMXBean, TimeUnit.MILLISECONDS, RuntimeMXBean::getUptime) + .tags(tags) + .description("The uptime of the Java virtual machine") + .register(registry); TimeGauge.builder("process.start.time", runtimeMXBean, TimeUnit.MILLISECONDS, RuntimeMXBean::getStartTime) - .tags(tags).description("Start time of the process since unix epoch.").register(registry); + .tags(tags) + .description("Start time of the process since unix epoch.") + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/tomcat/TomcatMetrics.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/tomcat/TomcatMetrics.java index 5e80cbfb48..5f9ff99e95 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/tomcat/TomcatMetrics.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/tomcat/TomcatMetrics.java @@ -114,105 +114,150 @@ private void registerSessionMetrics(MeterRegistry registry) { return; } - Gauge.builder("tomcat.sessions.active.max", manager, Manager::getMaxActive).tags(tags) - .baseUnit(BaseUnits.SESSIONS).register(registry); - - Gauge.builder("tomcat.sessions.active.current", manager, Manager::getActiveSessions).tags(tags) - .baseUnit(BaseUnits.SESSIONS).register(registry); - - FunctionCounter.builder("tomcat.sessions.created", manager, Manager::getSessionCounter).tags(tags) - .baseUnit(BaseUnits.SESSIONS).register(registry); - - FunctionCounter.builder("tomcat.sessions.expired", manager, Manager::getExpiredSessions).tags(tags) - .baseUnit(BaseUnits.SESSIONS).register(registry); - - FunctionCounter.builder("tomcat.sessions.rejected", manager, Manager::getRejectedSessions).tags(tags) - .baseUnit(BaseUnits.SESSIONS).register(registry); + Gauge.builder("tomcat.sessions.active.max", manager, Manager::getMaxActive) + .tags(tags) + .baseUnit(BaseUnits.SESSIONS) + .register(registry); + + Gauge.builder("tomcat.sessions.active.current", manager, Manager::getActiveSessions) + .tags(tags) + .baseUnit(BaseUnits.SESSIONS) + .register(registry); + + FunctionCounter.builder("tomcat.sessions.created", manager, Manager::getSessionCounter) + .tags(tags) + .baseUnit(BaseUnits.SESSIONS) + .register(registry); + + FunctionCounter.builder("tomcat.sessions.expired", manager, Manager::getExpiredSessions) + .tags(tags) + .baseUnit(BaseUnits.SESSIONS) + .register(registry); + + FunctionCounter.builder("tomcat.sessions.rejected", manager, Manager::getRejectedSessions) + .tags(tags) + .baseUnit(BaseUnits.SESSIONS) + .register(registry); TimeGauge.builder("tomcat.sessions.alive.max", manager, TimeUnit.SECONDS, Manager::getSessionMaxAliveTime) - .tags(tags).register(registry); + .tags(tags) + .register(registry); } private void registerThreadPoolMetrics(MeterRegistry registry) { registerMetricsEventually(":type=ThreadPool,name=*", (name, allTags) -> { - Gauge.builder("tomcat.threads.config.max", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "maxThreads"))).tags(allTags).baseUnit(BaseUnits.THREADS) - .register(registry); - - Gauge.builder("tomcat.threads.busy", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "currentThreadsBusy"))).tags(allTags) - .baseUnit(BaseUnits.THREADS).register(registry); - - Gauge.builder("tomcat.threads.current", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "currentThreadCount"))).tags(allTags) - .baseUnit(BaseUnits.THREADS).register(registry); - - Gauge.builder("tomcat.connections.current", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "connectionCount"))).tags(allTags) - .baseUnit(BaseUnits.CONNECTIONS).register(registry); - - Gauge.builder("tomcat.connections.keepalive.current", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "keepAliveCount"))).tags(allTags) - .baseUnit(BaseUnits.CONNECTIONS).register(registry); - - Gauge.builder("tomcat.connections.config.max", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "maxConnections"))).tags(allTags) - .baseUnit(BaseUnits.CONNECTIONS).register(registry); + Gauge + .builder("tomcat.threads.config.max", mBeanServer, + s -> safeDouble(() -> s.getAttribute(name, "maxThreads"))) + .tags(allTags) + .baseUnit(BaseUnits.THREADS) + .register(registry); + + Gauge + .builder("tomcat.threads.busy", mBeanServer, + s -> safeDouble(() -> s.getAttribute(name, "currentThreadsBusy"))) + .tags(allTags) + .baseUnit(BaseUnits.THREADS) + .register(registry); + + Gauge + .builder("tomcat.threads.current", mBeanServer, + s -> safeDouble(() -> s.getAttribute(name, "currentThreadCount"))) + .tags(allTags) + .baseUnit(BaseUnits.THREADS) + .register(registry); + + Gauge + .builder("tomcat.connections.current", mBeanServer, + s -> safeDouble(() -> s.getAttribute(name, "connectionCount"))) + .tags(allTags) + .baseUnit(BaseUnits.CONNECTIONS) + .register(registry); + + Gauge + .builder("tomcat.connections.keepalive.current", mBeanServer, + s -> safeDouble(() -> s.getAttribute(name, "keepAliveCount"))) + .tags(allTags) + .baseUnit(BaseUnits.CONNECTIONS) + .register(registry); + + Gauge + .builder("tomcat.connections.config.max", mBeanServer, + s -> safeDouble(() -> s.getAttribute(name, "maxConnections"))) + .tags(allTags) + .baseUnit(BaseUnits.CONNECTIONS) + .register(registry); }); } private void registerCacheMetrics(MeterRegistry registry) { registerMetricsEventually(":type=StringCache", (name, allTags) -> { FunctionCounter - .builder("tomcat.cache.access", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "accessCount"))) - .tags(allTags).register(registry); + .builder("tomcat.cache.access", mBeanServer, s -> safeDouble(() -> s.getAttribute(name, "accessCount"))) + .tags(allTags) + .register(registry); FunctionCounter - .builder("tomcat.cache.hit", mBeanServer, s -> safeDouble(() -> s.getAttribute(name, "hitCount"))) - .tags(allTags).register(registry); + .builder("tomcat.cache.hit", mBeanServer, s -> safeDouble(() -> s.getAttribute(name, "hitCount"))) + .tags(allTags) + .register(registry); }); } private void registerServletMetrics(MeterRegistry registry) { registerMetricsEventually(":j2eeType=Servlet,name=*,*", (name, allTags) -> { - FunctionCounter.builder("tomcat.servlet.error", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "errorCount"))).tags(allTags).register(registry); + FunctionCounter + .builder("tomcat.servlet.error", mBeanServer, s -> safeDouble(() -> s.getAttribute(name, "errorCount"))) + .tags(allTags) + .register(registry); FunctionTimer - .builder("tomcat.servlet.request", mBeanServer, - s -> safeLong(() -> s.getAttribute(name, "requestCount")), - s -> safeDouble(() -> s.getAttribute(name, "processingTime")), TimeUnit.MILLISECONDS) - .tags(allTags).register(registry); - - TimeGauge.builder("tomcat.servlet.request.max", mBeanServer, TimeUnit.MILLISECONDS, - s -> safeDouble(() -> s.getAttribute(name, "maxTime"))).tags(allTags).register(registry); + .builder("tomcat.servlet.request", mBeanServer, + s -> safeLong(() -> s.getAttribute(name, "requestCount")), + s -> safeDouble(() -> s.getAttribute(name, "processingTime")), TimeUnit.MILLISECONDS) + .tags(allTags) + .register(registry); + + TimeGauge + .builder("tomcat.servlet.request.max", mBeanServer, TimeUnit.MILLISECONDS, + s -> safeDouble(() -> s.getAttribute(name, "maxTime"))) + .tags(allTags) + .register(registry); }); } private void registerGlobalRequestMetrics(MeterRegistry registry) { registerMetricsEventually(":type=GlobalRequestProcessor,name=*", (name, allTags) -> { FunctionCounter - .builder("tomcat.global.sent", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "bytesSent"))) - .tags(allTags).baseUnit(BaseUnits.BYTES).register(registry); + .builder("tomcat.global.sent", mBeanServer, s -> safeDouble(() -> s.getAttribute(name, "bytesSent"))) + .tags(allTags) + .baseUnit(BaseUnits.BYTES) + .register(registry); FunctionCounter - .builder("tomcat.global.received", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "bytesReceived"))) - .tags(allTags).baseUnit(BaseUnits.BYTES).register(registry); + .builder("tomcat.global.received", mBeanServer, + s -> safeDouble(() -> s.getAttribute(name, "bytesReceived"))) + .tags(allTags) + .baseUnit(BaseUnits.BYTES) + .register(registry); - FunctionCounter.builder("tomcat.global.error", mBeanServer, - s -> safeDouble(() -> s.getAttribute(name, "errorCount"))).tags(allTags).register(registry); + FunctionCounter + .builder("tomcat.global.error", mBeanServer, s -> safeDouble(() -> s.getAttribute(name, "errorCount"))) + .tags(allTags) + .register(registry); FunctionTimer - .builder("tomcat.global.request", mBeanServer, - s -> safeLong(() -> s.getAttribute(name, "requestCount")), - s -> safeDouble(() -> s.getAttribute(name, "processingTime")), TimeUnit.MILLISECONDS) - .tags(allTags).register(registry); - - TimeGauge.builder("tomcat.global.request.max", mBeanServer, TimeUnit.MILLISECONDS, - s -> safeDouble(() -> s.getAttribute(name, "maxTime"))).tags(allTags).register(registry); + .builder("tomcat.global.request", mBeanServer, + s -> safeLong(() -> s.getAttribute(name, "requestCount")), + s -> safeDouble(() -> s.getAttribute(name, "processingTime")), TimeUnit.MILLISECONDS) + .tags(allTags) + .register(registry); + + TimeGauge + .builder("tomcat.global.request.max", mBeanServer, TimeUnit.MILLISECONDS, + s -> safeDouble(() -> s.getAttribute(name, "maxTime"))) + .tags(allTags) + .register(registry); }); } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/AbstractCompositeMeter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/AbstractCompositeMeter.java index b91faffb8d..8a1273c0ed 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/AbstractCompositeMeter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/AbstractCompositeMeter.java @@ -26,7 +26,7 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -abstract class AbstractCompositeMeter extends AbstractMeter implements CompositeMeter { +abstract class AbstractCompositeMeterextends AbstractMeter implements CompositeMeter { private final AtomicBoolean childrenGuard = new AtomicBoolean(); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeCounter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeCounter.java index dea5bd08e0..372cacb1a9 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeCounter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeCounter.java @@ -45,8 +45,11 @@ Counter newNoopMeter() { @Override Counter registerNewMeter(MeterRegistry registry) { - return Counter.builder(getId().getName()).tags(getId().getTagsAsIterable()) - .description(getId().getDescription()).baseUnit(getId().getBaseUnit()).register(registry); + return Counter.builder(getId().getName()) + .tags(getId().getTagsAsIterable()) + .description(getId().getDescription()) + .baseUnit(getId().getBaseUnit()) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeCustomMeter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeCustomMeter.java index 3f0bb08c92..28222a1be2 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeCustomMeter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeCustomMeter.java @@ -28,8 +28,11 @@ class CompositeCustomMeter extends DefaultMeter implements CompositeMeter { @Override public void add(MeterRegistry registry) { - Meter.builder(getId().getName(), getType(), measure()).tags(getId().getTagsAsIterable()) - .description(getId().getDescription()).baseUnit(getId().getBaseUnit()).register(registry); + Meter.builder(getId().getName(), getType(), measure()) + .tags(getId().getTagsAsIterable()) + .description(getId().getDescription()) + .baseUnit(getId().getBaseUnit()) + .register(registry); } @Override diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeDistributionSummary.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeDistributionSummary.java index 9eda13b9c0..44e6ea5335 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeDistributionSummary.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeDistributionSummary.java @@ -69,17 +69,20 @@ DistributionSummary newNoopMeter() { @SuppressWarnings("ConstantConditions") @Override DistributionSummary registerNewMeter(MeterRegistry registry) { - return DistributionSummary.builder(getId().getName()).tags(getId().getTagsAsIterable()) - .description(getId().getDescription()).baseUnit(getId().getBaseUnit()) - .publishPercentiles(distributionStatisticConfig.getPercentiles()) - .publishPercentileHistogram(distributionStatisticConfig.isPercentileHistogram()) - .maximumExpectedValue(distributionStatisticConfig.getMaximumExpectedValueAsDouble()) - .minimumExpectedValue(distributionStatisticConfig.getMinimumExpectedValueAsDouble()) - .distributionStatisticBufferLength(distributionStatisticConfig.getBufferLength()) - .distributionStatisticExpiry(distributionStatisticConfig.getExpiry()) - .percentilePrecision(distributionStatisticConfig.getPercentilePrecision()) - .serviceLevelObjectives(distributionStatisticConfig.getServiceLevelObjectiveBoundaries()).scale(scale) - .register(registry); + return DistributionSummary.builder(getId().getName()) + .tags(getId().getTagsAsIterable()) + .description(getId().getDescription()) + .baseUnit(getId().getBaseUnit()) + .publishPercentiles(distributionStatisticConfig.getPercentiles()) + .publishPercentileHistogram(distributionStatisticConfig.isPercentileHistogram()) + .maximumExpectedValue(distributionStatisticConfig.getMaximumExpectedValueAsDouble()) + .minimumExpectedValue(distributionStatisticConfig.getMinimumExpectedValueAsDouble()) + .distributionStatisticBufferLength(distributionStatisticConfig.getBufferLength()) + .distributionStatisticExpiry(distributionStatisticConfig.getExpiry()) + .percentilePrecision(distributionStatisticConfig.getPercentilePrecision()) + .serviceLevelObjectives(distributionStatisticConfig.getServiceLevelObjectiveBoundaries()) + .scale(scale) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeFunctionCounter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeFunctionCounter.java index 5f3a04662b..58f909b64b 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeFunctionCounter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeFunctionCounter.java @@ -23,7 +23,7 @@ import java.lang.ref.WeakReference; import java.util.function.ToDoubleFunction; -public class CompositeFunctionCounter extends AbstractCompositeMeter implements FunctionCounter { +public class CompositeFunctionCounterextends AbstractCompositeMeter implements FunctionCounter { private final WeakReference ref; @@ -53,8 +53,11 @@ FunctionCounter registerNewMeter(MeterRegistry registry) { return null; } - return FunctionCounter.builder(getId().getName(), obj, f).tags(getId().getTagsAsIterable()) - .description(getId().getDescription()).baseUnit(getId().getBaseUnit()).register(registry); + return FunctionCounter.builder(getId().getName(), obj, f) + .tags(getId().getTagsAsIterable()) + .description(getId().getDescription()) + .baseUnit(getId().getBaseUnit()) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeFunctionTimer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeFunctionTimer.java index 737c134e2d..627cd76cbb 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeFunctionTimer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeFunctionTimer.java @@ -25,7 +25,7 @@ import java.util.function.ToDoubleFunction; import java.util.function.ToLongFunction; -class CompositeFunctionTimer extends AbstractCompositeMeter implements FunctionTimer { +class CompositeFunctionTimerextends AbstractCompositeMeter implements FunctionTimer { private final WeakReference ref; @@ -72,7 +72,9 @@ FunctionTimer registerNewMeter(MeterRegistry registry) { } return FunctionTimer.builder(getId().getName(), obj, countFunction, totalTimeFunction, totalTimeFunctionUnit) - .tags(getId().getTagsAsIterable()).description(getId().getDescription()).register(registry); + .tags(getId().getTagsAsIterable()) + .description(getId().getDescription()) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeGauge.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeGauge.java index 567fa6dc3d..ba2f8e1815 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeGauge.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeGauge.java @@ -24,7 +24,7 @@ import java.lang.ref.WeakReference; import java.util.function.ToDoubleFunction; -class CompositeGauge extends AbstractCompositeMeter implements Gauge { +class CompositeGaugeextends AbstractCompositeMeter implements Gauge { private final WeakReference ref; @@ -53,8 +53,11 @@ Gauge registerNewMeter(MeterRegistry registry) { return null; } - return Gauge.builder(getId().getName(), obj, f).tags(getId().getTagsAsIterable()) - .description(getId().getDescription()).baseUnit(getId().getBaseUnit()).register(registry); + return Gauge.builder(getId().getName(), obj, f) + .tags(getId().getTagsAsIterable()) + .description(getId().getDescription()) + .baseUnit(getId().getBaseUnit()) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeLongTaskTimer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeLongTaskTimer.java index a1929408be..d34fabb2bf 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeLongTaskTimer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeLongTaskTimer.java @@ -78,17 +78,18 @@ LongTaskTimer newNoopMeter() { @SuppressWarnings("ConstantConditions") @Override LongTaskTimer registerNewMeter(MeterRegistry registry) { - LongTaskTimer.Builder builder = LongTaskTimer.builder(getId().getName()).tags(getId().getTagsAsIterable()) - .description(getId().getDescription()) - .maximumExpectedValue( - Duration.ofNanos(distributionStatisticConfig.getMaximumExpectedValueAsDouble().longValue())) - .minimumExpectedValue( - Duration.ofNanos(distributionStatisticConfig.getMinimumExpectedValueAsDouble().longValue())) - .publishPercentiles(distributionStatisticConfig.getPercentiles()) - .publishPercentileHistogram(distributionStatisticConfig.isPercentileHistogram()) - .distributionStatisticBufferLength(distributionStatisticConfig.getBufferLength()) - .distributionStatisticExpiry(distributionStatisticConfig.getExpiry()) - .percentilePrecision(distributionStatisticConfig.getPercentilePrecision()); + LongTaskTimer.Builder builder = LongTaskTimer.builder(getId().getName()) + .tags(getId().getTagsAsIterable()) + .description(getId().getDescription()) + .maximumExpectedValue( + Duration.ofNanos(distributionStatisticConfig.getMaximumExpectedValueAsDouble().longValue())) + .minimumExpectedValue( + Duration.ofNanos(distributionStatisticConfig.getMinimumExpectedValueAsDouble().longValue())) + .publishPercentiles(distributionStatisticConfig.getPercentiles()) + .publishPercentileHistogram(distributionStatisticConfig.isPercentileHistogram()) + .distributionStatisticBufferLength(distributionStatisticConfig.getBufferLength()) + .distributionStatisticExpiry(distributionStatisticConfig.getExpiry()) + .percentilePrecision(distributionStatisticConfig.getPercentilePrecision()); final double[] sloNanos = distributionStatisticConfig.getServiceLevelObjectiveBoundaries(); if (sloNanos != null) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeTimeGauge.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeTimeGauge.java index e5216cffbd..96601af091 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeTimeGauge.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeTimeGauge.java @@ -24,7 +24,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; -class CompositeTimeGauge extends AbstractCompositeMeter implements TimeGauge { +class CompositeTimeGaugeextends AbstractCompositeMeter implements TimeGauge { private final WeakReference ref; @@ -61,8 +61,10 @@ TimeGauge registerNewMeter(MeterRegistry registry) { return null; } - return TimeGauge.builder(getId().getName(), obj, fUnit, f).tags(getId().getTagsAsIterable()) - .description(getId().getDescription()).register(registry); + return TimeGauge.builder(getId().getName(), obj, fUnit, f) + .tags(getId().getTagsAsIterable()) + .description(getId().getDescription()) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeTimer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeTimer.java index ae58da2ef4..f29108d994 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeTimer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/CompositeTimer.java @@ -127,17 +127,19 @@ Timer newNoopMeter() { @SuppressWarnings("ConstantConditions") @Override Timer registerNewMeter(MeterRegistry registry) { - Timer.Builder builder = Timer.builder(getId().getName()).tags(getId().getTagsAsIterable()) - .description(getId().getDescription()) - .maximumExpectedValue( - Duration.ofNanos(distributionStatisticConfig.getMaximumExpectedValueAsDouble().longValue())) - .minimumExpectedValue( - Duration.ofNanos(distributionStatisticConfig.getMinimumExpectedValueAsDouble().longValue())) - .publishPercentiles(distributionStatisticConfig.getPercentiles()) - .publishPercentileHistogram(distributionStatisticConfig.isPercentileHistogram()) - .distributionStatisticBufferLength(distributionStatisticConfig.getBufferLength()) - .distributionStatisticExpiry(distributionStatisticConfig.getExpiry()) - .percentilePrecision(distributionStatisticConfig.getPercentilePrecision()).pauseDetector(pauseDetector); + Timer.Builder builder = Timer.builder(getId().getName()) + .tags(getId().getTagsAsIterable()) + .description(getId().getDescription()) + .maximumExpectedValue( + Duration.ofNanos(distributionStatisticConfig.getMaximumExpectedValueAsDouble().longValue())) + .minimumExpectedValue( + Duration.ofNanos(distributionStatisticConfig.getMinimumExpectedValueAsDouble().longValue())) + .publishPercentiles(distributionStatisticConfig.getPercentiles()) + .publishPercentileHistogram(distributionStatisticConfig.isPercentileHistogram()) + .distributionStatisticBufferLength(distributionStatisticConfig.getBufferLength()) + .distributionStatisticExpiry(distributionStatisticConfig.getExpiry()) + .percentilePrecision(distributionStatisticConfig.getPercentilePrecision()) + .pauseDetector(pauseDetector); final double[] sloNanos = distributionStatisticConfig.getServiceLevelObjectiveBoundaries(); if (sloNanos != null) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/MeterFilter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/MeterFilter.java index 5c25775b43..12db8bf999 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/MeterFilter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/MeterFilter.java @@ -311,8 +311,10 @@ static MeterFilter maxExpected(String prefix, Duration max) { @Override public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) { if (id.getType() == Meter.Type.TIMER && id.getName().startsWith(prefix)) { - return DistributionStatisticConfig.builder().maximumExpectedValue((double) max.toNanos()).build() - .merge(config); + return DistributionStatisticConfig.builder() + .maximumExpectedValue((double) max.toNanos()) + .build() + .merge(config); } return config; } @@ -366,8 +368,10 @@ static MeterFilter minExpected(String prefix, Duration min) { @Override public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) { if (id.getType() == Meter.Type.TIMER && id.getName().startsWith(prefix)) { - return DistributionStatisticConfig.builder().minimumExpectedValue((double) min.toNanos()).build() - .merge(config); + return DistributionStatisticConfig.builder() + .minimumExpectedValue((double) min.toNanos()) + .build() + .merge(config); } return config; } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/MeterRegistryConfigValidator.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/MeterRegistryConfigValidator.java index 0ad720157b..cb11fd6dfb 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/MeterRegistryConfigValidator.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/MeterRegistryConfigValidator.java @@ -33,8 +33,10 @@ private MeterRegistryConfigValidator() { @SafeVarargs public static Validated checkAll(M config, Function>... validation) { - return Arrays.stream(validation).map(v -> v.apply(config)).map(v -> (Validated) v).reduce(Validated.none(), - (v1, v2) -> (Validated) v1.and(v2)); + return Arrays.stream(validation) + .map(v -> v.apply(config)) + .map(v -> (Validated) v) + .reduce(Validated.none(), (v1, v2) -> (Validated) v1.and(v2)); } /** diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/DurationValidator.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/DurationValidator.java index 846f138277..f30b0d468f 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/DurationValidator.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/DurationValidator.java @@ -63,7 +63,7 @@ protected Validated doParse(String property, String value) { long multipliedResult = amount.longValue(); long multipliedFactor = (long) Math.pow(10, e); return validateChronoUnit(property, value, unit) - .map(cu -> Duration.of(multipliedResult, cu).dividedBy(multipliedFactor)); + .map(cu -> Duration.of(multipliedResult, cu).dividedBy(multipliedFactor)); } }, diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/PropertyValidator.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/PropertyValidator.java index 557279e4e4..a3d413c8f4 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/PropertyValidator.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/PropertyValidator.java @@ -112,7 +112,7 @@ public static Validated getUrlString(MeterRegistryConfig config, String try { return Validated.valid(prefixedProperty, value == null ? null : URI.create(value).toURL()) - .map(url -> value); + .map(url -> value); } catch (MalformedURLException | IllegalArgumentException ex) { return Validated.invalid(prefixedProperty, value, "must be a valid URL", InvalidReason.MALFORMED, ex); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/Validated.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/Validated.java index c221aa9067..5832866626 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/Validated.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/Validated.java @@ -41,7 +41,7 @@ * @since 1.5.0 */ @Incubating(since = "1.5.0") -public interface Validated extends Iterable> { +public interface Validatedextends Iterable> { boolean isValid(); @@ -50,8 +50,9 @@ default boolean isInvalid() { } default List> failures() { - return stream(spliterator(), false).filter(Validated::isInvalid).map(v -> (Invalid) v) - .collect(Collectors.toList()); + return stream(spliterator(), false).filter(Validated::isInvalid) + .map(v -> (Invalid) v) + .collect(Collectors.toList()); } static Secret validSecret(String property, String value) { @@ -389,8 +390,10 @@ public Validated flatMap(BiFunction, Validated> @NonNull @Override public Iterator> iterator() { - return Stream.concat(stream(left.spliterator(), false).map(v -> v.map(o -> (Object) o)), - stream(right.spliterator(), false).map(v -> v.map(o -> (Object) o))).iterator(); + return Stream + .concat(stream(left.spliterator(), false).map(v -> v.map(o -> (Object) o)), + stream(right.spliterator(), false).map(v -> v.map(o -> (Object) o))) + .iterator(); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/ValidationException.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/ValidationException.java index e3c0fbaf8d..7f8f0f8629 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/ValidationException.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/config/validate/ValidationException.java @@ -32,10 +32,12 @@ public class ValidationException extends IllegalStateException { private final Validated validation; public ValidationException(Validated validation) { - super(validation.failures().stream().map(invalid -> invalid.getProperty() + " was '" - + (invalid.getValue() == null ? "null" : invalid.getValue()) + "' but it " + invalid.getMessage()) - .collect(Collectors.joining("\n", - validation.failures().size() > 1 ? "Multiple validation failures:\n" : "", ""))); + super(validation.failures() + .stream() + .map(invalid -> invalid.getProperty() + " was '" + + (invalid.getValue() == null ? "null" : invalid.getValue()) + "' but it " + invalid.getMessage()) + .collect(Collectors.joining("\n", validation.failures().size() > 1 ? "Multiple validation failures:\n" : "", + ""))); this.validation = validation; } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/cumulative/CumulativeFunctionCounter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/cumulative/CumulativeFunctionCounter.java index ddc896017a..3f72342a87 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/cumulative/CumulativeFunctionCounter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/cumulative/CumulativeFunctionCounter.java @@ -22,7 +22,7 @@ import java.lang.ref.WeakReference; import java.util.function.ToDoubleFunction; -public class CumulativeFunctionCounter extends AbstractMeter implements FunctionCounter { +public class CumulativeFunctionCounterextends AbstractMeter implements FunctionCounter { private final WeakReference ref; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/cumulative/CumulativeFunctionTimer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/cumulative/CumulativeFunctionTimer.java index 803019f22f..563a335042 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/cumulative/CumulativeFunctionTimer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/cumulative/CumulativeFunctionTimer.java @@ -30,7 +30,7 @@ * @author Jon Schneider * @author Johnny Lim */ -public class CumulativeFunctionTimer extends AbstractMeter implements FunctionTimer { +public class CumulativeFunctionTimerextends AbstractMeter implements FunctionTimer { private final WeakReference ref; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/AbstractTimeWindowHistogram.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/AbstractTimeWindowHistogram.java index 1f44abf585..2c078b7ff1 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/AbstractTimeWindowHistogram.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/AbstractTimeWindowHistogram.java @@ -39,7 +39,7 @@ abstract class AbstractTimeWindowHistogram implements Histogram { @SuppressWarnings("rawtypes") private static final AtomicIntegerFieldUpdater rotatingUpdater = AtomicIntegerFieldUpdater - .newUpdater(AbstractTimeWindowHistogram.class, "rotating"); + .newUpdater(AbstractTimeWindowHistogram.class, "rotating"); final DistributionStatisticConfig distributionStatisticConfig; @@ -203,7 +203,7 @@ private CountAtBucket[] takeCountSnapshot() { } final Set monitoredValues = distributionStatisticConfig - .getHistogramBuckets(supportsAggregablePercentiles); + .getHistogramBuckets(supportsAggregablePercentiles); if (monitoredValues.isEmpty()) { return null; } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/DistributionStatisticConfig.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/DistributionStatisticConfig.java index 91d11771b1..3bf2a1c636 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/DistributionStatisticConfig.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/DistributionStatisticConfig.java @@ -37,8 +37,12 @@ public class DistributionStatisticConfig implements Mergeable { public static final DistributionStatisticConfig DEFAULT = builder().percentilesHistogram(false) - .percentilePrecision(1).minimumExpectedValue(1.0).maximumExpectedValue(Double.POSITIVE_INFINITY) - .expiry(Duration.ofMinutes(2)).bufferLength(3).build(); + .percentilePrecision(1) + .minimumExpectedValue(1.0) + .maximumExpectedValue(Double.POSITIVE_INFINITY) + .expiry(Duration.ofMinutes(2)) + .bufferLength(3) + .build(); public static final DistributionStatisticConfig NONE = builder().build(); @@ -80,19 +84,20 @@ public static Builder builder() { @Override public DistributionStatisticConfig merge(DistributionStatisticConfig parent) { return DistributionStatisticConfig.builder() - .percentilesHistogram( - this.percentileHistogram == null ? parent.percentileHistogram : this.percentileHistogram) - .percentiles(this.percentiles == null ? parent.percentiles : this.percentiles) - .serviceLevelObjectives(this.serviceLevelObjectives == null ? parent.serviceLevelObjectives - : this.serviceLevelObjectives) - .percentilePrecision( - this.percentilePrecision == null ? parent.percentilePrecision : this.percentilePrecision) - .minimumExpectedValue( - this.minimumExpectedValue == null ? parent.minimumExpectedValue : this.minimumExpectedValue) - .maximumExpectedValue( - this.maximumExpectedValue == null ? parent.maximumExpectedValue : this.maximumExpectedValue) - .expiry(this.expiry == null ? parent.expiry : this.expiry) - .bufferLength(this.bufferLength == null ? parent.bufferLength : this.bufferLength).build(); + .percentilesHistogram( + this.percentileHistogram == null ? parent.percentileHistogram : this.percentileHistogram) + .percentiles(this.percentiles == null ? parent.percentiles : this.percentiles) + .serviceLevelObjectives( + this.serviceLevelObjectives == null ? parent.serviceLevelObjectives : this.serviceLevelObjectives) + .percentilePrecision( + this.percentilePrecision == null ? parent.percentilePrecision : this.percentilePrecision) + .minimumExpectedValue( + this.minimumExpectedValue == null ? parent.minimumExpectedValue : this.minimumExpectedValue) + .maximumExpectedValue( + this.maximumExpectedValue == null ? parent.maximumExpectedValue : this.maximumExpectedValue) + .expiry(this.expiry == null ? parent.expiry : this.expiry) + .bufferLength(this.bufferLength == null ? parent.bufferLength : this.bufferLength) + .build(); } /** diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/FixedBoundaryVictoriaMetricsHistogram.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/FixedBoundaryVictoriaMetricsHistogram.java index fc446bfa71..c32af9f7a8 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/FixedBoundaryVictoriaMetricsHistogram.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/FixedBoundaryVictoriaMetricsHistogram.java @@ -88,8 +88,10 @@ public class FixedBoundaryVictoriaMetricsHistogram implements Histogram { String end = String.format("%.1fe%d", m, e10); VMRANGES[idx] = start + "..." + end; - UPPER_BOUNDS[idx] = BigDecimal.valueOf(m).setScale(1, RoundingMode.HALF_UP) - .multiply(BigDecimal.TEN.pow(e10, MathContext.DECIMAL128)).doubleValue(); + UPPER_BOUNDS[idx] = BigDecimal.valueOf(m) + .setScale(1, RoundingMode.HALF_UP) + .multiply(BigDecimal.TEN.pow(e10, MathContext.DECIMAL128)) + .doubleValue(); idx++; start = end; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/HistogramGauges.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/HistogramGauges.java index 0c2022ecd2..242661852b 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/HistogramGauges.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/HistogramGauges.java @@ -120,8 +120,10 @@ private HistogramGauges(HistogramSupport meter, MeterRegistry registry, }; Gauge.builder(percentileName.apply(valueAtPercentiles[i]), meter, percentileValueFunction) - .tags(percentileTags.apply(valueAtPercentiles[i])).baseUnit(meter.getId().getBaseUnit()) - .synthetic(meter.getId()).register(registry); + .tags(percentileTags.apply(valueAtPercentiles[i])) + .baseUnit(meter.getId().getBaseUnit()) + .synthetic(meter.getId()) + .register(registry); } for (int i = 0; i < countAtBuckets.length; i++) { @@ -134,7 +136,9 @@ private HistogramGauges(HistogramSupport meter, MeterRegistry registry, }; Gauge.builder(bucketName.apply(countAtBuckets[i]), meter, bucketCountFunction) - .tags(bucketTags.apply(countAtBuckets[i])).synthetic(meter.getId()).register(registry); + .tags(bucketTags.apply(countAtBuckets[i])) + .synthetic(meter.getId()) + .register(registry); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowFixedBoundaryHistogram.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowFixedBoundaryHistogram.java index 62e30eaa3e..875dfe8d6f 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowFixedBoundaryHistogram.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowFixedBoundaryHistogram.java @@ -60,7 +60,7 @@ public TimeWindowFixedBoundaryHistogram(Clock clock, DistributionStatisticConfig this.cumulativeBucketCounts = cumulativeBucketCounts; NavigableSet histogramBuckets = distributionStatisticConfig - .getHistogramBuckets(supportsAggregablePercentiles); + .getHistogramBuckets(supportsAggregablePercentiles); Boolean percentileHistogram = distributionStatisticConfig.isPercentileHistogram(); if (percentileHistogram != null && percentileHistogram) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java index f1889b7347..b42f26c56d 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java @@ -32,7 +32,7 @@ public class TimeWindowMax { private static final AtomicIntegerFieldUpdater rotatingUpdater = AtomicIntegerFieldUpdater - .newUpdater(TimeWindowMax.class, "rotating"); + .newUpdater(TimeWindowMax.class, "rotating"); private final Clock clock; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowSum.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowSum.java index 77337346a9..5524047ff0 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowSum.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowSum.java @@ -28,7 +28,7 @@ public class TimeWindowSum { private static final AtomicIntegerFieldUpdater rotatingUpdater = AtomicIntegerFieldUpdater - .newUpdater(TimeWindowSum.class, "rotating"); + .newUpdater(TimeWindowSum.class, "rotating"); private final long durationBetweenRotatesMillis; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardFunctionCounter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardFunctionCounter.java index daa9e60e20..6361b3427b 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardFunctionCounter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardFunctionCounter.java @@ -27,7 +27,7 @@ /** * @author Jon Schneider */ -public class DropwizardFunctionCounter extends AbstractMeter implements FunctionCounter { +public class DropwizardFunctionCounterextends AbstractMeter implements FunctionCounter { private final WeakReference ref; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardFunctionTimer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardFunctionTimer.java index acfeeb9d80..7360d5267c 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardFunctionTimer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardFunctionTimer.java @@ -36,7 +36,7 @@ * @author Jon Schneider * @author Johnny Lim */ -public class DropwizardFunctionTimer extends AbstractMeter implements FunctionTimer { +public class DropwizardFunctionTimerextends AbstractMeter implements FunctionTimer { private final WeakReference ref; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardMeterRegistry.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardMeterRegistry.java index 0babbdf343..992eda51ea 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardMeterRegistry.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/dropwizard/DropwizardMeterRegistry.java @@ -170,8 +170,10 @@ private String hierarchicalName(Meter.Id id) { @Override protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.builder().expiry(dropwizardConfig.step()).build() - .merge(DistributionStatisticConfig.DEFAULT); + return DistributionStatisticConfig.builder() + .expiry(dropwizardConfig.step()) + .build() + .merge(DistributionStatisticConfig.DEFAULT); } /** diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/CumulativeHistogramLongTaskTimer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/CumulativeHistogramLongTaskTimer.java index 40456514d4..451b87ce85 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/CumulativeHistogramLongTaskTimer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/CumulativeHistogramLongTaskTimer.java @@ -50,10 +50,10 @@ public HistogramSnapshot takeSnapshot() { snapshot = new HistogramSnapshot(snapshot.count(), snapshot.total(), snapshot.max(), snapshot.percentileValues(), Arrays.stream(snapshot.histogramCounts()) - .map(countAtBucket -> lastSnapshot == null ? countAtBucket - : new CountAtBucket(countAtBucket.bucket(), - countAtBucket.count() + lastSnapshot[i.getAndIncrement()].count())) - .toArray(CountAtBucket[]::new), + .map(countAtBucket -> lastSnapshot == null ? countAtBucket + : new CountAtBucket(countAtBucket.bucket(), + countAtBucket.count() + lastSnapshot[i.getAndIncrement()].count())) + .toArray(CountAtBucket[]::new), snapshot::outputSummary); lastSnapshot = snapshot.histogramCounts(); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/DefaultGauge.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/DefaultGauge.java index 28e1c0f1e1..b1574ad4ee 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/DefaultGauge.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/DefaultGauge.java @@ -31,7 +31,7 @@ * @author Jon Schneider * @author Johnny Lim */ -public class DefaultGauge extends AbstractMeter implements Gauge { +public class DefaultGaugeextends AbstractMeter implements Gauge { private static final WarnThenDebugLogger logger = new WarnThenDebugLogger(DefaultGauge.class); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/DefaultLongTaskTimer.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/DefaultLongTaskTimer.java index 7515f45b24..ad8591d573 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/DefaultLongTaskTimer.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/DefaultLongTaskTimer.java @@ -141,7 +141,8 @@ public HistogramSnapshot takeSnapshot() { CountAtBucket[] countAtBucketsArr = new CountAtBucket[0]; List percentilesAboveInterpolatableLine = percentilesRequested.stream() - .filter(p -> p * (activeTasks.size() + 1) > activeTasks.size()).collect(Collectors.toList()); + .filter(p -> p * (activeTasks.size() + 1) > activeTasks.size()) + .collect(Collectors.toList()); percentilesRequested.removeAll(percentilesAboveInterpolatableLine); @@ -158,8 +159,10 @@ public HistogramSnapshot takeSnapshot() { // Make snapshot of active task durations List youngestToOldestDurations = StreamSupport - .stream(((Iterable) activeTasks::descendingIterator).spliterator(), false).sequential() - .map(task -> task.duration(TimeUnit.NANOSECONDS)).collect(Collectors.toList()); + .stream(((Iterable) activeTasks::descendingIterator).spliterator(), false) + .sequential() + .map(task -> task.duration(TimeUnit.NANOSECONDS)) + .collect(Collectors.toList()); for (Double activeTaskDuration : youngestToOldestDurations) { while (bucket != null && activeTaskDuration > bucket) { countAtBuckets.add(new CountAtBucket(bucket, count)); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/OnlyOnceLoggingDenyMeterFilter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/OnlyOnceLoggingDenyMeterFilter.java index 57f56212b3..171b682079 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/OnlyOnceLoggingDenyMeterFilter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/internal/OnlyOnceLoggingDenyMeterFilter.java @@ -34,7 +34,7 @@ public final class OnlyOnceLoggingDenyMeterFilter implements MeterFilter { private static final InternalLogger logger = InternalLoggerFactory - .getInstance(OnlyOnceLoggingDenyMeterFilter.class); + .getInstance(OnlyOnceLoggingDenyMeterFilter.class); private final AtomicBoolean alreadyWarned = new AtomicBoolean(); diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/logging/LoggingMeterRegistry.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/logging/LoggingMeterRegistry.java index 97e8e02e6f..815c50e397 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/logging/LoggingMeterRegistry.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/logging/LoggingMeterRegistry.java @@ -81,7 +81,8 @@ private LoggingMeterRegistry(LoggingRegistryConfig config, Clock clock, ThreadFa private Function defaultMeterIdPrinter() { return (meter) -> getConventionName(meter.getId()) + getConventionTags(meter.getId()).stream() - .map(t -> t.getKey() + "=" + t.getValue()).collect(joining(",", "{", "}")); + .map(t -> t.getKey() + "=" + t.getValue()) + .collect(joining(",", "{", "}")); } @Override @@ -189,7 +190,7 @@ String id() { String time(double time) { return TimeUtils - .format(Duration.ofNanos((long) TimeUtils.convert(time, getBaseTimeUnit(), TimeUnit.NANOSECONDS))); + .format(Duration.ofNanos((long) TimeUtils.convert(time, getBaseTimeUnit(), TimeUnit.NANOSECONDS))); } String rate(double rate) { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/search/MeterNotFoundException.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/search/MeterNotFoundException.java index 961e4c5130..adb4fe7d60 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/search/MeterNotFoundException.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/search/MeterNotFoundException.java @@ -62,8 +62,14 @@ private String nameDetail() { if (search.nameMatches == null) return null; - Collection matchingName = Search.in(search.registry).name(search.nameMatches).meters().stream() - .map(m -> m.getId().getName()).distinct().sorted().collect(toList()); + Collection matchingName = Search.in(search.registry) + .name(search.nameMatches) + .meters() + .stream() + .map(m -> m.getId().getName()) + .distinct() + .sorted() + .collect(toList()); if (!matchingName.isEmpty()) { if (matchingName.size() == 1) { @@ -90,9 +96,16 @@ private List tagDetail() { List details = new ArrayList<>(); for (String requiredKey : search.requiredTagKeys) { - Collection matchingRequiredKey = Search.in(search.registry).name(search.nameMatches) - .tagKeys(requiredKey).meters().stream().filter(requiredMeterType::isInstance) - .map(m -> m.getId().getName()).distinct().sorted().collect(toList()); + Collection matchingRequiredKey = Search.in(search.registry) + .name(search.nameMatches) + .tagKeys(requiredKey) + .meters() + .stream() + .filter(requiredMeterType::isInstance) + .map(m -> m.getId().getName()) + .distinct() + .sorted() + .collect(toList()); String requiredTagDetail = "the required tag '" + requiredKey + "'."; if (matchingRequiredKey.isEmpty()) { @@ -110,17 +123,30 @@ else if (matchingRequiredKey.size() == 1) { } for (Tag requiredTag : search.requiredTags) { - Collection matchingRequiredTag = Search.in(search.registry).name(search.nameMatches) - .tag(requiredTag.getKey(), requiredTag.getValue()).meters().stream() - .filter(requiredMeterType::isInstance).map(m -> m.getId().getName()).distinct().sorted() - .collect(toList()); + Collection matchingRequiredTag = Search.in(search.registry) + .name(search.nameMatches) + .tag(requiredTag.getKey(), requiredTag.getValue()) + .meters() + .stream() + .filter(requiredMeterType::isInstance) + .map(m -> m.getId().getName()) + .distinct() + .sorted() + .collect(toList()); String requiredTagDetail = "a tag '" + requiredTag.getKey() + "' with value '" + requiredTag.getValue() + "'."; if (matchingRequiredTag.isEmpty()) { - Collection nonMatchingValues = Search.in(search.registry).name(search.nameMatches) - .tagKeys(requiredTag.getKey()).meters().stream().filter(requiredMeterType::isInstance) - .map(m -> m.getId().getTag(requiredTag.getKey())).distinct().sorted().collect(toList()); + Collection nonMatchingValues = Search.in(search.registry) + .name(search.nameMatches) + .tagKeys(requiredTag.getKey()) + .meters() + .stream() + .filter(requiredMeterType::isInstance) + .map(m -> m.getId().getTag(requiredTag.getKey())) + .distinct() + .sorted() + .collect(toList()); if (nonMatchingValues.isEmpty()) { details.add(NOT_OK + " No meters have the required tag '" + requiredTag.getKey() + "'."); @@ -164,8 +190,11 @@ private String typeDetail() { if (!matchesName.isEmpty()) { Collection nonMatchingTypes = matchesName.stream() - .filter(m -> !requiredMeterType.isInstance(m)).map(m -> meterTypeName(m.getClass())) - .distinct().sorted().collect(toList()); + .filter(m -> !requiredMeterType.isInstance(m)) + .map(m -> meterTypeName(m.getClass())) + .distinct() + .sorted() + .collect(toList()); if (nonMatchingTypes.size() == 1) { return NOT_OK + " Expected to find a " + meterTypeName(requiredMeterType) diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/search/RequiredSearch.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/search/RequiredSearch.java index 96a77ace5c..cb63c88e76 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/search/RequiredSearch.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/search/RequiredSearch.java @@ -227,8 +227,9 @@ public Collection meters() { } private Stream meterStream() { - Stream meterStream = registry.getMeters().stream() - .filter(m -> nameMatches == null || nameMatches.test(m.getId().getName())); + Stream meterStream = registry.getMeters() + .stream() + .filter(m -> nameMatches == null || nameMatches.test(m.getId().getName())); if (!requiredTags.isEmpty() || !requiredTagKeys.isEmpty()) { meterStream = meterStream.filter(m -> { diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/simple/SimpleMeterRegistry.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/simple/SimpleMeterRegistry.java index bca764322e..4773a213a5 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/simple/SimpleMeterRegistry.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/simple/SimpleMeterRegistry.java @@ -60,7 +60,7 @@ public SimpleMeterRegistry(SimpleConfig config, Clock clock) { protected DistributionSummary newDistributionSummary(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, double scale) { DistributionStatisticConfig merged = distributionStatisticConfig - .merge(DistributionStatisticConfig.builder().expiry(config.step()).build()); + .merge(DistributionStatisticConfig.builder().expiry(config.step()).build()); DistributionSummary summary; switch (config.mode()) { @@ -87,7 +87,7 @@ protected Meter newMeter(Meter.Id id, Meter.Type type, Iterable mea protected Timer newTimer(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetector) { DistributionStatisticConfig merged = distributionStatisticConfig - .merge(DistributionStatisticConfig.builder().expiry(config.step()).build()); + .merge(DistributionStatisticConfig.builder().expiry(config.step()).build()); Timer timer; switch (config.mode()) { @@ -164,8 +164,10 @@ protected TimeUnit getBaseTimeUnit() { @Override protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.builder().expiry(config.step()).build() - .merge(DistributionStatisticConfig.DEFAULT); + return DistributionStatisticConfig.builder() + .expiry(config.step()) + .build() + .merge(DistributionStatisticConfig.DEFAULT); } /** @@ -177,8 +179,11 @@ protected DistributionStatisticConfig defaultHistogramConfig() { */ @Incubating(since = "1.9.0") public String getMetersAsString() { - return this.getMeters().stream().sorted(Comparator.comparing(meter -> meter.getId().getName())) - .map(this::toString).collect(Collectors.joining("\n")); + return this.getMeters() + .stream() + .sorted(Comparator.comparing(meter -> meter.getId().getName())) + .map(this::toString) + .collect(Collectors.joining("\n")); } private String toString(Meter meter) { @@ -187,7 +192,8 @@ private String toString(Meter meter) { String baseUnit = id.getBaseUnit(); String meterUnitSuffix = baseUnit != null ? " " + baseUnit : ""; String measurements = StreamSupport.stream(meter.measure().spliterator(), false) - .map((measurement) -> toString(measurement, meterUnitSuffix)).collect(Collectors.joining(", ")); + .map((measurement) -> toString(measurement, meterUnitSuffix)) + .collect(Collectors.joining(", ")); return String.format("%s(%s)[%s]; %s", id.getName(), id.getType(), tags, measurements); } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepFunctionCounter.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepFunctionCounter.java index 7a66ae5974..58a8ebe951 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepFunctionCounter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepFunctionCounter.java @@ -22,7 +22,7 @@ import java.lang.ref.WeakReference; import java.util.function.ToDoubleFunction; -public class StepFunctionCounter extends AbstractMeter implements FunctionCounter { +public class StepFunctionCounterextends AbstractMeter implements FunctionCounter { private final WeakReference ref; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepMeterRegistry.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepMeterRegistry.java index 50a147e0e7..e827fe2bb6 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepMeterRegistry.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepMeterRegistry.java @@ -98,8 +98,10 @@ protected Meter newMeter(Meter.Id id, Meter.Type type, Iterable mea @Override protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.builder().expiry(config.step()).build() - .merge(DistributionStatisticConfig.DEFAULT); + return DistributionStatisticConfig.builder() + .expiry(config.step()) + .build() + .merge(DistributionStatisticConfig.DEFAULT); } } diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/util/AbstractPartition.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/util/AbstractPartition.java index 419a4c68ce..65a5df7a3c 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/util/AbstractPartition.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/util/AbstractPartition.java @@ -28,7 +28,7 @@ * @author Jon Schneider * @since 1.2.2 */ -public abstract class AbstractPartition extends AbstractList> { +public abstract class AbstractPartitionextends AbstractList> { final List delegate; diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/util/HierarchicalNameMapper.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/util/HierarchicalNameMapper.java index a2c548710e..74c4a95a1a 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/util/HierarchicalNameMapper.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/util/HierarchicalNameMapper.java @@ -32,9 +32,12 @@ public interface HierarchicalNameMapper { * Sort tags alphabetically by key and append tag key values to the name with '.', * e.g. {@code http_server_requests.response.200.method.GET} */ - HierarchicalNameMapper DEFAULT = (id, convention) -> id.getConventionName(convention) - + id.getConventionTags(convention).stream().map(t -> "." + t.getKey() + "." + t.getValue()) - .map(nameSegment -> nameSegment.replace(" ", "_")).collect(Collectors.joining("")); + HierarchicalNameMapper DEFAULT = (id, + convention) -> id.getConventionName(convention) + id.getConventionTags(convention) + .stream() + .map(t -> "." + t.getKey() + "." + t.getValue()) + .map(nameSegment -> nameSegment.replace(" ", "_")) + .collect(Collectors.joining("")); String toHierarchicalName(Meter.Id id, NamingConvention convention); diff --git a/micrometer-core/src/main/java/io/micrometer/core/ipc/http/HttpSender.java b/micrometer-core/src/main/java/io/micrometer/core/ipc/http/HttpSender.java index 443d2367e2..c336a526b7 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/ipc/http/HttpSender.java +++ b/micrometer-core/src/main/java/io/micrometer/core/ipc/http/HttpSender.java @@ -113,8 +113,9 @@ public static Builder build(String uri, HttpSender sender) { @Override public String toString() { - StringBuilder printed = new StringBuilder(method.toString()).append(' ').append(url.toString()) - .append("\n"); + StringBuilder printed = new StringBuilder(method.toString()).append(' ') + .append(url.toString()) + .append("\n"); if (entity.length == 0) { printed.append(""); } @@ -171,8 +172,8 @@ public final Builder withHeader(String name, String value) { public final Builder withBasicAuthentication(@Nullable String user, @Nullable String password) { if (StringUtils.isNotBlank(user)) { String encoded = Base64.getEncoder() - .encodeToString((user.trim() + ":" + (password == null ? "" : password.trim())) - .getBytes(StandardCharsets.UTF_8)); + .encodeToString((user.trim() + ":" + (password == null ? "" : password.trim())) + .getBytes(StandardCharsets.UTF_8)); withAuthentication("Basic", encoded); } return this; diff --git a/micrometer-core/src/main/java/io/micrometer/core/util/internal/logging/MessageFormatter.java b/micrometer-core/src/main/java/io/micrometer/core/util/internal/logging/MessageFormatter.java index 4337c9ca35..e1e99193df 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/util/internal/logging/MessageFormatter.java +++ b/micrometer-core/src/main/java/io/micrometer/core/util/internal/logging/MessageFormatter.java @@ -299,8 +299,8 @@ private static void safeObjectAppend(StringBuilder sbuf, Object o) { sbuf.append(oAsString); } catch (Throwable t) { - System.err.println( - "SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + ']'); + System.err + .println("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + ']'); t.printStackTrace(); sbuf.append("[FAILED toString()]"); } diff --git a/micrometer-core/src/test/java/io/micrometer/core/aop/CountedAspectTest.java b/micrometer-core/src/test/java/io/micrometer/core/aop/CountedAspectTest.java index b77d19e47a..69f5f4e89d 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/aop/CountedAspectTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/aop/CountedAspectTest.java @@ -55,9 +55,12 @@ void countedWithoutSuccessfulMetrics() { void countedWithSuccessfulMetrics() { countedService.succeedWithMetrics(); - Counter counter = meterRegistry.get("metric.success").tag("method", "succeedWithMetrics") - .tag("class", getClass().getName() + "$CountedService").tag("extra", "tag").tag("result", "success") - .counter(); + Counter counter = meterRegistry.get("metric.success") + .tag("method", "succeedWithMetrics") + .tag("class", getClass().getName() + "$CountedService") + .tag("extra", "tag") + .tag("result", "success") + .counter(); assertThat(counter.count()).isOne(); assertThat(counter.getId().getDescription()).isNull(); @@ -81,9 +84,12 @@ void countedWithFailure() { catch (Exception ignored) { } - Counter counter = meterRegistry.get("metric.failing").tag("method", "fail") - .tag("class", getClass().getName() + "$CountedService").tag("exception", "RuntimeException") - .tag("result", "failure").counter(); + Counter counter = meterRegistry.get("metric.failing") + .tag("method", "fail") + .tag("class", getClass().getName() + "$CountedService") + .tag("exception", "RuntimeException") + .tag("result", "failure") + .counter(); assertThat(counter.count()).isOne(); assertThat(counter.getId().getDescription()).isEqualTo("To record something"); @@ -118,16 +124,24 @@ void countedWithSuccessfulMetricsWhenCompleted() { GuardedResult guardedResult = new GuardedResult(); CompletableFuture completableFuture = asyncCountedService.succeedWithMetrics(guardedResult); - assertThat(meterRegistry.find("metric.success").tag("method", "succeedWithMetrics") - .tag("class", getClass().getName() + "$AsyncCountedService").tag("extra", "tag") - .tag("exception", "none").tag("result", "success").counter()).isNull(); + assertThat(meterRegistry.find("metric.success") + .tag("method", "succeedWithMetrics") + .tag("class", getClass().getName() + "$AsyncCountedService") + .tag("extra", "tag") + .tag("exception", "none") + .tag("result", "success") + .counter()).isNull(); guardedResult.complete(); completableFuture.join(); - Counter counterAfterCompletion = meterRegistry.get("metric.success").tag("method", "succeedWithMetrics") - .tag("class", getClass().getName() + "$AsyncCountedService").tag("extra", "tag") - .tag("exception", "none").tag("result", "success").counter(); + Counter counterAfterCompletion = meterRegistry.get("metric.success") + .tag("method", "succeedWithMetrics") + .tag("class", getClass().getName() + "$AsyncCountedService") + .tag("extra", "tag") + .tag("exception", "none") + .tag("result", "success") + .counter(); assertThat(counterAfterCompletion.count()).isOne(); assertThat(counterAfterCompletion.getId().getDescription()).isNull(); @@ -138,16 +152,22 @@ void countedWithFailureWhenCompleted() { GuardedResult guardedResult = new GuardedResult(); CompletableFuture completableFuture = asyncCountedService.fail(guardedResult); - assertThat(meterRegistry.find("metric.failing").tag("method", "fail") - .tag("class", getClass().getName() + "$AsyncCountedService").tag("exception", "RuntimeException") - .tag("result", "failure").counter()).isNull(); + assertThat(meterRegistry.find("metric.failing") + .tag("method", "fail") + .tag("class", getClass().getName() + "$AsyncCountedService") + .tag("exception", "RuntimeException") + .tag("result", "failure") + .counter()).isNull(); guardedResult.complete(new RuntimeException()); assertThatThrownBy(completableFuture::join).isInstanceOf(RuntimeException.class); - Counter counter = meterRegistry.get("metric.failing").tag("method", "fail") - .tag("class", getClass().getName() + "$AsyncCountedService").tag("exception", "RuntimeException") - .tag("result", "failure").counter(); + Counter counter = meterRegistry.get("metric.failing") + .tag("method", "fail") + .tag("class", getClass().getName() + "$AsyncCountedService") + .tag("exception", "RuntimeException") + .tag("result", "failure") + .counter(); assertThat(counter.count()).isOne(); assertThat(counter.getId().getDescription()).isEqualTo("To record something"); @@ -159,7 +179,7 @@ void countedWithEmptyMetricNamesWhenCompleted() { GuardedResult emptyMetricNameWithExceptionResult = new GuardedResult(); CompletableFuture emptyMetricNameFuture = asyncCountedService.emptyMetricName(emptyMetricNameResult); CompletableFuture emptyMetricNameWithExceptionFuture = asyncCountedService - .emptyMetricName(emptyMetricNameWithExceptionResult); + .emptyMetricName(emptyMetricNameWithExceptionResult); assertThat(meterRegistry.find("method.counted").counters()).hasSize(0); diff --git a/micrometer-core/src/test/java/io/micrometer/core/aop/TimedAspectTest.java b/micrometer-core/src/test/java/io/micrometer/core/aop/TimedAspectTest.java index a3625a83d3..293d444024 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/aop/TimedAspectTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/aop/TimedAspectTest.java @@ -50,8 +50,12 @@ void timeMethod() { service.call(); - assertThat(registry.get("call").tag("class", getClass().getName() + "$TimedService").tag("method", "call") - .tag("extra", "tag").timer().count()).isEqualTo(1); + assertThat(registry.get("call") + .tag("class", getClass().getName() + "$TimedService") + .tag("method", "call") + .tag("extra", "tag") + .timer() + .count()).isEqualTo(1); } @Test @@ -79,8 +83,12 @@ void timeMethodWithLongTaskTimer() { service.longCall(); - assertThat(registry.get("longCall").tag("class", getClass().getName() + "$TimedService") - .tag("method", "longCall").tag("extra", "tag").longTaskTimers().size()).isEqualTo(1); + assertThat(registry.get("longCall") + .tag("class", getClass().getName() + "$TimedService") + .tag("method", "longCall") + .tag("extra", "tag") + .longTaskTimers() + .size()).isEqualTo(1); } @Test @@ -95,8 +103,11 @@ void timeMethodFailure() { service.call(); assertThatExceptionOfType(MeterNotFoundException.class).isThrownBy(() -> { - failingRegistry.get("call").tag("class", getClass().getName() + "$TimedService").tag("method", "call") - .tag("extra", "tag").timer(); + failingRegistry.get("call") + .tag("class", getClass().getName() + "$TimedService") + .tag("method", "call") + .tag("extra", "tag") + .timer(); }); } @@ -112,8 +123,11 @@ void timeMethodFailureWithLongTaskTimer() { service.longCall(); assertThatExceptionOfType(MeterNotFoundException.class).isThrownBy(() -> { - failingRegistry.get("longCall").tag("class", getClass().getName() + "$TimedService") - .tag("method", "longCall").tag("extra", "tag").longTaskTimer(); + failingRegistry.get("longCall") + .tag("class", getClass().getName() + "$TimedService") + .tag("method", "longCall") + .tag("extra", "tag") + .longTaskTimer(); }); } @@ -129,14 +143,23 @@ void timeMethodWhenCompleted() { GuardedResult guardedResult = new GuardedResult(); CompletableFuture completableFuture = service.call(guardedResult); - assertThat(registry.find("call").tag("class", getClass().getName() + "$AsyncTimedService").tag("method", "call") - .tag("extra", "tag").tag("exception", "none").timer()).isNull(); + assertThat(registry.find("call") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "call") + .tag("extra", "tag") + .tag("exception", "none") + .timer()).isNull(); guardedResult.complete(); completableFuture.join(); - assertThat(registry.get("call").tag("class", getClass().getName() + "$AsyncTimedService").tag("method", "call") - .tag("extra", "tag").tag("exception", "none").timer().count()).isEqualTo(1); + assertThat(registry.get("call") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "call") + .tag("extra", "tag") + .tag("exception", "none") + .timer() + .count()).isEqualTo(1); } @Test @@ -151,14 +174,23 @@ void timeMethodWhenCompletedExceptionally() { GuardedResult guardedResult = new GuardedResult(); CompletableFuture completableFuture = service.call(guardedResult); - assertThat(registry.find("call").tag("class", getClass().getName() + "$AsyncTimedService").tag("method", "call") - .tag("extra", "tag").tag("exception", "NullPointerException").timer()).isNull(); + assertThat(registry.find("call") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "call") + .tag("extra", "tag") + .tag("exception", "NullPointerException") + .timer()).isNull(); guardedResult.complete(new NullPointerException()); catchThrowableOfType(completableFuture::join, CompletionException.class); - assertThat(registry.get("call").tag("class", getClass().getName() + "$AsyncTimedService").tag("method", "call") - .tag("extra", "tag").tag("exception", "NullPointerException").timer().count()).isEqualTo(1); + assertThat(registry.get("call") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "call") + .tag("extra", "tag") + .tag("exception", "NullPointerException") + .timer() + .count()).isEqualTo(1); } @Test @@ -173,14 +205,22 @@ void timeMethodWithLongTaskTimerWhenCompleted() { GuardedResult guardedResult = new GuardedResult(); CompletableFuture completableFuture = service.longCall(guardedResult); - assertThat(registry.find("longCall").tag("class", getClass().getName() + "$AsyncTimedService") - .tag("method", "longCall").tag("extra", "tag").longTaskTimer().activeTasks()).isEqualTo(1); + assertThat(registry.find("longCall") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "longCall") + .tag("extra", "tag") + .longTaskTimer() + .activeTasks()).isEqualTo(1); guardedResult.complete(); completableFuture.join(); - assertThat(registry.get("longCall").tag("class", getClass().getName() + "$AsyncTimedService") - .tag("method", "longCall").tag("extra", "tag").longTaskTimer().activeTasks()).isEqualTo(0); + assertThat(registry.get("longCall") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "longCall") + .tag("extra", "tag") + .longTaskTimer() + .activeTasks()).isEqualTo(0); } @Test @@ -195,14 +235,22 @@ void timeMethodWithLongTaskTimerWhenCompletedExceptionally() { GuardedResult guardedResult = new GuardedResult(); CompletableFuture completableFuture = service.longCall(guardedResult); - assertThat(registry.find("longCall").tag("class", getClass().getName() + "$AsyncTimedService") - .tag("method", "longCall").tag("extra", "tag").longTaskTimer().activeTasks()).isEqualTo(1); + assertThat(registry.find("longCall") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "longCall") + .tag("extra", "tag") + .longTaskTimer() + .activeTasks()).isEqualTo(1); guardedResult.complete(new NullPointerException()); catchThrowableOfType(completableFuture::join, CompletionException.class); - assertThat(registry.get("longCall").tag("class", getClass().getName() + "$AsyncTimedService") - .tag("method", "longCall").tag("extra", "tag").longTaskTimer().activeTasks()).isEqualTo(0); + assertThat(registry.get("longCall") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "longCall") + .tag("extra", "tag") + .longTaskTimer() + .activeTasks()).isEqualTo(0); } @Test @@ -219,9 +267,12 @@ void timeMethodFailureWhenCompletedExceptionally() { guardedResult.complete(); completableFuture.join(); - assertThatExceptionOfType(MeterNotFoundException.class) - .isThrownBy(() -> failingRegistry.get("call").tag("class", getClass().getName() + "$AsyncTimedService") - .tag("method", "call").tag("extra", "tag").tag("exception", "none").timer()); + assertThatExceptionOfType(MeterNotFoundException.class).isThrownBy(() -> failingRegistry.get("call") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "call") + .tag("extra", "tag") + .tag("exception", "none") + .timer()); } @Test @@ -239,8 +290,11 @@ void timeMethodFailureWithLongTaskTimerWhenCompleted() { completableFuture.join(); assertThatExceptionOfType(MeterNotFoundException.class).isThrownBy(() -> { - failingRegistry.get("longCall").tag("class", getClass().getName() + "$AsyncTimedService") - .tag("method", "longCall").tag("extra", "tag").longTaskTimer(); + failingRegistry.get("longCall") + .tag("class", getClass().getName() + "$AsyncTimedService") + .tag("method", "longCall") + .tag("extra", "tag") + .longTaskTimer(); }); } @@ -255,8 +309,12 @@ void timeClass() { service.call(); - assertThat(registry.get("call").tag("class", "io.micrometer.core.aop.TimedAspectTest$TimedClass") - .tag("method", "call").tag("extra", "tag").timer().count()).isEqualTo(1); + assertThat(registry.get("call") + .tag("class", "io.micrometer.core.aop.TimedAspectTest$TimedClass") + .tag("method", "call") + .tag("extra", "tag") + .timer() + .count()).isEqualTo(1); } @Test @@ -284,8 +342,12 @@ void timeClassImplementingInterface() { service.call(); - assertThat(registry.get("call").tag("class", "io.micrometer.core.aop.TimedAspectTest$TimedInterface") - .tag("method", "call").tag("extra", "tag").timer().count()).isEqualTo(1); + assertThat(registry.get("call") + .tag("class", "io.micrometer.core.aop.TimedAspectTest$TimedInterface") + .tag("method", "call") + .tag("extra", "tag") + .timer() + .count()).isEqualTo(1); } @Test @@ -300,8 +362,11 @@ void timeClassFailure() { service.call(); assertThatExceptionOfType(MeterNotFoundException.class).isThrownBy(() -> { - failingRegistry.get("call").tag("class", "io.micrometer.core.aop.TimedAspectTest$TimedClass") - .tag("method", "call").tag("extra", "tag").timer(); + failingRegistry.get("call") + .tag("class", "io.micrometer.core.aop.TimedAspectTest$TimedClass") + .tag("method", "call") + .tag("extra", "tag") + .timer(); }); } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/DistributionSummaryTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/DistributionSummaryTest.java index 74d8296c6e..ab836fe3d7 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/DistributionSummaryTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/DistributionSummaryTest.java @@ -29,8 +29,9 @@ class DistributionSummaryTest { void histogramsInCumulativeMode() { MockClock clock = new MockClock(); MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, clock); - DistributionSummary summary = DistributionSummary.builder("my.summary").serviceLevelObjectives(1.0) - .register(registry); + DistributionSummary summary = DistributionSummary.builder("my.summary") + .serviceLevelObjectives(1.0) + .register(registry); summary.record(1); @@ -55,8 +56,9 @@ public CountingMode mode() { } }, clock); - DistributionSummary summary = DistributionSummary.builder("my.summary").serviceLevelObjectives(1.0) - .register(registry); + DistributionSummary summary = DistributionSummary.builder("my.summary") + .serviceLevelObjectives(1.0) + .register(registry); summary.record(1); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterFilterTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterFilterTest.java index 0e058f2587..b7df02efef 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterFilterTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterFilterTest.java @@ -45,8 +45,8 @@ private static Condition tag(String tagKey) { private static Condition tag(String tagKey, @Nullable String tagValue) { return new Condition<>( - id -> stream(id.getTagsAsIterable().spliterator(), false).anyMatch( - t -> t.getKey().equals(tagKey) && (tagValue == null || t.getValue().equals(tagValue))), + id -> stream(id.getTagsAsIterable().spliterator(), false) + .anyMatch(t -> t.getKey().equals(tagKey) && (tagValue == null || t.getValue().equals(tagValue))), "Must have a tag with key '" + tagKey + "'"); } @@ -66,7 +66,7 @@ void commonTagsShouldNotOverrideTagValuesFromMeterId() { Meter.Id id = new Meter.Id("name", Tags.of("k1", "m1", "k2", "m2", "k3", "m3"), null, null, Meter.Type.COUNTER); Meter.Id filteredId = filter.map(id); assertThat(filteredId.getTags()) - .containsExactlyElementsOf(Tags.of("k0", "c0", "k1", "m1", "k2", "m2", "k3", "m3")); + .containsExactlyElementsOf(Tags.of("k0", "c0", "k1", "m1", "k2", "m2", "k3", "m3")); } @Test @@ -197,7 +197,7 @@ void minExpectedOnSummary() { Meter.Id timer = new Meter.Id("name", Tags.empty(), null, null, Meter.Type.DISTRIBUTION_SUMMARY); assertThat(filter.configure(timer, DistributionStatisticConfig.DEFAULT)) - .satisfies(conf -> assertThat(conf.getMinimumExpectedValueAsDouble()).isEqualTo(100)); + .satisfies(conf -> assertThat(conf.getMinimumExpectedValueAsDouble()).isEqualTo(100)); } @Test @@ -206,7 +206,7 @@ void maxExpectedOnSummary() { Meter.Id timer = new Meter.Id("name", Tags.empty(), null, null, Meter.Type.DISTRIBUTION_SUMMARY); assertThat(filter.configure(timer, DistributionStatisticConfig.DEFAULT)) - .satisfies(conf -> assertThat(conf.getMaximumExpectedValueAsDouble()).isEqualTo(100)); + .satisfies(conf -> assertThat(conf.getMaximumExpectedValueAsDouble()).isEqualTo(100)); } @Test @@ -215,7 +215,7 @@ void minExpectedOnTimer() { Meter.Id timer = new Meter.Id("name", Tags.empty(), null, null, Meter.Type.TIMER); assertThat(filter.configure(timer, DistributionStatisticConfig.DEFAULT)) - .satisfies(conf -> assertThat(conf.getMinimumExpectedValueAsDouble()).isEqualTo(100)); + .satisfies(conf -> assertThat(conf.getMinimumExpectedValueAsDouble()).isEqualTo(100)); } @Test @@ -224,7 +224,7 @@ void maxExpectedOnTimer() { Meter.Id timer = new Meter.Id("name", Tags.empty(), null, null, Meter.Type.TIMER); assertThat(filter.configure(timer, DistributionStatisticConfig.DEFAULT)) - .satisfies(conf -> assertThat(conf.getMaximumExpectedValueAsDouble()).isEqualTo(100)); + .satisfies(conf -> assertThat(conf.getMaximumExpectedValueAsDouble()).isEqualTo(100)); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterRegistryTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterRegistryTest.java index 0aa586506f..b4d094ea66 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterRegistryTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterRegistryTest.java @@ -85,8 +85,11 @@ protected Timer newTimer(@Nonnull Meter.Id id, DistributionStatisticConfig histo registry.config().meterFilter(new MeterFilter() { @Override public DistributionStatisticConfig configure(Meter.Id mappedId, DistributionStatisticConfig config) { - return DistributionStatisticConfig.builder().percentiles(0.95).percentilesHistogram(true).build() - .merge(config); + return DistributionStatisticConfig.builder() + .percentiles(0.95) + .percentilesHistogram(true) + .build() + .merge(config); } }); @@ -197,9 +200,9 @@ void gaugeRegistersGaugeOnceAndSubsequentGaugeCallsWillNotRegister() { void shouldNotLetRegisteringMetersTwice() { registry.counter("my.dupe.meter"); assertThatThrownBy(() -> registry.timer("my.dupe.meter")).isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "There is already a registered meter of a different type (CumulativeCounter vs. Timer) with the same name: my.dupe.meter") - .hasNoCause(); + .hasMessage( + "There is already a registered meter of a different type (CumulativeCounter vs. Timer) with the same name: my.dupe.meter") + .hasNoCause(); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterTest.java index 4a73b789f1..4404b0940f 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/MeterTest.java @@ -30,7 +30,7 @@ class MeterTest { TimeGauge gauge = TimeGauge.builder("time.gauge", null, TimeUnit.MILLISECONDS, o -> 1.0) - .register(new SimpleMeterRegistry()); + .register(new SimpleMeterRegistry()); @Test void matchWhenTimeGaugeShouldUseFunctionForTimeGauge() { diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/MissingHdrHistogramTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/MissingHdrHistogramTest.java index 46df2232a0..8ace7482ba 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/MissingHdrHistogramTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/MissingHdrHistogramTest.java @@ -41,7 +41,7 @@ void doesNotThrowAnyExceptionWhenPercentilesAreNotUsed() { @Test void throwsClassNotFoundExceptionWhenPercentilesAreUsed() { assertThatThrownBy(() -> Timer.builder("my.timer").publishPercentiles(0.5d, 0.9d).register(registry)) - .hasCauseExactlyInstanceOf(ClassNotFoundException.class); + .hasCauseExactlyInstanceOf(ClassNotFoundException.class); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/MultiGaugeTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/MultiGaugeTest.java index 9e2658a9f5..d080c217d2 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/MultiGaugeTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/MultiGaugeTest.java @@ -49,12 +49,12 @@ void multiGauge() { colorGauges.register(Stream.of(RED, GREEN).map(c -> c.toRow(1.0)).collect(toList())); assertThat(registry.get("colors").gauges().stream().map(g -> g.getId().getTag("color"))) - .containsExactlyInAnyOrder("red", "green"); + .containsExactlyInAnyOrder("red", "green"); colorGauges.register(Stream.of(RED, BLUE).map(c -> c.toRow(1.0)).collect(toList())); assertThat(registry.get("colors").gauges().stream().map(g -> g.getId().getTag("color"))) - .containsExactlyInAnyOrder("red", "blue"); + .containsExactlyInAnyOrder("red", "blue"); } /** @@ -117,26 +117,30 @@ private void testOverwrite(String mappedMeterName) { MultiGauge gauge = MultiGauge.builder(meterName).register(registry); - List> rows = map.entrySet().stream() - .map(row -> Row.of(Tags.of(testTagKey, row.getKey()), row.getValue())).collect(Collectors.toList()); + List> rows = map.entrySet() + .stream() + .map(row -> Row.of(Tags.of(testTagKey, row.getKey()), row.getValue())) + .collect(Collectors.toList()); gauge.register(rows, true); assertThat(registry.getMeters()).hasSize(2); assertThat(registry.get(mappedMeterName).tag(testTagKey, testKey1).gauge().value()) - .isEqualTo(testValue1.intValue()); + .isEqualTo(testValue1.intValue()); assertThat(registry.get(mappedMeterName).tag(testTagKey, testKey2).gauge().value()) - .isEqualTo(testValue2.intValue()); + .isEqualTo(testValue2.intValue()); testValue1 = new AtomicInteger(100); map.put(testKey1, testValue1); map.remove(testKey2); - rows = map.entrySet().stream().map(t -> Row.of(Tags.of(testTagKey, t.getKey()), t.getValue())) - .collect(Collectors.toList()); + rows = map.entrySet() + .stream() + .map(t -> Row.of(Tags.of(testTagKey, t.getKey()), t.getValue())) + .collect(Collectors.toList()); gauge.register(rows, true); assertThat(registry.getMeters()).hasSize(1); assertThat(registry.get(mappedMeterName).tag(testTagKey, testKey1).gauge().value()) - .isEqualTo(testValue1.intValue()); + .isEqualTo(testValue1.intValue()); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/TimeGaugeTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/TimeGaugeTest.java index 4f94d0b1c8..8c8fdf4676 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/TimeGaugeTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/TimeGaugeTest.java @@ -30,8 +30,8 @@ void hasBaseTimeUnit() { MeterRegistry registry = new SimpleMeterRegistry(); AtomicLong n = new AtomicLong(); - TimeGauge g = registry.more().timeGauge("my.time.gauge", Tags.empty(), n, TimeUnit.SECONDS, - AtomicLong::doubleValue); + TimeGauge g = registry.more() + .timeGauge("my.time.gauge", Tags.empty(), n, TimeUnit.SECONDS, AtomicLong::doubleValue); assertThat(g.getId().getBaseUnit()).isEqualTo("seconds"); } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/cache/EhCache2MetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/cache/EhCache2MetricsTest.java index 6ba7d8e47b..f43f54cc70 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/cache/EhCache2MetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/cache/EhCache2MetricsTest.java @@ -98,7 +98,7 @@ void reportMetrics() { // rollback transaction metrics String xaRollbacks = "cache.xa.rollbacks"; FunctionCounter exceptionRollback = fetch(registry, xaRollbacks, Tags.of("result", "exception")) - .functionCounter(); + .functionCounter(); assertThat(exceptionRollback.count()).isEqualTo(stats.xaRollbackExceptionCount()); FunctionCounter successRollback = fetch(registry, xaRollbacks, Tags.of("result", "success")).functionCounter(); @@ -107,11 +107,11 @@ void reportMetrics() { // recovery transaction metrics String xaRecoveries = "cache.xa.recoveries"; FunctionCounter nothingRecovered = fetch(registry, xaRecoveries, Tags.of("result", "nothing")) - .functionCounter(); + .functionCounter(); assertThat(nothingRecovered.count()).isEqualTo(stats.xaRecoveryNothingCount()); FunctionCounter successRecoveries = fetch(registry, xaRecoveries, Tags.of("result", "success")) - .functionCounter(); + .functionCounter(); assertThat(successRecoveries.count()).isEqualTo(stats.xaRecoveryRecoveredCount()); } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetricsTest.java index 1442cc497e..2576c4518f 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetricsTest.java @@ -153,7 +153,7 @@ void returnPutCount() { @Test void nonIMapCacheFails() { assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> new HazelcastCacheMetrics(new HashMap(), Tags.empty())); + .isThrownBy(() -> new HazelcastCacheMetrics(new HashMap(), Tags.empty())); } @BeforeAll diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/commonspool2/CommonsObjectPool2MetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/commonspool2/CommonsObjectPool2MetricsTest.java index 0df9cad165..5f8bb62284 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/commonspool2/CommonsObjectPool2MetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/commonspool2/CommonsObjectPool2MetricsTest.java @@ -61,13 +61,16 @@ void verifyMetricsWithExpectedTags() { registry.get("commons.pool2.num.idle").tags(tags).gauge(); registry.get("commons.pool2.num.waiters").tags(tags).gauge(); - Arrays.asList("commons.pool2.created", "commons.pool2.borrowed", "commons.pool2.returned", - "commons.pool2.destroyed", "commons.pool2.destroyed.by.evictor", - "commons.pool2.destroyed.by.borrow.validation") - .forEach(name -> registry.get(name).tags(tags).functionCounter()); - - Arrays.asList("commons.pool2.max.borrow.wait", "commons.pool2.mean.active", "commons.pool2.mean.idle", - "commons.pool2.mean.borrow.wait").forEach(name -> registry.get(name).tags(tags).timeGauge()); + Arrays + .asList("commons.pool2.created", "commons.pool2.borrowed", "commons.pool2.returned", + "commons.pool2.destroyed", "commons.pool2.destroyed.by.evictor", + "commons.pool2.destroyed.by.borrow.validation") + .forEach(name -> registry.get(name).tags(tags).functionCounter()); + + Arrays + .asList("commons.pool2.max.borrow.wait", "commons.pool2.mean.active", "commons.pool2.mean.idle", + "commons.pool2.mean.borrow.wait") + .forEach(name -> registry.get(name).tags(tags).timeGauge()); } } @@ -78,15 +81,18 @@ void verifyGenericKeyedObjectPoolMetricsWithExpectedTags() { commonsObjectPool2Metrics.bindTo(registry); Arrays.asList("commons.pool2.num.idle", "commons.pool2.num.waiters") - .forEach(name -> registry.get(name).tags(tagsToMatch).gauge()); - - Arrays.asList("commons.pool2.created", "commons.pool2.borrowed", "commons.pool2.returned", - "commons.pool2.destroyed", "commons.pool2.destroyed.by.evictor", - "commons.pool2.destroyed.by.borrow.validation") - .forEach(name -> registry.get(name).tags(tagsToMatch).functionCounter()); - - Arrays.asList("commons.pool2.max.borrow.wait", "commons.pool2.mean.active", "commons.pool2.mean.idle", - "commons.pool2.mean.borrow.wait").forEach(name -> registry.get(name).tags(tagsToMatch).timeGauge()); + .forEach(name -> registry.get(name).tags(tagsToMatch).gauge()); + + Arrays + .asList("commons.pool2.created", "commons.pool2.borrowed", "commons.pool2.returned", + "commons.pool2.destroyed", "commons.pool2.destroyed.by.evictor", + "commons.pool2.destroyed.by.borrow.validation") + .forEach(name -> registry.get(name).tags(tagsToMatch).functionCounter()); + + Arrays + .asList("commons.pool2.max.borrow.wait", "commons.pool2.mean.active", "commons.pool2.mean.idle", + "commons.pool2.mean.borrow.wait") + .forEach(name -> registry.get(name).tags(tagsToMatch).timeGauge()); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/db/MetricsDSLContextTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/db/MetricsDSLContextTest.java index ad306dbe50..ac58812017 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/db/MetricsDSLContextTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/db/MetricsDSLContextTest.java @@ -60,7 +60,7 @@ void timeFluentSelectStatement() throws SQLException { assertThat( meterRegistry.get("jooq.query").tag("name", "selectAllAuthors").tag("type", "read").timer().count()) - .isEqualTo(1); + .isEqualTo(1); } } @@ -76,7 +76,7 @@ void timeParsedSelectStatement() throws SQLException { assertThat( meterRegistry.get("jooq.query").tag("name", "selectAllAuthors").tag("type", "read").timer().count()) - .isEqualTo(1); + .isEqualTo(1); } } @@ -91,9 +91,13 @@ void timeFaultySelectStatement() throws SQLException { catch (DataAccessException ignored) { } - assertThat(meterRegistry.get("jooq.query").tag("name", "selectAllAuthors").tag("type", "read") - .tag("exception", "c42 syntax error or access rule violation").tag("exception.subclass", "none").timer() - .count()).isEqualTo(1); + assertThat(meterRegistry.get("jooq.query") + .tag("name", "selectAllAuthors") + .tag("type", "read") + .tag("exception", "c42 syntax error or access rule violation") + .tag("exception.subclass", "none") + .timer() + .count()).isEqualTo(1); } @Test @@ -134,8 +138,10 @@ void timingBatchQueriesNotSupported() throws SQLException { try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:fluentSelect")) { MetricsDSLContext jooq = createDatabase(conn); - jooq.tag("name", "batch").batch(jooq.insertInto(table("author")).values("3", "jon", "schneider"), - jooq.insertInto(table("author")).values("4", "jon", "schneider")).execute(); + jooq.tag("name", "batch") + .batch(jooq.insertInto(table("author")).values("3", "jon", "schneider"), + jooq.insertInto(table("author")).values("4", "jon", "schneider")) + .execute(); assertThat(meterRegistry.find("jooq.query").timer()).isNull(); } @@ -151,8 +157,9 @@ void timeTwoStatementsCreatedBeforeEitherIsExecuted() throws SQLException { MetricsDSLContext jooq = createDatabase(conn); SelectJoinStep select1 = jooq.tag("name", "selectAllAuthors").select(asterisk()).from("author"); - SelectJoinStep> select2 = jooq.tag("name", "selectAllAuthors2").select(field("first_name")) - .from("author"); + SelectJoinStep> select2 = jooq.tag("name", "selectAllAuthors2") + .select(field("first_name")) + .from("author"); select1.fetch(); select2.fetch(); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetricsIntegrationTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetricsIntegrationTest.java index abf4d8c7d3..023f014ee3 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetricsIntegrationTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetricsIntegrationTest.java @@ -107,7 +107,7 @@ void countersAreNotZero() throws Exception { for (String name : COUNTERS) { assertThat(get(name).functionCounter().count()).withFailMessage("Counter " + name + " is zero.") - .isGreaterThan(0); + .isGreaterThan(0); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpClientInterceptorTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpClientInterceptorTest.java index 8fc9cddfb2..b6a35671ce 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpClientInterceptorTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpClientInterceptorTest.java @@ -81,8 +81,11 @@ void uriIsReadFromHttpHeader(@WiremockResolver.Wiremock WireMockServer server) t HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); - assertThat(registry.get("httpcomponents.httpclient.request").tag("uri", "/some/pattern").tag("status", "200") - .timer().count()).isEqualTo(1); + assertThat(registry.get("httpcomponents.httpclient.request") + .tag("uri", "/some/pattern") + .tag("status", "200") + .timer() + .count()).isEqualTo(1); client.close(); } @@ -94,8 +97,10 @@ private CloseableHttpAsyncClient asyncClient() { } private CloseableHttpAsyncClient asyncClient(MicrometerHttpClientInterceptor interceptor) { - return HttpAsyncClients.custom().addInterceptorFirst(interceptor.getRequestInterceptor()) - .addInterceptorLast(interceptor.getResponseInterceptor()).build(); + return HttpAsyncClients.custom() + .addInterceptorFirst(interceptor.getRequestInterceptor()) + .addInterceptorLast(interceptor.getResponseInterceptor()) + .build(); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpRequestExecutorTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpRequestExecutorTest.java index b23d847b70..76edbd31ba 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpRequestExecutorTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpRequestExecutorTest.java @@ -89,11 +89,11 @@ void httpStatusCodeIsTagged(@WiremockResolver.Wiremock WireMockServer server) th EntityUtils.consume(client.execute(new HttpGet(server.baseUrl() + "/notfound")).getEntity()); EntityUtils.consume(client.execute(new HttpGet(server.baseUrl() + "/error")).getEntity()); assertThat(registry.get(EXPECTED_METER_NAME).tags("method", "GET", "status", "200").timer().count()) - .isEqualTo(2L); + .isEqualTo(2L); assertThat(registry.get(EXPECTED_METER_NAME).tags("method", "GET", "status", "404").timer().count()) - .isEqualTo(1L); + .isEqualTo(1L); assertThat(registry.get(EXPECTED_METER_NAME).tags("method", "GET", "status", "500").timer().count()) - .isEqualTo(1L); + .isEqualTo(1L); } @Test @@ -123,8 +123,13 @@ void routeNotTaggedByDefault(@WiremockResolver.Wiremock WireMockServer server) t server.stubFor(any(anyUrl())); HttpClient client = client(executor(false)); EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity()); - List tagKeys = registry.get(EXPECTED_METER_NAME).timer().getId().getTags().stream().map(Tag::getKey) - .collect(Collectors.toList()); + List tagKeys = registry.get(EXPECTED_METER_NAME) + .timer() + .getId() + .getTags() + .stream() + .map(Tag::getKey) + .collect(Collectors.toList()); assertThat(tagKeys).doesNotContain("target.scheme", "target.host", "target.port"); assertThat(tagKeys).contains("status", "method"); } @@ -134,15 +139,21 @@ void routeTaggedIfEnabled(@WiremockResolver.Wiremock WireMockServer server) thro server.stubFor(any(anyUrl())); HttpClient client = client(executor(true)); EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity()); - List tagKeys = registry.get(EXPECTED_METER_NAME).timer().getId().getTags().stream().map(Tag::getKey) - .collect(Collectors.toList()); + List tagKeys = registry.get(EXPECTED_METER_NAME) + .timer() + .getId() + .getTags() + .stream() + .map(Tag::getKey) + .collect(Collectors.toList()); assertThat(tagKeys).contains("target.scheme", "target.host", "target.port"); } @Test void waitForContinueGetsPassedToSuper() { MicrometerHttpRequestExecutor requestExecutor = MicrometerHttpRequestExecutor.builder(registry) - .waitForContinue(1000).build(); + .waitForContinue(1000) + .build(); assertThat(requestExecutor).hasFieldOrPropertyWithValue("waitForContinue", 1000); } @@ -150,7 +161,8 @@ void waitForContinueGetsPassedToSuper() { void uriMapperWorksAsExpected(@WiremockResolver.Wiremock WireMockServer server) throws IOException { server.stubFor(any(anyUrl())); MicrometerHttpRequestExecutor executor = MicrometerHttpRequestExecutor.builder(registry) - .uriMapper(request -> request.getRequestLine().getUri()).build(); + .uriMapper(request -> request.getRequestLine().getUri()) + .build(); HttpClient client = client(executor); EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity()); EntityUtils.consume(client.execute(new HttpGet(server.baseUrl() + "/foo")).getEntity()); @@ -165,11 +177,15 @@ void uriMapperWorksAsExpected(@WiremockResolver.Wiremock WireMockServer server) void additionalTagsAreExposed(@WiremockResolver.Wiremock WireMockServer server) throws IOException { server.stubFor(any(anyUrl())); MicrometerHttpRequestExecutor executor = MicrometerHttpRequestExecutor.builder(registry) - .tags(Tags.of("foo", "bar", "some.key", "value")).exportTagsForRoute(true).build(); + .tags(Tags.of("foo", "bar", "some.key", "value")) + .exportTagsForRoute(true) + .build(); HttpClient client = client(executor); EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity()); - assertThat(registry.get(EXPECTED_METER_NAME).tags("foo", "bar", "some.key", "value", "target.host", "localhost") - .timer().count()).isEqualTo(1L); + assertThat(registry.get(EXPECTED_METER_NAME) + .tags("foo", "bar", "some.key", "value", "target.host", "localhost") + .timer() + .count()).isEqualTo(1L); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/PoolingHttpClientConnectionManagerMetricsBinderTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/PoolingHttpClientConnectionManagerMetricsBinderTest.java index d33e7d54a4..2510687295 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/PoolingHttpClientConnectionManagerMetricsBinderTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/httpcomponents/PoolingHttpClientConnectionManagerMetricsBinderTest.java @@ -56,7 +56,7 @@ void totalMax() { when(poolStats.getMax()).thenReturn(13); when(connPoolControl.getTotalStats()).thenReturn(poolStats); assertThat(registry.get("httpcomponents.httpclient.pool.total.max").tags("httpclient", "test").gauge().value()) - .isEqualTo(13.0); + .isEqualTo(13.0); } @Test @@ -65,7 +65,9 @@ void totalAvailable() { when(poolStats.getAvailable()).thenReturn(17); when(connPoolControl.getTotalStats()).thenReturn(poolStats); assertThat(registry.get("httpcomponents.httpclient.pool.total.connections") - .tags("httpclient", "test", "state", "available").gauge().value()).isEqualTo(17.0); + .tags("httpclient", "test", "state", "available") + .gauge() + .value()).isEqualTo(17.0); } @Test @@ -74,7 +76,9 @@ void totalLeased() { when(poolStats.getLeased()).thenReturn(23); when(connPoolControl.getTotalStats()).thenReturn(poolStats); assertThat(registry.get("httpcomponents.httpclient.pool.total.connections") - .tags("httpclient", "test", "state", "leased").gauge().value()).isEqualTo(23.0); + .tags("httpclient", "test", "state", "leased") + .gauge() + .value()).isEqualTo(23.0); } @Test @@ -84,14 +88,16 @@ void totalPending() { when(connPoolControl.getTotalStats()).thenReturn(poolStats); assertThat( registry.get("httpcomponents.httpclient.pool.total.pending").tags("httpclient", "test").gauge().value()) - .isEqualTo(37.0); + .isEqualTo(37.0); } @Test void routeMaxDefault() { when(connPoolControl.getDefaultMaxPerRoute()).thenReturn(7); - assertThat(registry.get("httpcomponents.httpclient.pool.route.max.default").tags("httpclient", "test").gauge() - .value()).isEqualTo(7.0); + assertThat(registry.get("httpcomponents.httpclient.pool.route.max.default") + .tags("httpclient", "test") + .gauge() + .value()).isEqualTo(7.0); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherCommandTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherCommandTest.java index 06f923c78d..5d7d579bb8 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherCommandTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherCommandTest.java @@ -39,10 +39,12 @@ class MicrometerMetricsPublisherCommandTest { @BeforeEach void init() { Hystrix.reset(); - propertiesSetter = HystrixCommandProperties.Setter().withCircuitBreakerEnabled(true) - .withCircuitBreakerRequestVolumeThreshold(20).withCircuitBreakerSleepWindowInMilliseconds(10_000) - .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD) - .withExecutionTimeoutInMilliseconds(100); + propertiesSetter = HystrixCommandProperties.Setter() + .withCircuitBreakerEnabled(true) + .withCircuitBreakerRequestVolumeThreshold(20) + .withCircuitBreakerSleepWindowInMilliseconds(10_000) + .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD) + .withExecutionTimeoutInMilliseconds(100); } @AfterEach @@ -55,7 +57,7 @@ void cumulativeCounters() throws Exception { HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher(); HystrixPlugins.reset(); HystrixPlugins.getInstance() - .registerMetricsPublisher(new MicrometerMetricsPublisher(registry, metricsPublisher)); + .registerMetricsPublisher(new MicrometerMetricsPublisher(registry, metricsPublisher)); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("MicrometerCOMMAND-A"); for (int i = 0; i < 3; i++) { @@ -94,7 +96,7 @@ void openCircuit() { HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher(); HystrixPlugins.reset(); HystrixPlugins.getInstance() - .registerMetricsPublisher(new MicrometerMetricsPublisher(registry, metricsPublisher)); + .registerMetricsPublisher(new MicrometerMetricsPublisher(registry, metricsPublisher)); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("MicrometerCOMMAND-B"); propertiesSetter.withCircuitBreakerForceOpen(true); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherThreadPoolTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherThreadPoolTest.java index 0a2ff741d9..14c6c72f0f 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherThreadPoolTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/hystrix/MicrometerMetricsPublisherThreadPoolTest.java @@ -44,7 +44,7 @@ class MicrometerMetricsPublisherThreadPoolTest { private MeterRegistry registry = new SimpleMeterRegistry(); private HystrixCommandProperties.Setter propertiesSetter = HystrixCommandProperties.Setter() - .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); + .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); private final HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey(NAME_MICROMETER_GROUP); @@ -66,17 +66,18 @@ void testMetricIds() { HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher(); HystrixPlugins.reset(); HystrixPlugins.getInstance() - .registerMetricsPublisher(new MicrometerMetricsPublisher(registry, metricsPublisher)); + .registerMetricsPublisher(new MicrometerMetricsPublisher(registry, metricsPublisher)); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("MicrometerCOMMAND-A"); new SampleCommand(key).execute(); final Tags tags = Tags.of("key", NAME_MICROMETER_GROUP); - final Set actualMeterIds = registry.getMeters().stream() - .map(meter -> new MeterId(meter.getId().getName(), meter.getId().getType(), - Tags.of(meter.getId().getTags()))) - .collect(Collectors.toSet()); + final Set actualMeterIds = registry.getMeters() + .stream() + .map(meter -> new MeterId(meter.getId().getName(), meter.getId().getType(), + Tags.of(meter.getId().getTags()))) + .collect(Collectors.toSet()); final Set expectedMeterIds = new HashSet<>(Arrays.asList( new MeterId(metricName("threads.active.current.count"), Type.GAUGE, tags), diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/DefaultJerseyTagsProviderTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/DefaultJerseyTagsProviderTest.java index 3bc842be0b..5b6a4349eb 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/DefaultJerseyTagsProviderTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/DefaultJerseyTagsProviderTest.java @@ -51,47 +51,47 @@ class DefaultJerseyTagsProviderTest { @Test void testRootPath() { assertThat(tagsProvider.httpRequestTags(event(200, null, "/", (String[]) null))) - .containsExactlyInAnyOrder(tagsFrom("root", 200, null, "SUCCESS")); + .containsExactlyInAnyOrder(tagsFrom("root", 200, null, "SUCCESS")); } @Test void templatedPathsAreReturned() { assertThat(tagsProvider.httpRequestTags(event(200, null, "/", "/", "/hello/{name}"))) - .containsExactlyInAnyOrder(tagsFrom("/hello/{name}", 200, null, "SUCCESS")); + .containsExactlyInAnyOrder(tagsFrom("/hello/{name}", 200, null, "SUCCESS")); } @Test void applicationPathIsPresent() { assertThat(tagsProvider.httpRequestTags(event(200, null, "/app", "/", "/hello"))) - .containsExactlyInAnyOrder(tagsFrom("/app/hello", 200, null, "SUCCESS")); + .containsExactlyInAnyOrder(tagsFrom("/app/hello", 200, null, "SUCCESS")); } @Test void notFoundsAreShunted() { assertThat(tagsProvider.httpRequestTags(event(404, null, "/app", "/", "/not-found"))) - .containsExactlyInAnyOrder(tagsFrom("NOT_FOUND", 404, null, "CLIENT_ERROR")); + .containsExactlyInAnyOrder(tagsFrom("NOT_FOUND", 404, null, "CLIENT_ERROR")); } @Test void redirectsAreShunted() { assertThat(tagsProvider.httpRequestTags(event(301, null, "/app", "/", "/redirect301"))) - .containsExactlyInAnyOrder(tagsFrom("REDIRECTION", 301, null, "REDIRECTION")); + .containsExactlyInAnyOrder(tagsFrom("REDIRECTION", 301, null, "REDIRECTION")); assertThat(tagsProvider.httpRequestTags(event(302, null, "/app", "/", "/redirect302"))) - .containsExactlyInAnyOrder(tagsFrom("REDIRECTION", 302, null, "REDIRECTION")); + .containsExactlyInAnyOrder(tagsFrom("REDIRECTION", 302, null, "REDIRECTION")); assertThat(tagsProvider.httpRequestTags(event(399, null, "/app", "/", "/redirect399"))) - .containsExactlyInAnyOrder(tagsFrom("REDIRECTION", 399, null, "REDIRECTION")); + .containsExactlyInAnyOrder(tagsFrom("REDIRECTION", 399, null, "REDIRECTION")); } @Test @SuppressWarnings("serial") void exceptionsAreMappedCorrectly() { assertThat(tagsProvider.httpRequestTags(event(500, new IllegalArgumentException(), "/app", (String[]) null))) - .containsExactlyInAnyOrder(tagsFrom("/app", 500, "IllegalArgumentException", "SERVER_ERROR")); + .containsExactlyInAnyOrder(tagsFrom("/app", 500, "IllegalArgumentException", "SERVER_ERROR")); assertThat(tagsProvider.httpRequestTags( event(500, new IllegalArgumentException(new NullPointerException()), "/app", (String[]) null))) - .containsExactlyInAnyOrder(tagsFrom("/app", 500, "NullPointerException", "SERVER_ERROR")); + .containsExactlyInAnyOrder(tagsFrom("/app", 500, "NullPointerException", "SERVER_ERROR")); assertThat(tagsProvider.httpRequestTags(event(406, new NotAcceptableException(), "/app", (String[]) null))) - .containsExactlyInAnyOrder(tagsFrom("/app", 406, "NotAcceptableException", "CLIENT_ERROR")); + .containsExactlyInAnyOrder(tagsFrom("/app", 406, "NotAcceptableException", "CLIENT_ERROR")); assertThat(tagsProvider.httpRequestTags(event(500, new Exception("anonymous") { }, "/app", (String[]) null))).containsExactlyInAnyOrder(tagsFrom("/app", 500, "io.micrometer.core.instrument.binder.jersey.server.DefaultJerseyTagsProviderTest$1", "SERVER_ERROR")); @@ -100,7 +100,7 @@ void exceptionsAreMappedCorrectly() { @Test void longRequestTags() { assertThat(tagsProvider.httpLongRequestTags(event(0, null, "/app", (String[]) null))) - .containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/app")); + .containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/app")); } private static RequestEvent event(Integer status, Exception exception, String baseUri, @@ -119,7 +119,7 @@ private static RequestEvent event(Integer status, Exception exception, String ba ExtendedUriInfo extendedUriInfo = mock(ExtendedUriInfo.class); when(extendedUriInfo.getBaseUri()) - .thenReturn(URI.create("http://localhost:8080" + (baseUri == null ? "/" : baseUri))); + .thenReturn(URI.create("http://localhost:8080" + (baseUri == null ? "/" : baseUri))); List uriTemplates = uriTemplateStrings == null ? Collections.emptyList() : Arrays.stream(uriTemplateStrings).map(uri -> new UriTemplate(uri)).collect(Collectors.toList()); // UriTemplate are returned in reverse order diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListenerTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListenerTest.java index e18d9f8e86..44243c6e8c 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListenerTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListenerTest.java @@ -72,16 +72,18 @@ void resourcesAreTimed() { target("sub-resource/sub-hello/peter").request().get(); assertThat(registry.get(METRIC_NAME).tags(tagsFrom("root", "200", "SUCCESS", null)).timer().count()) - .isEqualTo(1); + .isEqualTo(1); assertThat(registry.get(METRIC_NAME).tags(tagsFrom("/hello", "200", "SUCCESS", null)).timer().count()) - .isEqualTo(2); + .isEqualTo(2); assertThat(registry.get(METRIC_NAME).tags(tagsFrom("/hello/{name}", "200", "SUCCESS", null)).timer().count()) - .isEqualTo(1); + .isEqualTo(1); - assertThat(registry.get(METRIC_NAME).tags(tagsFrom("/sub-resource/sub-hello/{name}", "200", "SUCCESS", null)) - .timer().count()).isEqualTo(1); + assertThat(registry.get(METRIC_NAME) + .tags(tagsFrom("/sub-resource/sub-hello/{name}", "200", "SUCCESS", null)) + .timer() + .count()).isEqualTo(1); // assert we are not auto-timing long task @Timed assertThat(registry.getMeters()).hasSize(4); @@ -96,7 +98,7 @@ void notFoundIsAccumulatedUnderSameUri() { } assertThat(registry.get(METRIC_NAME).tags(tagsFrom("NOT_FOUND", "404", "CLIENT_ERROR", null)).timer().count()) - .isEqualTo(1); + .isEqualTo(1); } @Test @@ -107,8 +109,10 @@ void notFoundIsReportedWithUriOfMatchedResource() { catch (NotFoundException ignored) { } - assertThat(registry.get(METRIC_NAME).tags(tagsFrom("/throws-not-found-exception", "404", "CLIENT_ERROR", null)) - .timer().count()).isEqualTo(1); + assertThat(registry.get(METRIC_NAME) + .tags(tagsFrom("/throws-not-found-exception", "404", "CLIENT_ERROR", null)) + .timer() + .count()).isEqualTo(1); } @Test @@ -116,11 +120,15 @@ void redirectsAreReportedWithUriOfMatchedResource() { target("redirect/302").request().get(); target("redirect/307").request().get(); - assertThat(registry.get(METRIC_NAME).tags(tagsFrom("/redirect/{status}", "302", "REDIRECTION", null)).timer() - .count()).isEqualTo(1); + assertThat(registry.get(METRIC_NAME) + .tags(tagsFrom("/redirect/{status}", "302", "REDIRECTION", null)) + .timer() + .count()).isEqualTo(1); - assertThat(registry.get(METRIC_NAME).tags(tagsFrom("/redirect/{status}", "307", "REDIRECTION", null)).timer() - .count()).isEqualTo(1); + assertThat(registry.get(METRIC_NAME) + .tags(tagsFrom("/redirect/{status}", "307", "REDIRECTION", null)) + .timer() + .count()).isEqualTo(1); } @Test @@ -142,16 +150,19 @@ void exceptionsAreMappedCorrectly() { } assertThat(registry.get(METRIC_NAME) - .tags(tagsFrom("/throws-exception", "500", "SERVER_ERROR", "IllegalArgumentException")).timer().count()) - .isEqualTo(1); + .tags(tagsFrom("/throws-exception", "500", "SERVER_ERROR", "IllegalArgumentException")) + .timer() + .count()).isEqualTo(1); assertThat(registry.get(METRIC_NAME) - .tags(tagsFrom("/throws-webapplication-exception", "401", "CLIENT_ERROR", "NotAuthorizedException")) - .timer().count()).isEqualTo(1); + .tags(tagsFrom("/throws-webapplication-exception", "401", "CLIENT_ERROR", "NotAuthorizedException")) + .timer() + .count()).isEqualTo(1); assertThat(registry.get(METRIC_NAME) - .tags(tagsFrom("/throws-mappable-exception", "410", "CLIENT_ERROR", "ResourceGoneException")).timer() - .count()).isEqualTo(1); + .tags(tagsFrom("/throws-mappable-exception", "410", "CLIENT_ERROR", "ResourceGoneException")) + .timer() + .count()).isEqualTo(1); } private static Iterable tagsFrom(String uri, String status, String outcome, String exception) { diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListenerTimedTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListenerTimedTest.java index 5c20925b08..61027be9cc 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListenerTimedTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jersey/server/MetricsRequestEventListenerTimedTest.java @@ -111,8 +111,10 @@ void longTaskTimerSupported() throws InterruptedException, ExecutionException, T assertThat(registry.find(METRIC_NAME).tags(tagsFrom("/timed", 200)).timer()).isNull(); // the long running task is timed - assertThat(registry.get("long.task.in.request").tags(Tags.of("method", "GET", "uri", "/long-timed")) - .longTaskTimer().activeTasks()).isEqualTo(1); + assertThat(registry.get("long.task.in.request") + .tags(Tags.of("method", "GET", "uri", "/long-timed")) + .longTaskTimer() + .activeTasks()).isEqualTo(1); // finish the long running request longTaskRequestReleaseLatch.countDown(); @@ -135,8 +137,10 @@ void longTaskTimerOnlyOneMeter() throws InterruptedException, ExecutionException longTaskRequestStartedLatch.await(5, TimeUnit.SECONDS); // the long running task is timed - assertThat(registry.get("long.task.in.request").tags(Tags.of("method", "GET", "uri", "/just-long-timed")) - .longTaskTimer().activeTasks()).isEqualTo(1); + assertThat(registry.get("long.task.in.request") + .tags(Tags.of("method", "GET", "uri", "/just-long-timed")) + .longTaskTimer() + .activeTasks()).isEqualTo(1); // finish the long running request longTaskRequestReleaseLatch.countDown(); @@ -149,8 +153,8 @@ void longTaskTimerOnlyOneMeter() throws InterruptedException, ExecutionException @Test void unnamedLongTaskTimerIsNotSupported() { assertThatExceptionOfType(ProcessingException.class) - .isThrownBy(() -> target("long-timed-unnamed").request().get()) - .withCauseInstanceOf(IllegalArgumentException.class); + .isThrownBy(() -> target("long-timed-unnamed").request().get()) + .withCauseInstanceOf(IllegalArgumentException.class); } @Test @@ -158,8 +162,9 @@ void classLevelAnnotationIsInherited() { target("/class/inherited").request().get(); assertThat(registry.get(METRIC_NAME) - .tags(Tags.concat(tagsFrom("/class/inherited", 200), Tags.of("on", "class"))).timer().count()) - .isEqualTo(1); + .tags(Tags.concat(tagsFrom("/class/inherited", 200), Tags.of("on", "class"))) + .timer() + .count()).isEqualTo(1); } @Test @@ -167,8 +172,9 @@ void methodLevelAnnotationOverridesClassLevel() { target("/class/on-method").request().get(); assertThat(registry.get(METRIC_NAME) - .tags(Tags.concat(tagsFrom("/class/on-method", 200), Tags.of("on", "method"))).timer().count()) - .isEqualTo(1); + .tags(Tags.concat(tagsFrom("/class/on-method", 200), Tags.of("on", "method"))) + .timer() + .count()).isEqualTo(1); // class level annotation is not picked up assertThat(registry.getMeters()).hasSize(1); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettyClientMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettyClientMetricsTest.java index 9c802bf353..7fef170b10 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettyClientMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettyClientMetricsTest.java @@ -72,7 +72,7 @@ public void handle(String target, org.eclipse.jetty.server.Request baseRequest, httpClient.setFollowRedirects(false); httpClient.getRequestListeners() - .add(JettyClientMetrics.builder(registry, result -> result.getRequest().getURI().getPath()).build()); + .add(JettyClientMetrics.builder(registry, result -> result.getRequest().getURI().getPath()).build()); httpClient.addLifeCycleListener(new LifeCycle.Listener() { @Override @@ -100,8 +100,13 @@ void successfulHttpPostRequest() throws Exception { httpClient.stop(); assertTrue(singleRequestLatch.await(10, SECONDS)); - assertThat(registry.get("jetty.client.requests").tag("outcome", "SUCCESS").tag("status", "200") - .tag("uri", "/ok").tag("host", "localhost").timer().count()).isEqualTo(1); + assertThat(registry.get("jetty.client.requests") + .tag("outcome", "SUCCESS") + .tag("status", "200") + .tag("uri", "/ok") + .tag("host", "localhost") + .timer() + .count()).isEqualTo(1); } @Test @@ -110,8 +115,12 @@ void successfulHttpGetRequest() throws Exception { httpClient.stop(); assertTrue(singleRequestLatch.await(10, SECONDS)); - assertThat(registry.get("jetty.client.requests").tag("outcome", "SUCCESS").tag("status", "200") - .tag("uri", "/ok").timer().count()).isEqualTo(1); + assertThat(registry.get("jetty.client.requests") + .tag("outcome", "SUCCESS") + .tag("status", "200") + .tag("uri", "/ok") + .timer() + .count()).isEqualTo(1); DistributionSummary requestSizeSummary = registry.get("jetty.client.request.size").summary(); assertThat(requestSizeSummary.count()).isEqualTo(1); assertThat(requestSizeSummary.totalAmount()).isEqualTo(0); @@ -125,8 +134,13 @@ void requestSize() throws Exception { httpClient.stop(); assertTrue(singleRequestLatch.await(10, SECONDS)); - assertThat(registry.get("jetty.client.request.size").tag("outcome", "SUCCESS").tag("status", "200") - .tag("uri", "/ok").tag("host", "localhost").summary().totalAmount()).isEqualTo("123456".length()); + assertThat(registry.get("jetty.client.request.size") + .tag("outcome", "SUCCESS") + .tag("status", "200") + .tag("uri", "/ok") + .tag("host", "localhost") + .summary() + .totalAmount()).isEqualTo("123456".length()); } @Test @@ -137,8 +151,13 @@ void serverError() throws Exception { httpClient.stop(); assertTrue(singleRequestLatch.await(10, SECONDS)); - assertThat(registry.get("jetty.client.requests").tag("outcome", "SERVER_ERROR").tag("status", "500") - .tag("uri", "/error").tag("host", "localhost").timer().count()).isEqualTo(1); + assertThat(registry.get("jetty.client.requests") + .tag("outcome", "SERVER_ERROR") + .tag("status", "500") + .tag("uri", "/error") + .tag("host", "localhost") + .timer() + .count()).isEqualTo(1); } @Test @@ -149,8 +168,13 @@ void handlerWrapperUncheckedException() throws Exception { httpClient.stop(); assertTrue(singleRequestLatch.await(10, SECONDS)); - assertThat(registry.get("jetty.client.requests").tag("outcome", "SERVER_ERROR").tag("status", "500") - .tag("uri", "/errorUnchecked").tag("host", "localhost").timer().count()).isEqualTo(1); + assertThat(registry.get("jetty.client.requests") + .tag("outcome", "SERVER_ERROR") + .tag("status", "500") + .tag("uri", "/errorUnchecked") + .tag("host", "localhost") + .timer() + .count()).isEqualTo(1); } @Test @@ -161,8 +185,13 @@ void notFound() throws Exception { httpClient.stop(); assertTrue(singleRequestLatch.await(10, SECONDS)); - assertThat(registry.get("jetty.client.requests").tag("outcome", "CLIENT_ERROR").tag("status", "404") - .tag("uri", "NOT_FOUND").tag("host", "localhost").timer().count()).isEqualTo(1); + assertThat(registry.get("jetty.client.requests") + .tag("outcome", "CLIENT_ERROR") + .tag("status", "404") + .tag("uri", "NOT_FOUND") + .tag("host", "localhost") + .timer() + .count()).isEqualTo(1); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettyConnectionMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettyConnectionMetricsTest.java index 5f20427e7e..b98c5e6462 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettyConnectionMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettyConnectionMetricsTest.java @@ -125,7 +125,7 @@ void passingConnectorAddsConnectorNameTag() { new JettyConnectionMetrics(registry, connector); assertThat(registry.get("jetty.connections.messages.in").counter().getId().getTag("connector.name")) - .isEqualTo("unnamed"); + .isEqualTo("unnamed"); } @Test @@ -134,7 +134,7 @@ void namedConnectorsGetTaggedWithName() { new JettyConnectionMetrics(registry, connector); assertThat(registry.get("jetty.connections.messages.in").counter().getId().getTag("connector.name")) - .isEqualTo("super-fast-connector"); + .isEqualTo("super-fast-connector"); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettySslHandshakeMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettySslHandshakeMetricsTest.java index 1199aa1908..30a007fd43 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettySslHandshakeMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/JettySslHandshakeMetricsTest.java @@ -62,8 +62,9 @@ void handshakeFailed() { SslHandshakeListener.Event event = new SslHandshakeListener.Event(engine); sslHandshakeMetrics.handshakeFailed(event, new javax.net.ssl.SSLHandshakeException("")); assertThat(registry.get("jetty.ssl.handshakes") - .tags("id", "0", "protocol", "unknown", "ciphersuite", "unknown", "result", "failed").counter().count()) - .isEqualTo(1.0); + .tags("id", "0", "protocol", "unknown", "ciphersuite", "unknown", "result", "failed") + .counter() + .count()).isEqualTo(1.0); } @Test @@ -74,16 +75,19 @@ void handshakeSucceeded() { when(session.getCipherSuite()).thenReturn("RSA_XYZZY"); sslHandshakeMetrics.handshakeSucceeded(event); assertThat(registry.get("jetty.ssl.handshakes") - .tags("id", "0", "protocol", "TLSv1.3", "ciphersuite", "RSA_XYZZY", "result", "succeeded").counter() - .count()).isEqualTo(1.0); + .tags("id", "0", "protocol", "TLSv1.3", "ciphersuite", "RSA_XYZZY", "result", "succeeded") + .counter() + .count()).isEqualTo(1.0); } @Test void connectorTagAdded() { Connector connector = mock(Connector.class); new JettySslHandshakeMetrics(registry, connector, tags); - assertThatCode(() -> registry.get("jetty.ssl.handshakes").tags("id", "0", "protocol", "unknown", "ciphersuite", - "unknown", "result", "failed", "connector.name", "unnamed").counter()).doesNotThrowAnyException(); + assertThatCode(() -> registry.get("jetty.ssl.handshakes") + .tags("id", "0", "protocol", "unknown", "ciphersuite", "unknown", "result", "failed", "connector.name", + "unnamed") + .counter()).doesNotThrowAnyException(); } @Test @@ -91,8 +95,10 @@ void namedConnectorTagAdded() { Connector connector = mock(Connector.class); when(connector.getName()).thenReturn("my-connector"); new JettySslHandshakeMetrics(registry, connector, tags); - assertThatCode(() -> registry.get("jetty.ssl.handshakes").tags("id", "0", "protocol", "unknown", "ciphersuite", - "unknown", "result", "failed", "connector.name", "my-connector").counter()).doesNotThrowAnyException(); + assertThatCode(() -> registry.get("jetty.ssl.handshakes") + .tags("id", "0", "protocol", "unknown", "ciphersuite", "unknown", "result", "failed", "connector.name", + "my-connector") + .counter()).doesNotThrowAnyException(); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/TimedHandlerTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/TimedHandlerTest.java index e2c6cb5aef..420c236182 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/TimedHandlerTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jetty/TimedHandlerTest.java @@ -116,8 +116,12 @@ public void handle(String path, Request request, HttpServletRequest httpRequest, barrier[1].await(5, TimeUnit.SECONDS); assertTrue(latchHandler.await()); - assertThat(registry.get("jetty.server.requests").tag("outcome", Outcome.SUCCESS.name()).tag("method", "GET") - .tag("status", "200").timer().count()).isEqualTo(2); + assertThat(registry.get("jetty.server.requests") + .tag("outcome", Outcome.SUCCESS.name()) + .tag("method", "GET") + .tag("status", "200") + .timer() + .count()).isEqualTo(2); } @Test @@ -204,8 +208,12 @@ public void onComplete(AsyncEvent event) { assertTrue(latchHandler.await()); // exited timed handler barrier[2].await(5, TimeUnit.SECONDS); // onComplete called - assertThat(registry.get("jetty.server.requests").tag("outcome", Outcome.SUCCESS.name()).tag("method", "GET") - .tag("status", "200").timer().count()).isEqualTo(1); + assertThat(registry.get("jetty.server.requests") + .tag("outcome", Outcome.SUCCESS.name()) + .tag("method", "GET") + .tag("status", "200") + .timer() + .count()).isEqualTo(1); } @Test @@ -359,8 +367,12 @@ public void onComplete(AsyncEvent event) { asyncHolder.get().complete(); latch.await(5, TimeUnit.SECONDS); - assertThat(registry.get("jetty.server.requests").tag("outcome", Outcome.SUCCESS.name()).tag("method", "GET") - .tag("status", "200").timer().count()).isEqualTo(1); + assertThat(registry.get("jetty.server.requests") + .tag("outcome", Outcome.SUCCESS.name()) + .tag("method", "GET") + .tag("status", "200") + .timer() + .count()).isEqualTo(1); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateMetricsNoSecondLevelCacheTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateMetricsNoSecondLevelCacheTest.java index 3ea3adb295..a8e2bed8ef 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateMetricsNoSecondLevelCacheTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateMetricsNoSecondLevelCacheTest.java @@ -52,7 +52,7 @@ private static SessionFactory createMockSessionFactory(boolean statsEnabled) { doReturn(new String[] { "region1", "region2" }).when(stats).getSecondLevelCacheRegionNames(); doReturn(null).when(stats).getDomainDataRegionStatistics("region1"); doThrow(new IllegalArgumentException("Mocked: Unknown region")).when(stats) - .getDomainDataRegionStatistics("region2"); + .getDomainDataRegionStatistics("region2"); when(sf.getStatistics()).thenReturn(stats); return sf; } @@ -70,9 +70,9 @@ private void assertThatMonitorShouldExposeMetricsWhenStatsEnabled() { assertThat(registry.get("hibernate.sessions.open").functionCounter().count()).isEqualTo(42.0); assertThatThrownBy(() -> registry.get("hibernate.second.level.cache.requests").functionCounters()) - .isInstanceOf(MeterNotFoundException.class); + .isInstanceOf(MeterNotFoundException.class); assertThatThrownBy(() -> registry.get("hibernate.second.level.cache.puts").functionCounters()) - .isInstanceOf(MeterNotFoundException.class); + .isInstanceOf(MeterNotFoundException.class); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateMetricsTest.java index 4a962ffe2b..e6ad69e050 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateMetricsTest.java @@ -86,33 +86,41 @@ private void assertThatMonitorShouldExposeMetricsWhenStatsEnabled() { assertThat(registry.get("hibernate.sessions.closed").functionCounter().count()).isEqualTo(42.0); assertThat(registry.get("hibernate.transactions").tags("result", "success").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat(registry.get("hibernate.transactions").tags("result", "failure").functionCounter().count()) - .isEqualTo(0.0d); + .isEqualTo(0.0d); assertThat(registry.get("hibernate.optimistic.failures").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.flushes").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.connections.obtained").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.statements").tags("status", "prepared").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat(registry.get("hibernate.statements").tags("status", "closed").functionCounter().count()) - .isEqualTo(42.0d); - - assertThat(registry.get("hibernate.second.level.cache.requests").tags("result", "hit", "region", "region1") - .functionCounter().count()).isEqualTo(42.0d); - assertThat(registry.get("hibernate.second.level.cache.requests").tags("result", "hit", "region", "region2") - .functionCounter().count()).isEqualTo(42.0d); - assertThat(registry.get("hibernate.second.level.cache.requests").tags("result", "miss", "region", "region1") - .functionCounter().count()).isEqualTo(42.0d); - assertThat(registry.get("hibernate.second.level.cache.requests").tags("result", "miss", "region", "region2") - .functionCounter().count()).isEqualTo(42.0d); + .isEqualTo(42.0d); + + assertThat(registry.get("hibernate.second.level.cache.requests") + .tags("result", "hit", "region", "region1") + .functionCounter() + .count()).isEqualTo(42.0d); + assertThat(registry.get("hibernate.second.level.cache.requests") + .tags("result", "hit", "region", "region2") + .functionCounter() + .count()).isEqualTo(42.0d); + assertThat(registry.get("hibernate.second.level.cache.requests") + .tags("result", "miss", "region", "region1") + .functionCounter() + .count()).isEqualTo(42.0d); + assertThat(registry.get("hibernate.second.level.cache.requests") + .tags("result", "miss", "region", "region2") + .functionCounter() + .count()).isEqualTo(42.0d); assertThat( registry.get("hibernate.second.level.cache.puts").tags("region", "region1").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat( registry.get("hibernate.second.level.cache.puts").tags("region", "region2").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat(registry.get("hibernate.entities.deletes").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.entities.fetches").functionCounter().count()).isEqualTo(42.0d); @@ -127,33 +135,37 @@ private void assertThatMonitorShouldExposeMetricsWhenStatsEnabled() { assertThat(registry.get("hibernate.collections.updates").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.cache.natural.id.requests").tags("result", "hit").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat(registry.get("hibernate.cache.natural.id.requests").tags("result", "miss").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat(registry.get("hibernate.cache.natural.id.puts").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.query.natural.id.executions").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.query.natural.id.executions.max").timeGauge().value(TimeUnit.MILLISECONDS)) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat(registry.get("hibernate.query.executions").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.query.executions.max").timeGauge().value(TimeUnit.MILLISECONDS)) - .isEqualTo(42.0d); - - assertThat(registry.get("hibernate.cache.update.timestamps.requests").tags("result", "hit").functionCounter() - .count()).isEqualTo(42.0d); - assertThat(registry.get("hibernate.cache.update.timestamps.requests").tags("result", "miss").functionCounter() - .count()).isEqualTo(42.0d); + .isEqualTo(42.0d); + + assertThat(registry.get("hibernate.cache.update.timestamps.requests") + .tags("result", "hit") + .functionCounter() + .count()).isEqualTo(42.0d); + assertThat(registry.get("hibernate.cache.update.timestamps.requests") + .tags("result", "miss") + .functionCounter() + .count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.cache.update.timestamps.puts").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.cache.query.requests").tags("result", "hit").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat(registry.get("hibernate.cache.query.requests").tags("result", "miss").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat(registry.get("hibernate.cache.query.puts").functionCounter().count()).isEqualTo(42.0d); assertThat(registry.get("hibernate.cache.query.plan").tags("result", "hit").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); assertThat(registry.get("hibernate.cache.query.plan").tags("result", "miss").functionCounter().count()) - .isEqualTo(42.0d); + .isEqualTo(42.0d); } @SuppressWarnings("deprecation") diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateQueryMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateQueryMetricsTest.java index f58043bd73..9e726fef34 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateQueryMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jpa/HibernateQueryMetricsTest.java @@ -56,21 +56,29 @@ void metricsEventHandlerRegistersMetrics() { eventHandler.registerQueryMetric(statistics); - assertThat(registry.get("hibernate.query.cache.requests").tags("result", "hit", "query", query) - .functionCounter().count()).isEqualTo(43.0d); - assertThat(registry.get("hibernate.query.cache.requests").tags("result", "miss", "query", query) - .functionCounter().count()).isEqualTo(43.0d); + assertThat(registry.get("hibernate.query.cache.requests") + .tags("result", "hit", "query", query) + .functionCounter() + .count()).isEqualTo(43.0d); + assertThat(registry.get("hibernate.query.cache.requests") + .tags("result", "miss", "query", query) + .functionCounter() + .count()).isEqualTo(43.0d); assertThat(registry.get("hibernate.query.cache.puts").tags("query", query).functionCounter().count()) - .isEqualTo(43.0d); + .isEqualTo(43.0d); FunctionTimer timer = registry.get("hibernate.query.execution.total").tags("query", query).functionTimer(); assertThat(timer.count()).isEqualTo(43.0d); assertThat(timer.totalTime(TimeUnit.MILLISECONDS)).isEqualTo(43.0d); - assertThat(registry.get("hibernate.query.execution.max").tags("query", query).timeGauge() - .value(TimeUnit.MILLISECONDS)).isEqualTo(43.0d); - assertThat(registry.get("hibernate.query.execution.min").tags("query", query).timeGauge() - .value(TimeUnit.MILLISECONDS)).isEqualTo(43.0d); + assertThat(registry.get("hibernate.query.execution.max") + .tags("query", query) + .timeGauge() + .value(TimeUnit.MILLISECONDS)).isEqualTo(43.0d); + assertThat(registry.get("hibernate.query.execution.min") + .tags("query", query) + .timeGauge() + .value(TimeUnit.MILLISECONDS)).isEqualTo(43.0d); assertThat(registry.get("hibernate.query.execution.rows").tags("query", query).functionCounter().count()) - .isEqualTo(43.0); + .isEqualTo(43.0); } private Statistics createQueryStatisticsMock(String query) { diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetricsTest.java index e04c9f1784..296452723f 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetricsTest.java @@ -61,11 +61,14 @@ void executor(String metricPrefix, String expectedMetricPrefix) throws Interrupt executor.execute(() -> System.out.println("hello")); lock.await(); - assertThat(registry.get(expectedMetricPrefix + "executor.execution").tags(userTags).tag("name", "exec").timer() - .count()).isEqualTo(1L); + assertThat(registry.get(expectedMetricPrefix + "executor.execution") + .tags(userTags) + .tag("name", "exec") + .timer() + .count()).isEqualTo(1L); assertThat( registry.get(expectedMetricPrefix + "executor.idle").tags(userTags).tag("name", "exec").timer().count()) - .isEqualTo(1L); + .isEqualTo(1L); } @DisplayName("ExecutorService is casted from Executor when necessary") @@ -133,8 +136,11 @@ void monitorExecutorService(String metricPrefix, String expectedMetricPrefix) th assertThat(taskStart.await(1, TimeUnit.SECONDS)).isTrue(); - assertThat(registry.get(expectedMetricPrefix + "executor.queued").tags(userTags).tag("name", "beep.pool") - .gauge().value()).isEqualTo(1.0); + assertThat(registry.get(expectedMetricPrefix + "executor.queued") + .tags(userTags) + .tag("name", "beep.pool") + .gauge() + .value()).isEqualTo(1.0); taskComplete.countDown(); @@ -144,7 +150,7 @@ void monitorExecutorService(String metricPrefix, String expectedMetricPrefix) th assertThat(registry.get(expectedMetricPrefix + "executor").tags(userTags).timer().count()).isEqualTo(2L); assertThat(registry.get(expectedMetricPrefix + "executor.idle").tags(userTags).timer().count()).isEqualTo(2L); assertThat(registry.get(expectedMetricPrefix + "executor.queued").tags(userTags).gauge().value()) - .isEqualTo(0.0); + .isEqualTo(0.0); } @DisplayName("No exception thrown trying to monitor Executors private class") @@ -152,7 +158,7 @@ void monitorExecutorService(String metricPrefix, String expectedMetricPrefix) th @Issue("#2447") // Note: only reproduces on Java 16+ or with --illegal-access=deny void monitorExecutorsExecutorServicePrivateClass() { assertThatCode(() -> ExecutorServiceMetrics.monitor(registry, Executors.newSingleThreadExecutor(), "")) - .doesNotThrowAnyException(); + .doesNotThrowAnyException(); } @DisplayName("ScheduledExecutorService can be monitored with a default set of metrics") @@ -186,8 +192,11 @@ void monitorScheduledExecutorService(String metricPrefix, String expectedMetricP }; ScheduledFuture runnableResult = pool.schedule(scheduledBeepRunnable, 15, TimeUnit.MILLISECONDS); - assertThat(registry.get(expectedMetricPrefix + "executor.scheduled.once").tags(userTags) - .tag("name", "scheduled.pool").counter().count()).isEqualTo(2); + assertThat(registry.get(expectedMetricPrefix + "executor.scheduled.once") + .tags(userTags) + .tag("name", "scheduled.pool") + .counter() + .count()).isEqualTo(2); assertThat(callableTaskStart.await(1, TimeUnit.SECONDS)).isTrue(); assertThat(runnableTaskStart.await(1, TimeUnit.SECONDS)).isTrue(); @@ -217,7 +226,7 @@ void monitorScheduledExecutorServiceWithRepetitiveTasks(String metricPrefix, Str assertThat( registry.get(expectedMetricPrefix + "executor.scheduled.repetitively").tags(userTags).counter().count()) - .isEqualTo(0); + .isEqualTo(0); assertThat(registry.get(expectedMetricPrefix + "executor").tags(userTags).timer().count()).isEqualTo(0L); Runnable repeatedAtFixedRate = () -> { @@ -238,7 +247,7 @@ void monitorScheduledExecutorServiceWithRepetitiveTasks(String metricPrefix, Str assertThat( registry.get(expectedMetricPrefix + "executor.scheduled.repetitively").tags(userTags).counter().count()) - .isEqualTo(2); + .isEqualTo(2); assertThat(fixedRateInvocations.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(fixedDelayInvocations.await(5, TimeUnit.SECONDS)).isTrue(); @@ -295,7 +304,7 @@ void newSingleThreadScheduledExecutorWhenReflectiveAccessIsDisabled() { ExecutorServiceMetrics.monitor(registry, Executors.newSingleThreadScheduledExecutor(), executorServiceName); registry.get("executor").tag("name", executorServiceName).timer(); assertThatThrownBy(() -> registry.get("executor.completed").tag("name", executorServiceName).functionCounter()) - .isExactlyInstanceOf(MeterNotFoundException.class); + .isExactlyInstanceOf(MeterNotFoundException.class); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jvm/JvmGcMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jvm/JvmGcMetricsTest.java index f486655612..b3e9de3e6d 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jvm/JvmGcMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/jvm/JvmGcMetricsTest.java @@ -69,11 +69,12 @@ void beforeEach() { @Test void noJvmImplementationSpecificApiSignatures() { JavaClasses importedClasses = new ClassFileImporter() - .importPackages("io.micrometer.core.instrument.binder.jvm"); + .importPackages("io.micrometer.core.instrument.binder.jvm"); ArchRule noSunManagementInMethodSignatures = methods().should() - .notHaveRawReturnType(resideInAPackage("com.sun.management..")).andShould() - .notHaveRawParameterTypes(DescribedPredicate.anyElementThat(resideInAPackage("com.sun.management.."))); + .notHaveRawReturnType(resideInAPackage("com.sun.management..")) + .andShould() + .notHaveRawParameterTypes(DescribedPredicate.anyElementThat(resideInAPackage("com.sun.management.."))); noSunManagementInMethodSignatures.check(importedClasses); } @@ -81,8 +82,9 @@ void noJvmImplementationSpecificApiSignatures() { @Test void gcMetricsAvailableAfterGc() { System.gc(); - await().timeout(200, TimeUnit.MILLISECONDS).alias("NotificationListener takes time after GC") - .untilAsserted(() -> assertThat(registry.find("jvm.gc.live.data.size").gauge().value()).isPositive()); + await().timeout(200, TimeUnit.MILLISECONDS) + .alias("NotificationListener takes time after GC") + .untilAsserted(() -> assertThat(registry.find("jvm.gc.live.data.size").gauge().value()).isPositive()); assertThat(registry.find("jvm.gc.memory.allocated").counter().count()).isPositive(); assertThat(registry.find("jvm.gc.max.data.size").gauge().value()).isPositive(); @@ -113,8 +115,8 @@ else if (mbean.getName().contains("Cycles")) { concurrentPhaseCount += mbean.getCollectionCount(); concurrentTimeMs += mbean.getCollectionTime(); } - System.out.println( - mbean.getName() + " (" + mbean.getCollectionCount() + ") " + mbean.getCollectionTime() + "ms"); + System.out + .println(mbean.getName() + " (" + mbean.getCollectionCount() + ") " + mbean.getCollectionTime() + "ms"); } checkPhaseCount(pausePhaseCount, concurrentPhaseCount); checkCollectionTime(pauseTimeMs, concurrentTimeMs); @@ -134,7 +136,7 @@ void sizeMetricsNotSetToZero() throws InterruptedException { } NotificationEmitter notificationEmitter = (NotificationEmitter) gcBean; notificationEmitter.addNotificationListener(capturingListener, notification -> notification.getType() - .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION), null); + .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION), null); notificationListenerCleanUpRunnables.add(() -> { try { notificationEmitter.removeNotificationListener(capturingListener); @@ -187,8 +189,11 @@ public void handleNotification(Notification notification, Object handback) { private void checkPhaseCount(long expectedPauseCount, long expectedConcurrentCount) { await().atMost(200, TimeUnit.MILLISECONDS).untilAsserted(() -> { long observedPauseCount = registry.find("jvm.gc.pause").timers().stream().mapToLong(Timer::count).sum(); - long observedConcurrentCount = registry.find("jvm.gc.concurrent.phase.time").timers().stream() - .mapToLong(Timer::count).sum(); + long observedConcurrentCount = registry.find("jvm.gc.concurrent.phase.time") + .timers() + .stream() + .mapToLong(Timer::count) + .sum(); assertThat(observedPauseCount).isEqualTo(expectedPauseCount); assertThat(observedConcurrentCount).isEqualTo(expectedConcurrentCount); }); @@ -196,10 +201,16 @@ private void checkPhaseCount(long expectedPauseCount, long expectedConcurrentCou private void checkCollectionTime(long expectedPauseTimeMs, long expectedConcurrentTimeMs) { await().atMost(200, TimeUnit.MILLISECONDS).untilAsserted(() -> { - double observedPauseTimeMs = registry.find("jvm.gc.pause").timers().stream() - .mapToDouble(timer -> timer.totalTime(TimeUnit.MILLISECONDS)).sum(); - double observedConcurrentTimeMs = registry.find("jvm.gc.concurrent.phase.time").timers().stream() - .mapToDouble(timer -> timer.totalTime(TimeUnit.MILLISECONDS)).sum(); + double observedPauseTimeMs = registry.find("jvm.gc.pause") + .timers() + .stream() + .mapToDouble(timer -> timer.totalTime(TimeUnit.MILLISECONDS)) + .sum(); + double observedConcurrentTimeMs = registry.find("jvm.gc.concurrent.phase.time") + .timers() + .stream() + .mapToDouble(timer -> timer.totalTime(TimeUnit.MILLISECONDS)) + .sum(); // small difference can happen when less than 1ms timing gets rounded assertThat(observedPauseTimeMs).isCloseTo(expectedPauseTimeMs, within(1d)); assertThat(observedConcurrentTimeMs).isCloseTo(expectedConcurrentTimeMs, within(1d)); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsAdminTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsAdminTest.java index c0ecbc1c81..e060af2ffe 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsAdminTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsAdminTest.java @@ -49,8 +49,9 @@ void shouldCreateMeters() { MeterRegistry registry = new SimpleMeterRegistry(); metrics.bindTo(registry); - assertThat(registry.getMeters()).hasSizeGreaterThan(0).extracting(meter -> meter.getId().getName()) - .allMatch(s -> s.startsWith(METRIC_NAME_PREFIX)); + assertThat(registry.getMeters()).hasSizeGreaterThan(0) + .extracting(meter -> meter.getId().getName()) + .allMatch(s -> s.startsWith(METRIC_NAME_PREFIX)); } } @@ -62,8 +63,9 @@ void shouldCreateMetersWithTags() { metrics.bindTo(registry); - assertThat(registry.getMeters()).hasSizeGreaterThan(0).extracting(meter -> meter.getId().getTag("app")) - .allMatch(s -> s.equals("myapp")); + assertThat(registry.getMeters()).hasSizeGreaterThan(0) + .extracting(meter -> meter.getId().getTag("app")) + .allMatch(s -> s.equals("myapp")); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsConsumerTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsConsumerTest.java index f9ed37a1f6..7908f318d2 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsConsumerTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsConsumerTest.java @@ -51,8 +51,9 @@ void shouldCreateMeters() { MeterRegistry registry = new SimpleMeterRegistry(); metrics.bindTo(registry); - assertThat(registry.getMeters()).hasSizeGreaterThan(0).extracting(meter -> meter.getId().getName()) - .allMatch(s -> s.startsWith(METRIC_NAME_PREFIX)); + assertThat(registry.getMeters()).hasSizeGreaterThan(0) + .extracting(meter -> meter.getId().getName()) + .allMatch(s -> s.startsWith(METRIC_NAME_PREFIX)); } } @@ -64,8 +65,9 @@ void shouldCreateMetersWithTags() { metrics.bindTo(registry); - assertThat(registry.getMeters()).hasSizeGreaterThan(0).extracting(meter -> meter.getId().getTag("app")) - .allMatch(s -> s.equals("myapp")); + assertThat(registry.getMeters()).hasSizeGreaterThan(0) + .extracting(meter -> meter.getId().getTag("app")) + .allMatch(s -> s.equals("myapp")); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsIntegrationTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsIntegrationTest.java index ff2856fe9c..b368de9183 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsIntegrationTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsIntegrationTest.java @@ -115,16 +115,20 @@ void shouldManageProducerAndConsumerMetrics() { // see gh-3300 assertThat(registry.getMeters().stream().filter(meter -> meter.getId().getName().endsWith(".count"))) - .allMatch(meter -> meter instanceof Gauge); + .allMatch(meter -> meter instanceof Gauge); // Printing out for discovery purposes out.println("All meters from producer and consumer:"); printMeters(registry); - List metersEndingWithTotal = registry.getMeters().stream() - .filter(meter -> meter.getId().getName().endsWith(".total")).collect(Collectors.toList()); - List functionCounters = registry.getMeters().stream().filter(meter -> meter instanceof FunctionCounter) - .collect(Collectors.toList()); + List metersEndingWithTotal = registry.getMeters() + .stream() + .filter(meter -> meter.getId().getName().endsWith(".total")) + .collect(Collectors.toList()); + List functionCounters = registry.getMeters() + .stream() + .filter(meter -> meter instanceof FunctionCounter) + .collect(Collectors.toList()); assertThat(metersEndingWithTotal).isEqualTo(functionCounters); producerKafkaMetrics.close(); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsProducerTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsProducerTest.java index 1b4361a04d..7d8131ff52 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsProducerTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaClientMetricsProducerTest.java @@ -51,8 +51,9 @@ void shouldCreateMeters() { MeterRegistry registry = new SimpleMeterRegistry(); metrics.bindTo(registry); - assertThat(registry.getMeters()).hasSizeGreaterThan(0).extracting(meter -> meter.getId().getName()) - .allMatch(s -> s.startsWith(METRIC_NAME_PREFIX)); + assertThat(registry.getMeters()).hasSizeGreaterThan(0) + .extracting(meter -> meter.getId().getName()) + .allMatch(s -> s.startsWith(METRIC_NAME_PREFIX)); } } @@ -64,8 +65,9 @@ void shouldCreateMetersWithTags() { metrics.bindTo(registry); - assertThat(registry.getMeters()).hasSizeGreaterThan(0).extracting(meter -> meter.getId().getTag("app")) - .allMatch(s -> s.equals("myapp")); + assertThat(registry.getMeters()).hasSizeGreaterThan(0) + .extracting(meter -> meter.getId().getTag("app")) + .allMatch(s -> s.equals("myapp")); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetricsTest.java index 2fa6e40437..eba34a6bda 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetricsTest.java @@ -86,8 +86,9 @@ void metricsReportedPerMultipleConsumers() { // fetch metrics registry.get("kafka.consumer.fetch.total").tag("client.id", "consumer-" + consumerCount).functionCounter(); - registry.get("kafka.consumer.fetch.total").tag("client.id", "consumer-" + (consumerCount - 1)) - .functionCounter(); + registry.get("kafka.consumer.fetch.total") + .tag("client.id", "consumer-" + (consumerCount - 1)) + .functionCounter(); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaMetricsTest.java index eb5e9bdae9..452c5254f8 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaMetricsTest.java @@ -245,8 +245,8 @@ void shouldRemoveOlderMeterWithLessTagsWhenCommonTagsConfigured() { kafkaMetrics.bindTo(registry); assertThat(registry.getMeters()).hasSize(1); assertThat(registry.getMeters().get(0).getId().getTags()) - .containsExactlyInAnyOrder(Tag.of("kafka.version", "unknown"), Tag.of("common", "value")); // only - // version + .containsExactlyInAnyOrder(Tag.of("kafka.version", "unknown"), Tag.of("common", "value")); // only + // version tags.put("key0", "value0"); kafkaMetrics.checkAndBindMetrics(registry); @@ -279,8 +279,13 @@ void shouldRemoveMeterWithLessTagsWithMultipleClients() { kafkaMetrics = new KafkaMetrics(supplier); MeterRegistry registry = new SimpleMeterRegistry(); // simulate PrometheusMeterRegistry restriction - registry.config().onMeterAdded(meter -> registry.find(meter.getId().getName()).meters().stream() - .filter(m -> m.getId().getTags().size() != meter.getId().getTags().size()).findAny().ifPresent(m -> { + registry.config() + .onMeterAdded(meter -> registry.find(meter.getId().getName()) + .meters() + .stream() + .filter(m -> m.getId().getTags().size() != meter.getId().getTags().size()) + .findAny() + .ifPresent(m -> { throw new RuntimeException("meter exists with different number of tags"); })); // When @@ -312,7 +317,8 @@ void shouldRemoveMeterWithLessTagsWithMultipleClients() { kafkaMetrics.checkAndBindMetrics(registry); // Then assertThat(registry.getMeters()).hasSize(2); - registry.getMeters().forEach(meter -> assertThat(meter.getId().getTags()).extracting(Tag::getKey) + registry.getMeters() + .forEach(meter -> assertThat(meter.getId().getTags()).extracting(Tag::getKey) .containsOnly("key0", "key1", "client.id", "kafka.version")); } @@ -339,9 +345,11 @@ void shouldUseMetricFromSupplierIfInstanceChanges() { metrics.put(metricName, newMetricInstance); kafkaMetrics.checkAndBindMetrics(registry); - assertThat(registry.getMeters()).singleElement().extracting(Meter::measure) - .satisfies(measurements -> assertThat(measurements).singleElement().extracting(Measurement::getValue) - .isEqualTo(2.0)); + assertThat(registry.getMeters()).singleElement() + .extracting(Meter::measure) + .satisfies(measurements -> assertThat(measurements).singleElement() + .extracting(Measurement::getValue) + .isEqualTo(2.0)); } @Issue("#2801") @@ -362,9 +370,11 @@ void shouldUseMetricFromSupplierIndirectly() { kafkaMetrics.bindTo(registry); assertThat(registry.getMeters()).hasSize(1); - assertThat(registry.getMeters()).singleElement().extracting(Meter::measure) - .satisfies(measurements -> assertThat(measurements).singleElement().extracting(Measurement::getValue) - .isEqualTo(1.0)); + assertThat(registry.getMeters()).singleElement() + .extracting(Meter::measure) + .satisfies(measurements -> assertThat(measurements).singleElement() + .extracting(Measurement::getValue) + .isEqualTo(1.0)); metricsReference.set(new HashMap<>()); MetricName newMetricName = new MetricName("a0", "b0", "c0", new LinkedHashMap<>()); @@ -373,16 +383,20 @@ void shouldUseMetricFromSupplierIndirectly() { KafkaMetric newMetricInstance = new KafkaMetric(this, newMetricName, newValue, new MetricConfig(), Time.SYSTEM); metricsReference.get().put(newMetricName, newMetricInstance); - assertThat(registry.getMeters()).singleElement().extracting(Meter::measure) - .satisfies(measurements -> assertThat(measurements).singleElement().extracting(Measurement::getValue) - .isEqualTo(1.0)); // still referencing the old value since the map - // is only updated in checkAndBindMetrics + assertThat(registry.getMeters()).singleElement() + .extracting(Meter::measure) + .satisfies(measurements -> assertThat(measurements).singleElement() + .extracting(Measurement::getValue) + .isEqualTo(1.0)); // still referencing the old value since the map + // is only updated in checkAndBindMetrics kafkaMetrics.checkAndBindMetrics(registry); - assertThat(registry.getMeters()).singleElement().extracting(Meter::measure) - .satisfies(measurements -> assertThat(measurements).singleElement().extracting(Measurement::getValue) - .isEqualTo(2.0)); // referencing the new value since the map was - // updated in checkAndBindMetrics + assertThat(registry.getMeters()).singleElement() + .extracting(Meter::measure) + .satisfies(measurements -> assertThat(measurements).singleElement() + .extracting(Measurement::getValue) + .isEqualTo(2.0)); // referencing the new value since the map was + // updated in checkAndBindMetrics } @Issue("#2843") diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaStreamsMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaStreamsMetricsTest.java index c4f2f9f796..93935f7dd3 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaStreamsMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/kafka/KafkaStreamsMetricsTest.java @@ -51,8 +51,9 @@ void shouldCreateMeters() { MeterRegistry registry = new SimpleMeterRegistry(); metrics.bindTo(registry); - assertThat(registry.getMeters()).hasSizeGreaterThan(0).extracting(meter -> meter.getId().getName()) - .allMatch(s -> s.startsWith(METRIC_NAME_PREFIX)); + assertThat(registry.getMeters()).hasSizeGreaterThan(0) + .extracting(meter -> meter.getId().getName()) + .allMatch(s -> s.startsWith(METRIC_NAME_PREFIX)); } } @@ -64,8 +65,9 @@ void shouldCreateMetersWithTags() { metrics.bindTo(registry); - assertThat(registry.getMeters()).hasSizeGreaterThan(0).extracting(meter -> meter.getId().getTag("app")) - .allMatch(s -> s.equals("myapp")); + assertThat(registry.getMeters()).hasSizeGreaterThan(0) + .extracting(meter -> meter.getId().getTag("app")) + .allMatch(s -> s.equals("myapp")); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/logging/Log4j2MetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/logging/Log4j2MetricsTest.java index 7f757c275c..81f8008dc7 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/logging/Log4j2MetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/logging/Log4j2MetricsTest.java @@ -175,7 +175,7 @@ void asyncLogShouldNotBeDuplicated() throws IOException { assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(0); logger.info("Hello, world!"); await().atMost(Duration.ofSeconds(1)) - .until(() -> registry.get("log4j2.events").tags("level", "info").counter().count() == 1); + .until(() -> registry.get("log4j2.events").tags("level", "info").counter().count() == 1); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/DefaultMongoCommandTagsProviderTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/DefaultMongoCommandTagsProviderTest.java index 9b5839c292..81bb3cbe8d 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/DefaultMongoCommandTagsProviderTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/DefaultMongoCommandTagsProviderTest.java @@ -98,13 +98,13 @@ class DetermineCollectionName { @Test void withNameInAllowList() { assertThat(tagsProvider.determineCollectionName("find", new BsonDocument("find", new BsonString(" bar ")))) - .hasValue("bar"); + .hasValue("bar"); } @Test void withNameNotInAllowList() { assertThat(tagsProvider.determineCollectionName("cmd", new BsonDocument("cmd", new BsonString(" bar ")))) - .isEmpty(); + .isEmpty(); } @Test @@ -115,19 +115,20 @@ void withNameNotInCommand() { @Test void withNonStringCommand() { assertThat(tagsProvider.determineCollectionName("find", new BsonDocument("find", BsonBoolean.TRUE))) - .isEmpty(); + .isEmpty(); } @Test void withEmptyStringCommand() { assertThat(tagsProvider.determineCollectionName("find", new BsonDocument("find", new BsonString(" ")))) - .isEmpty(); + .isEmpty(); } @Test void withCollectionFieldOnly() { assertThat(tagsProvider.determineCollectionName("find", - new BsonDocument("collection", new BsonString(" bar ")))).hasValue("bar"); + new BsonDocument("collection", new BsonString(" bar ")))) + .hasValue("bar"); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsCommandListenerTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsCommandListenerTest.java index f8578ffe1c..40f9f3b768 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsCommandListenerTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsCommandListenerTest.java @@ -59,14 +59,15 @@ void setup() { registry = new SimpleMeterRegistry(); clusterId = new AtomicReference<>(); MongoClientSettings settings = MongoClientSettings.builder() - .addCommandListener(new MongoMetricsCommandListener(registry)).applyToClusterSettings(builder -> builder - .hosts(singletonList(new ServerAddress(host, port))).addClusterListener(new ClusterListener() { - @Override - public void clusterOpening(ClusterOpeningEvent event) { - clusterId.set(event.getClusterId().getValue()); - } - })) - .build(); + .addCommandListener(new MongoMetricsCommandListener(registry)) + .applyToClusterSettings(builder -> builder.hosts(singletonList(new ServerAddress(host, port))) + .addClusterListener(new ClusterListener() { + @Override + public void clusterOpening(ClusterOpeningEvent event) { + clusterId.set(event.getClusterId().getValue()); + } + })) + .build(); mongo = MongoClients.create(settings); } @@ -97,15 +98,15 @@ public Iterable commandTags(CommandEvent event) { } }; MongoClientSettings settings = MongoClientSettings.builder() - .addCommandListener(new MongoMetricsCommandListener(registry, tagsProvider)) - .applyToClusterSettings(builder -> builder.hosts(singletonList(new ServerAddress(host, port))) - .addClusterListener(new ClusterListener() { - @Override - public void clusterOpening(ClusterOpeningEvent event) { - clusterId.set(event.getClusterId().getValue()); - } - })) - .build(); + .addCommandListener(new MongoMetricsCommandListener(registry, tagsProvider)) + .applyToClusterSettings(builder -> builder.hosts(singletonList(new ServerAddress(host, port))) + .addClusterListener(new ClusterListener() { + @Override + public void clusterOpening(ClusterOpeningEvent event) { + clusterId.set(event.getClusterId().getValue()); + } + })) + .build(); try (MongoClient mongo = MongoClients.create(settings)) { mongo.getDatabase("test").getCollection("testCol").insertOne(new Document("testDoc", new Date())); Tags tags = Tags.of("cluster.id", clusterId.get(), "server.address", String.format("%s:%s", host, port), @@ -123,15 +124,15 @@ public Iterable commandTags(CommandEvent event) { } }; MongoClientSettings settings = MongoClientSettings.builder() - .addCommandListener(new MongoMetricsCommandListener(registry, tagsProvider)) - .applyToClusterSettings(builder -> builder.hosts(singletonList(new ServerAddress(host, port))) - .addClusterListener(new ClusterListener() { - @Override - public void clusterOpening(ClusterOpeningEvent event) { - clusterId.set(event.getClusterId().getValue()); - } - })) - .build(); + .addCommandListener(new MongoMetricsCommandListener(registry, tagsProvider)) + .applyToClusterSettings(builder -> builder.hosts(singletonList(new ServerAddress(host, port))) + .addClusterListener(new ClusterListener() { + @Override + public void clusterOpening(ClusterOpeningEvent event) { + clusterId.set(event.getClusterId().getValue()); + } + })) + .build(); try (MongoClient mongo = MongoClients.create(settings)) { mongo.getDatabase("test").getCollection("testCol").dropIndex("nonExistentIndex"); Tags tags = Tags.of("cluster.id", clusterId.get(), "server.address", String.format("%s:%s", host, port), @@ -145,16 +146,21 @@ void shouldSupportConcurrentCommands() throws InterruptedException { for (int i = 0; i < 20; i++) { Map commandThreadMap = new HashMap<>(); - commandThreadMap.put("insert", new Thread(() -> mongo.getDatabase("test").getCollection("testCol") - .insertOne(new Document("testField", new Date())))); + commandThreadMap.put("insert", + new Thread(() -> mongo.getDatabase("test") + .getCollection("testCol") + .insertOne(new Document("testField", new Date())))); commandThreadMap.put("update", - new Thread(() -> mongo.getDatabase("test").getCollection("testCol").updateOne( - new Document("nonExistentField", "abc"), - new Document("$set", new Document("nonExistentField", "xyz"))))); + new Thread(() -> mongo.getDatabase("test") + .getCollection("testCol") + .updateOne(new Document("nonExistentField", "abc"), + new Document("$set", new Document("nonExistentField", "xyz"))))); - commandThreadMap.put("delete", new Thread(() -> mongo.getDatabase("test").getCollection("testCol") - .deleteOne(new Document("nonExistentField", "abc")))); + commandThreadMap.put("delete", + new Thread(() -> mongo.getDatabase("test") + .getCollection("testCol") + .deleteOne(new Document("nonExistentField", "abc")))); commandThreadMap.put("aggregate", new Thread(() -> mongo.getDatabase("test").getCollection("testCol").countDocuments())); @@ -172,15 +178,18 @@ void shouldSupportConcurrentCommands() throws InterruptedException { for (String command : commandThreadMap.keySet()) { long commandsRecorded; try { - commandsRecorded = registry.get("mongodb.driver.commands").tags(Tags.of("command", command)).timer() - .count(); + commandsRecorded = registry.get("mongodb.driver.commands") + .tags(Tags.of("command", command)) + .timer() + .count(); } catch (MeterNotFoundException e) { commandsRecorded = 0L; } - assertThat(commandsRecorded).as("Check how many %s commands were recorded after %d iterations", command, - iterationsCompleted).isEqualTo(iterationsCompleted); + assertThat(commandsRecorded) + .as("Check how many %s commands were recorded after %d iterations", command, iterationsCompleted) + .isEqualTo(iterationsCompleted); } } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsConnectionPoolListenerTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsConnectionPoolListenerTest.java index b28270c12c..7e0757dd27 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsConnectionPoolListenerTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/mongodb/MongoMetricsConnectionPoolListenerTest.java @@ -50,16 +50,16 @@ class MongoMetricsConnectionPoolListenerTest extends AbstractMongoDbTest { void shouldCreatePoolMetrics() { AtomicReference clusterId = new AtomicReference<>(); MongoClientSettings settings = MongoClientSettings.builder() - .applyToConnectionPoolSettings(builder -> builder.minSize(2) - .addConnectionPoolListener(new MongoMetricsConnectionPoolListener(registry))) - .applyToClusterSettings(builder -> builder.hosts(singletonList(new ServerAddress(host, port))) - .addClusterListener(new ClusterListener() { - @Override - public void clusterOpening(ClusterOpeningEvent event) { - clusterId.set(event.getClusterId().getValue()); - } - })) - .build(); + .applyToConnectionPoolSettings(builder -> builder.minSize(2) + .addConnectionPoolListener(new MongoMetricsConnectionPoolListener(registry))) + .applyToClusterSettings(builder -> builder.hosts(singletonList(new ServerAddress(host, port))) + .addClusterListener(new ClusterListener() { + @Override + public void clusterOpening(ClusterOpeningEvent event) { + clusterId.set(event.getClusterId().getValue()); + } + })) + .build(); MongoClient mongo = MongoClients.create(settings); mongo.getDatabase("test").createCollection("testCol"); @@ -73,7 +73,8 @@ public void clusterOpening(ClusterOpeningEvent event) { mongo.close(); assertThat(registry.find("mongodb.driver.pool.size").tags(tags).gauge()) - .describedAs("metrics should be removed when the connection pool is closed").isNull(); + .describedAs("metrics should be removed when the connection pool is closed") + .isNull(); } @Test @@ -84,16 +85,16 @@ void shouldCreatePoolMetricsWithCustomTags() { e -> Tags.of("cluster.id", e.getServerId().getClusterId().getValue(), "server.address", e.getServerId().getAddress().toString(), "my.custom.connection.pool.identifier", "custom")); MongoClientSettings settings = MongoClientSettings.builder() - .applyToConnectionPoolSettings( - builder -> builder.minSize(2).addConnectionPoolListener(connectionPoolListener)) - .applyToClusterSettings(builder -> builder.hosts(singletonList(new ServerAddress(host, port))) - .addClusterListener(new ClusterListener() { - @Override - public void clusterOpening(ClusterOpeningEvent event) { - clusterId.set(event.getClusterId().getValue()); - } - })) - .build(); + .applyToConnectionPoolSettings( + builder -> builder.minSize(2).addConnectionPoolListener(connectionPoolListener)) + .applyToClusterSettings(builder -> builder.hosts(singletonList(new ServerAddress(host, port))) + .addClusterListener(new ClusterListener() { + @Override + public void clusterOpening(ClusterOpeningEvent event) { + clusterId.set(event.getClusterId().getValue()); + } + })) + .build(); MongoClient mongo = MongoClients.create(settings); mongo.getDatabase("test").createCollection("testCol"); @@ -108,7 +109,8 @@ public void clusterOpening(ClusterOpeningEvent event) { mongo.close(); assertThat(registry.find("mongodb.driver.pool.size").tags(tags).gauge()) - .describedAs("metrics should be removed when the connection pool is closed").isNull(); + .describedAs("metrics should be removed when the connection pool is closed") + .isNull(); } @Issue("#2384") @@ -116,12 +118,12 @@ void whenConnectionCheckedInAfterPoolClose_thenNoExceptionThrown() { ServerId serverId = new ServerId(new ClusterId(), new ServerAddress(host, port)); ConnectionId connectionId = new ConnectionId(serverId); MongoMetricsConnectionPoolListener listener = new MongoMetricsConnectionPoolListener(registry); - listener.connectionPoolCreated( - new ConnectionPoolCreatedEvent(serverId, ConnectionPoolSettings.builder().build())); + listener + .connectionPoolCreated(new ConnectionPoolCreatedEvent(serverId, ConnectionPoolSettings.builder().build())); listener.connectionCheckedOut(new ConnectionCheckedOutEvent(connectionId)); listener.connectionPoolClosed(new ConnectionPoolClosedEvent(serverId)); assertThatCode(() -> listener.connectionCheckedIn(new ConnectionCheckedInEvent(connectionId))) - .doesNotThrowAnyException(); + .doesNotThrowAnyException(); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetricsTest.java index a896f59c8a..dc8d60bdc9 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetricsTest.java @@ -101,15 +101,23 @@ void activeAndIdle() { when(connectionPool.connectionCount()).thenReturn(17); when(connectionPool.idleConnectionCount()).thenReturn(10, 9); - assertThat(registry.get("okhttp.pool.connection.count").tags(Tags.of("foo", "bar", "state", "active")).gauge() - .value()).isEqualTo(7.0); - assertThat(registry.get("okhttp.pool.connection.count").tags(Tags.of("foo", "bar", "state", "idle")).gauge() - .value()).isEqualTo(10.0); - - assertThat(registry.get("okhttp.pool.connection.count").tags(Tags.of("foo", "bar", "state", "active")).gauge() - .value()).isEqualTo(8.0); - assertThat(registry.get("okhttp.pool.connection.count").tags(Tags.of("foo", "bar", "state", "idle")).gauge() - .value()).isEqualTo(9.0); + assertThat(registry.get("okhttp.pool.connection.count") + .tags(Tags.of("foo", "bar", "state", "active")) + .gauge() + .value()).isEqualTo(7.0); + assertThat(registry.get("okhttp.pool.connection.count") + .tags(Tags.of("foo", "bar", "state", "idle")) + .gauge() + .value()).isEqualTo(10.0); + + assertThat(registry.get("okhttp.pool.connection.count") + .tags(Tags.of("foo", "bar", "state", "active")) + .gauge() + .value()).isEqualTo(8.0); + assertThat(registry.get("okhttp.pool.connection.count") + .tags(Tags.of("foo", "bar", "state", "idle")) + .gauge() + .value()).isEqualTo(9.0); } @Test @@ -118,7 +126,7 @@ void maxIfGiven() { Tags.of("foo", "bar"), 1234); instance.bindTo(registry); assertThat(registry.get("huge.pool.connection.limit").tags(Tags.of("foo", "bar")).gauge().value()) - .isEqualTo(1234.0); + .isEqualTo(1234.0); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpMetricsEventListenerTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpMetricsEventListenerTest.java index 0fbeb4beeb..9063f95a26 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpMetricsEventListenerTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpMetricsEventListenerTest.java @@ -57,8 +57,12 @@ class OkHttpMetricsEventListenerTest { private MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); - private OkHttpClient client = new OkHttpClient.Builder().eventListener(OkHttpMetricsEventListener - .builder(registry, "okhttp.requests").tags(Tags.of("foo", "bar")).uriMapper(URI_MAPPER).build()).build(); + private OkHttpClient client = new OkHttpClient.Builder() + .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") + .tags(Tags.of("foo", "bar")) + .uriMapper(URI_MAPPER) + .build()) + .build(); @Test void timeSuccessful(@WiremockResolver.Wiremock WireMockServer server) throws IOException { @@ -68,9 +72,10 @@ void timeSuccessful(@WiremockResolver.Wiremock WireMockServer server) throws IOE client.newCall(request).execute().close(); assertThat(registry.get("okhttp.requests") - .tags("foo", "bar", "status", "200", "uri", URI_EXAMPLE_VALUE, "target.host", "localhost", - "target.port", String.valueOf(server.port()), "target.scheme", "http") - .timer().count()).isEqualTo(1L); + .tags("foo", "bar", "status", "200", "uri", URI_EXAMPLE_VALUE, "target.host", "localhost", "target.port", + String.valueOf(server.port()), "target.scheme", "http") + .timer() + .count()).isEqualTo(1L); } @Test @@ -80,11 +85,11 @@ void timeNotFound(@WiremockResolver.Wiremock WireMockServer server) throws IOExc client.newCall(request).execute().close(); - assertThat( - registry.get("okhttp.requests") - .tags("foo", "bar", "status", "404", "uri", "NOT_FOUND", "target.host", "localhost", - "target.port", String.valueOf(server.port()), "target.scheme", "http") - .timer().count()).isEqualTo(1L); + assertThat(registry.get("okhttp.requests") + .tags("foo", "bar", "status", "404", "uri", "NOT_FOUND", "target.host", "localhost", "target.port", + String.valueOf(server.port()), "target.scheme", "http") + .timer() + .count()).isEqualTo(1L); } @Test @@ -93,10 +98,12 @@ void timeFailureDueToTimeout(@WiremockResolver.Wiremock WireMockServer server) { server.stop(); - OkHttpClient client = new OkHttpClient.Builder() - .connectTimeout(1, TimeUnit.MILLISECONDS).eventListener(OkHttpMetricsEventListener - .builder(registry, "okhttp.requests").tags(Tags.of("foo", "bar")).uriMapper(URI_MAPPER).build()) - .build(); + OkHttpClient client = new OkHttpClient.Builder().connectTimeout(1, TimeUnit.MILLISECONDS) + .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") + .tags(Tags.of("foo", "bar")) + .uriMapper(URI_MAPPER) + .build()) + .build(); try { client.newCall(request).execute().close(); @@ -107,52 +114,61 @@ void timeFailureDueToTimeout(@WiremockResolver.Wiremock WireMockServer server) { } assertThat(registry.get("okhttp.requests") - .tags("foo", "bar", "uri", URI_EXAMPLE_VALUE, "status", "IO_ERROR", "target.host", "localhost").timer() - .count()).isEqualTo(1L); + .tags("foo", "bar", "uri", URI_EXAMPLE_VALUE, "status", "IO_ERROR", "target.host", "localhost") + .timer() + .count()).isEqualTo(1L); } @Test void uriTagWorksWithUriPatternHeader(@WiremockResolver.Wiremock WireMockServer server) throws IOException { server.stubFor(any(anyUrl())); Request request = new Request.Builder().url(server.baseUrl() + "/helloworld.txt") - .header(OkHttpMetricsEventListener.URI_PATTERN, "/").build(); + .header(OkHttpMetricsEventListener.URI_PATTERN, "/") + .build(); - client = new OkHttpClient.Builder().eventListener( - OkHttpMetricsEventListener.builder(registry, "okhttp.requests").tags(Tags.of("foo", "bar")).build()) - .build(); + client = new OkHttpClient.Builder() + .eventListener( + OkHttpMetricsEventListener.builder(registry, "okhttp.requests").tags(Tags.of("foo", "bar")).build()) + .build(); client.newCall(request).execute().close(); - assertThat(registry.get("okhttp.requests").tags("foo", "bar", "uri", "/", "status", "200", "target.host", - "localhost", "target.port", String.valueOf(server.port()), "target.scheme", "http").timer().count()) - .isEqualTo(1L); + assertThat(registry.get("okhttp.requests") + .tags("foo", "bar", "uri", "/", "status", "200", "target.host", "localhost", "target.port", + String.valueOf(server.port()), "target.scheme", "http") + .timer() + .count()).isEqualTo(1L); } @Test void uriTagWorksWithUriMapper(@WiremockResolver.Wiremock WireMockServer server) throws IOException { server.stubFor(any(anyUrl())); OkHttpClient client = new OkHttpClient.Builder() - .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") - .uriMapper(req -> req.url().encodedPath()).tags(Tags.of("foo", "bar")).build()) - .build(); + .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") + .uriMapper(req -> req.url().encodedPath()) + .tags(Tags.of("foo", "bar")) + .build()) + .build(); Request request = new Request.Builder().url(server.baseUrl() + "/helloworld.txt").build(); client.newCall(request).execute().close(); assertThat(registry.get("okhttp.requests") - .tags("foo", "bar", "uri", "/helloworld.txt", "status", "200", "target.host", "localhost", - "target.port", String.valueOf(server.port()), "target.scheme", "http") - .timer().count()).isEqualTo(1L); + .tags("foo", "bar", "uri", "/helloworld.txt", "status", "200", "target.host", "localhost", "target.port", + String.valueOf(server.port()), "target.scheme", "http") + .timer() + .count()).isEqualTo(1L); } @Test void contextSpecificTags(@WiremockResolver.Wiremock WireMockServer server) throws IOException { server.stubFor(any(anyUrl())); OkHttpClient client = new OkHttpClient.Builder() - .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") - .tag((req, res) -> Tag.of("another.uri", req.url().encodedPath())).build()) - .build(); + .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") + .tag((req, res) -> Tag.of("another.uri", req.url().encodedPath())) + .build()) + .build(); Request request = new Request.Builder().url(server.baseUrl() + "/helloworld.txt").build(); @@ -160,7 +176,7 @@ void contextSpecificTags(@WiremockResolver.Wiremock WireMockServer server) throw assertThat( registry.get("okhttp.requests").tags("another.uri", "/helloworld.txt", "status", "200").timer().count()) - .isEqualTo(1L); + .isEqualTo(1L); } @Test @@ -168,7 +184,8 @@ void cachedResponsesDoNotLeakMemory(@WiremockResolver.Wiremock WireMockServer se throws IOException { OkHttpMetricsEventListener listener = OkHttpMetricsEventListener.builder(registry, "okhttp.requests").build(); OkHttpClient clientWithCache = new OkHttpClient.Builder().eventListener(listener) - .cache(new Cache(tempDir.toFile(), 55555)).build(); + .cache(new Cache(tempDir.toFile(), 55555)) + .build(); server.stubFor(any(anyUrl()).willReturn(aResponse().withHeader("Cache-Control", "max-age=9600"))); Request request = new Request.Builder().url(server.baseUrl()).build(); @@ -184,7 +201,8 @@ void cachedResponsesDoNotLeakMemory(@WiremockResolver.Wiremock WireMockServer se @Test void requestTagsWithClass(@WiremockResolver.Wiremock WireMockServer server) throws IOException { Request request = new Request.Builder().url(server.baseUrl() + "/helloworld.txt") - .tag(Tags.class, Tags.of("requestTag1", "tagValue1")).build(); + .tag(Tags.class, Tags.of("requestTag1", "tagValue1")) + .build(); testRequestTags(server, request); } @@ -192,7 +210,8 @@ void requestTagsWithClass(@WiremockResolver.Wiremock WireMockServer server) thro @Test void requestTagsWithoutClass(@WiremockResolver.Wiremock WireMockServer server) throws IOException { Request request = new Request.Builder().url(server.baseUrl() + "/helloworld.txt") - .tag(Tags.of("requestTag1", "tagValue1")).build(); + .tag(Tags.of("requestTag1", "tagValue1")) + .build(); testRequestTags(server, request); } @@ -201,18 +220,19 @@ void requestTagsWithoutClass(@WiremockResolver.Wiremock WireMockServer server) t void hostTagCanBeDisabled(@WiremockResolver.Wiremock WireMockServer server) throws IOException { server.stubFor(any(anyUrl())); OkHttpClient client = new OkHttpClient.Builder() - .eventListener( - OkHttpMetricsEventListener.builder(registry, "okhttp.requests").includeHostTag(false).build()) - .build(); + .eventListener( + OkHttpMetricsEventListener.builder(registry, "okhttp.requests").includeHostTag(false).build()) + .build(); Request request = new Request.Builder().url(server.baseUrl()).build(); client.newCall(request).execute().close(); - assertThat( - registry.get("okhttp.requests") - .tags("status", "200", "target.host", "localhost", "target.port", String.valueOf(server.port()), - "target.scheme", "http") - .timer().getId().getTags()).doesNotContain(Tag.of("host", "localhost")); + assertThat(registry.get("okhttp.requests") + .tags("status", "200", "target.host", "localhost", "target.port", String.valueOf(server.port()), + "target.scheme", "http") + .timer() + .getId() + .getTags()).doesNotContain(Tag.of("host", "localhost")); } @Test @@ -223,36 +243,42 @@ void timeWhenRequestIsNull() { listener.time(state); assertThat(registry.get("okhttp.requests") - .tags("uri", "UNKNOWN", "target.host", "UNKNOWN", "target.port", "UNKNOWN", "target.scheme", "UNKNOWN") - .timer().count()).isEqualTo(1L); + .tags("uri", "UNKNOWN", "target.host", "UNKNOWN", "target.port", "UNKNOWN", "target.scheme", "UNKNOWN") + .timer() + .count()).isEqualTo(1L); } @Test void timeWhenRequestIsNullAndRequestTagKeysAreGiven() { OkHttpMetricsEventListener listener = OkHttpMetricsEventListener.builder(registry, "okhttp.requests") - .requestTagKeys("tag1", "tag2").build(); + .requestTagKeys("tag1", "tag2") + .build(); OkHttpMetricsEventListener.CallState state = new OkHttpMetricsEventListener.CallState( registry.config().clock().monotonicTime(), null); listener.time(state); - assertThat(registry.get("okhttp.requests").tags("uri", "UNKNOWN", "tag1", "UNKNOWN", "tag2", "UNKNOWN").timer() - .count()).isEqualTo(1L); + assertThat(registry.get("okhttp.requests") + .tags("uri", "UNKNOWN", "tag1", "UNKNOWN", "tag2", "UNKNOWN") + .timer() + .count()).isEqualTo(1L); } private void testRequestTags(@WiremockResolver.Wiremock WireMockServer server, Request request) throws IOException { server.stubFor(any(anyUrl())); OkHttpClient client = new OkHttpClient.Builder() - .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") - .uriMapper(req -> req.url().encodedPath()).tags(Tags.of("foo", "bar")).build()) - .build(); + .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") + .uriMapper(req -> req.url().encodedPath()) + .tags(Tags.of("foo", "bar")) + .build()) + .build(); client.newCall(request).execute().close(); assertThat(registry.get("okhttp.requests") - .tags("foo", "bar", "uri", "/helloworld.txt", "status", "200", "requestTag1", "tagValue1", - "target.host", "localhost", "target.port", String.valueOf(server.port()), "target.scheme", - "http") - .timer().count()).isEqualTo(1L); + .tags("foo", "bar", "uri", "/helloworld.txt", "status", "200", "requestTag1", "tagValue1", "target.host", + "localhost", "target.port", String.valueOf(server.port()), "target.scheme", "http") + .timer() + .count()).isEqualTo(1L); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/system/ProcessorMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/system/ProcessorMetricsTest.java index ad1c285401..5918b45dce 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/system/ProcessorMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/system/ProcessorMetricsTest.java @@ -78,7 +78,7 @@ void openJ9CpuMetrics() { assertThat(registry.get("system.cpu.usage").gauge().value()).isPositive(); assertThat(registry.get("process.cpu.usage").gauge().value()).isGreaterThanOrEqualTo(-1); await().atMost(Duration.ofMillis(200)) - .untilAsserted(() -> assertThat(registry.get("process.cpu.usage").gauge().value()).isPositive()); + .untilAsserted(() -> assertThat(registry.get("process.cpu.usage").gauge().value()).isPositive()); } private boolean isOpenJ9() { diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/tomcat/TomcatMetricsTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/tomcat/TomcatMetricsTest.java index 751b4e5dec..3972d330df 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/tomcat/TomcatMetricsTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/binder/tomcat/TomcatMetricsTest.java @@ -158,7 +158,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I CloseableHttpResponse response1 = httpClient.execute(post); CloseableHttpResponse response2 = httpClient - .execute(new HttpGet("http://localhost:" + this.port + "/0/no-get")); + .execute(new HttpGet("http://localhost:" + this.port + "/0/no-get")); long expectedSentBytes = response1.getEntity().getContentLength() + response2.getEntity().getContentLength(); @@ -191,7 +191,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I CloseableHttpResponse response1 = httpClient.execute(post); CloseableHttpResponse response2 = httpClient - .execute(new HttpGet("http://localhost:" + this.port + "/0/no-get")); + .execute(new HttpGet("http://localhost:" + this.port + "/0/no-get")); long expectedSentBytes = response1.getEntity().getContentLength() + response2.getEntity().getContentLength(); @@ -233,7 +233,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) CloseableHttpResponse response1 = httpClient.execute(post); CloseableHttpResponse response2 = httpClient - .execute(new HttpGet("http://localhost:" + this.port + "/1")); + .execute(new HttpGet("http://localhost:" + this.port + "/1")); FunctionTimer servlet0 = registry.get("tomcat.servlet.request").tag("name", "servlet0").functionTimer(); FunctionTimer servlet1 = registry.get("tomcat.servlet.request").tag("name", "servlet1").functionTimer(); @@ -294,7 +294,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) CloseableHttpResponse response1 = httpClient.execute(post); CloseableHttpResponse response2 = httpClient - .execute(new HttpGet("http://localhost:" + this.port + "/1")); + .execute(new HttpGet("http://localhost:" + this.port + "/1")); FunctionTimer servlet0 = registry.get("tomcat.servlet.request").tag("name", "servlet0").functionTimer(); FunctionTimer servlet1 = registry.get("tomcat.servlet.request").tag("name", "servlet1").functionTimer(); @@ -347,7 +347,7 @@ private void checkMbeansInitialState() { assertThat(registry.get("tomcat.global.error").functionCounter().count()).isEqualTo(0.0); assertThat(registry.get("tomcat.global.request").functionTimer().count()).isEqualTo(0.0); assertThat(registry.get("tomcat.global.request").functionTimer().totalTime(TimeUnit.MILLISECONDS)) - .isEqualTo(0.0); + .isEqualTo(0.0); assertThat(registry.get("tomcat.global.request.max").timeGauge().value(TimeUnit.MILLISECONDS)).isEqualTo(0.0); assertThat(registry.get("tomcat.threads.config.max").gauge().value()).isGreaterThan(0.0); assertThat(registry.get("tomcat.threads.busy").gauge().value()).isGreaterThanOrEqualTo(0.0); @@ -362,14 +362,14 @@ private void checkMbeansInitialState() { private void checkMbeansAfterRequests(long expectedSentBytes) { await().atMost(5, TimeUnit.SECONDS) - .until(() -> registry.get("tomcat.global.sent").functionCounter().count() == expectedSentBytes); + .until(() -> registry.get("tomcat.global.sent").functionCounter().count() == expectedSentBytes); assertThat(registry.get("tomcat.global.received").functionCounter().count()).isEqualTo(10.0); assertThat(registry.get("tomcat.global.error").functionCounter().count()).isEqualTo(1.0); assertThat(registry.get("tomcat.global.request").functionTimer().count()).isEqualTo(2.0); assertThat(registry.get("tomcat.global.request").functionTimer().totalTime(TimeUnit.MILLISECONDS)) - .isGreaterThanOrEqualTo(PROCESSING_TIME_IN_MILLIS); + .isGreaterThanOrEqualTo(PROCESSING_TIME_IN_MILLIS); assertThat(registry.get("tomcat.global.request.max").timeGauge().value(TimeUnit.MILLISECONDS)) - .isGreaterThanOrEqualTo(PROCESSING_TIME_IN_MILLIS); + .isGreaterThanOrEqualTo(PROCESSING_TIME_IN_MILLIS); assertThat(registry.get("tomcat.threads.config.max").gauge().value()).isGreaterThan(0.0); assertThat(registry.get("tomcat.threads.busy").gauge().value()).isGreaterThanOrEqualTo(0.0); assertThat(registry.get("tomcat.threads.current").gauge().value()).isGreaterThan(0.0); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/composite/CompositeMeterRegistryTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/composite/CompositeMeterRegistryTest.java index 21798ddf4d..4d95274858 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/composite/CompositeMeterRegistryTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/composite/CompositeMeterRegistryTest.java @@ -379,16 +379,16 @@ void stopTrackingMetersThatAreRemoved() { registry.add(counting); Meter custom = Meter - .builder("custom", Meter.Type.COUNTER, singletonList(new Measurement(() -> 1.0, Statistic.COUNT))) - .register(registry); + .builder("custom", Meter.Type.COUNTER, singletonList(new Measurement(() -> 1.0, Statistic.COUNT))) + .register(registry); counting.publish(); registry.remove(custom); counting.publish(); assertThat(counting.count(custom)).isEqualTo(1); AtomicInteger tgObj = new AtomicInteger(1); - registry.more().timeGauge("timegauge", Tags.empty(), tgObj, TimeUnit.MILLISECONDS, - AtomicInteger::incrementAndGet); + registry.more() + .timeGauge("timegauge", Tags.empty(), tgObj, TimeUnit.MILLISECONDS, AtomicInteger::incrementAndGet); TimeGauge timeGauge = registry.get("timegauge").timeGauge(); counting.publish(); registry.remove(timeGauge); @@ -435,8 +435,9 @@ void stopTrackingMetersThatAreRemoved() { assertThat(counting.count(ltt)).isEqualTo(1); AtomicInteger ftObj = new AtomicInteger(1); - registry.more().timer("functiontimer", Tags.empty(), ftObj, AtomicInteger::incrementAndGet, AtomicInteger::get, - TimeUnit.MILLISECONDS); + registry.more() + .timer("functiontimer", Tags.empty(), ftObj, AtomicInteger::incrementAndGet, AtomicInteger::get, + TimeUnit.MILLISECONDS); FunctionTimer functionTimer = registry.get("functiontimer").functionTimer(); counting.publish(); registry.remove(functionTimer); @@ -465,8 +466,9 @@ void meterRegistrationShouldWorkConcurrently() throws InterruptedException { for (int i = 0; i < count; i++) { int tagValue = i % tagCount; executor.execute(() -> { - Counter counter = Counter.builder(meterName).tag(tagName, String.valueOf(tagValue)) - .register(this.composite); + Counter counter = Counter.builder(meterName) + .tag(tagName, String.valueOf(tagValue)) + .register(this.composite); counter.increment(); }); } @@ -474,7 +476,7 @@ void meterRegistrationShouldWorkConcurrently() throws InterruptedException { assertThat(executor.awaitTermination(1L, TimeUnit.SECONDS)).isTrue(); for (int i = 0; i < tagCount; i++) { assertThat(this.composite.find(meterName).tag(tagName, String.valueOf(i)).counter().count()) - .isEqualTo(count / tagCount); + .isEqualTo(count / tagCount); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/config/DurationValidatorTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/config/DurationValidatorTest.java index e0ae03e1b9..1abc6d229b 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/config/DurationValidatorTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/config/DurationValidatorTest.java @@ -50,7 +50,7 @@ void parseIso8601Duration() { assertThat(validate("dur", "PT10H").get()).isEqualByComparingTo(Duration.ofHours(10)); assertThat(validate("dur", "P2D").get()).isEqualByComparingTo(Duration.ofDays(2)); assertThat(validate("dur", "P2DT3H4M").get()) - .isEqualByComparingTo(Duration.ofDays(2).plus(Duration.ofHours(3)).plus(Duration.ofMinutes(4))); + .isEqualByComparingTo(Duration.ofDays(2).plus(Duration.ofHours(3)).plus(Duration.ofMinutes(4))); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/config/ValidatedTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/config/ValidatedTest.java index a5873e9d2d..e280c3becd 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/config/ValidatedTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/config/ValidatedTest.java @@ -34,8 +34,8 @@ void mapInvalid() { @Test void combine() { - Validated validated = Validated.valid("simple.step", Duration.ofSeconds(1)).and( - Validated.invalid("simple.mode", "BAD", "must be 'STEP' or 'CUMULATIVE'", InvalidReason.MALFORMED)); + Validated validated = Validated.valid("simple.step", Duration.ofSeconds(1)) + .and(Validated.invalid("simple.mode", "BAD", "must be 'STEP' or 'CUMULATIVE'", InvalidReason.MALFORMED)); assertThat(validated.isValid()).isFalse(); } @@ -43,10 +43,10 @@ void combine() { @Test void orThrowOnEitherWithInvalidThrows() { Validated valid = Validated.valid("prop", "good") - .and(Validated.invalid("prop2", "bad", "must be good", InvalidReason.MALFORMED)); + .and(Validated.invalid("prop2", "bad", "must be good", InvalidReason.MALFORMED)); assertThatThrownBy(valid::orThrow).isInstanceOf(ValidationException.class) - .hasMessage("prop2 was 'bad' but it must be good"); + .hasMessage("prop2 was 'bad' but it must be good"); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/HistogramGaugesTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/HistogramGaugesTest.java index 6c84f1a174..d5907ee15e 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/HistogramGaugesTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/HistogramGaugesTest.java @@ -55,8 +55,10 @@ public Meter.Id map(Meter.Id id) { } }); - Timer.builder("my.timer").serviceLevelObjectives(Duration.ofMillis(1)).publishPercentiles(0.95) - .register(registry); + Timer.builder("my.timer") + .serviceLevelObjectives(Duration.ofMillis(1)) + .publishPercentiles(0.95) + .register(registry); registry.get("MYPREFIX.my.timer.percentile").tag("phi", "0.95").gauge(); registry.get("MYPREFIX.my.timer.histogram").tag("le", "0.001").gauge(); @@ -66,11 +68,13 @@ public Meter.Id map(Meter.Id id) { void histogramsContainLongMaxValue() { MeterRegistry registry = new SimpleMeterRegistry(); - Timer timer = Timer.builder("my.timer").serviceLevelObjectives(Duration.ofNanos(Long.MAX_VALUE)) - .register(registry); + Timer timer = Timer.builder("my.timer") + .serviceLevelObjectives(Duration.ofNanos(Long.MAX_VALUE)) + .register(registry); DistributionSummary distributionSummary = DistributionSummary.builder("my.distribution") - .serviceLevelObjectives(Double.POSITIVE_INFINITY).register(registry); + .serviceLevelObjectives(Double.POSITIVE_INFINITY) + .register(registry); HistogramGauges distributionGauges = HistogramGauges.registerWithCommonFormat(distributionSummary, registry); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowFixedBoundaryHistogramTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowFixedBoundaryHistogramTest.java index c9ce4d7fcb..76245d54de 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowFixedBoundaryHistogramTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowFixedBoundaryHistogramTest.java @@ -34,7 +34,8 @@ void binarySearchForTail() { private void assertTailSearch(int search, int expectedIndex, double... buckets) { DistributionStatisticConfig statisticConfig = DistributionStatisticConfig.builder() - .serviceLevelObjectives(buckets).build(); + .serviceLevelObjectives(buckets) + .build(); try (TimeWindowFixedBoundaryHistogram histogram = new TimeWindowFixedBoundaryHistogram(Clock.SYSTEM, statisticConfig.merge(DistributionStatisticConfig.DEFAULT), false)) { TimeWindowFixedBoundaryHistogram.FixedBoundaryHistogram bucket = histogram.newBucket(); @@ -45,8 +46,11 @@ private void assertTailSearch(int search, int expectedIndex, double... buckets) @Test void histogramsAreCumulative() { try (TimeWindowFixedBoundaryHistogram histogram = new TimeWindowFixedBoundaryHistogram(new MockClock(), - DistributionStatisticConfig.builder().serviceLevelObjectives(3.0, 6, 7).bufferLength(1).build() - .merge(DistributionStatisticConfig.DEFAULT), + DistributionStatisticConfig.builder() + .serviceLevelObjectives(3.0, 6, 7) + .bufferLength(1) + .build() + .merge(DistributionStatisticConfig.DEFAULT), false)) { histogram.recordDouble(3); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowPercentileHistogramTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowPercentileHistogramTest.java index 191f464af5..04764c32fd 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowPercentileHistogramTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowPercentileHistogramTest.java @@ -30,8 +30,10 @@ class TimeWindowPercentileHistogramTest { @Test void histogramsAreCumulative() { try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), - DistributionStatisticConfig.builder().serviceLevelObjectives(3.0, 6, 7).build() - .merge(DistributionStatisticConfig.DEFAULT), + DistributionStatisticConfig.builder() + .serviceLevelObjectives(3.0, 6, 7) + .build() + .merge(DistributionStatisticConfig.DEFAULT), false)) { histogram.recordDouble(3); @@ -52,8 +54,11 @@ void histogramsAreCumulative() { @Test void sampleValueAboveMaximumExpectedValue() { try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), - DistributionStatisticConfig.builder().serviceLevelObjectives(3.0).maximumExpectedValue(2.0).build() - .merge(DistributionStatisticConfig.DEFAULT), + DistributionStatisticConfig.builder() + .serviceLevelObjectives(3.0) + .maximumExpectedValue(2.0) + .build() + .merge(DistributionStatisticConfig.DEFAULT), false)) { histogram.recordDouble(3); @@ -64,8 +69,10 @@ void sampleValueAboveMaximumExpectedValue() { @Test void recordValuesThatExceedTheDynamicRange() { try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), - DistributionStatisticConfig.builder().serviceLevelObjectives(Double.POSITIVE_INFINITY).build() - .merge(DistributionStatisticConfig.DEFAULT), + DistributionStatisticConfig.builder() + .serviceLevelObjectives(Double.POSITIVE_INFINITY) + .build() + .merge(DistributionStatisticConfig.DEFAULT), false)) { // Regardless of the imputed dynamic bound for the underlying histogram, @@ -74,17 +81,19 @@ void recordValuesThatExceedTheDynamicRange() { histogram.recordDouble(Double.MAX_VALUE); assertThat(histogram.takeSnapshot(0, 0, 0).histogramCounts()) - .containsExactly(new CountAtBucket(Double.POSITIVE_INFINITY, 0)); + .containsExactly(new CountAtBucket(Double.POSITIVE_INFINITY, 0)); } } @Test void percentiles() { try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), - DistributionStatisticConfig.builder().percentiles(0.5, 0.9, 0.95) - .minimumExpectedValue(millisToUnit(1, TimeUnit.NANOSECONDS)) - .maximumExpectedValue(secondsToUnit(30, TimeUnit.NANOSECONDS)).build() - .merge(DistributionStatisticConfig.DEFAULT), + DistributionStatisticConfig.builder() + .percentiles(0.5, 0.9, 0.95) + .minimumExpectedValue(millisToUnit(1, TimeUnit.NANOSECONDS)) + .maximumExpectedValue(secondsToUnit(30, TimeUnit.NANOSECONDS)) + .build() + .merge(DistributionStatisticConfig.DEFAULT), false)) { for (long i = 1; i <= 10; i++) { @@ -92,16 +101,18 @@ void percentiles() { } assertThat(histogram.takeSnapshot(0, 0, 0).percentileValues()) - .anyMatch(p -> percentileValueIsApproximately(p, 0.5, 5e6)) - .anyMatch(p -> percentileValueIsApproximately(p, 0.9, 9e6)) - .anyMatch(p -> percentileValueIsApproximately(p, 0.95, 10e6)); + .anyMatch(p -> percentileValueIsApproximately(p, 0.5, 5e6)) + .anyMatch(p -> percentileValueIsApproximately(p, 0.9, 9e6)) + .anyMatch(p -> percentileValueIsApproximately(p, 0.95, 10e6)); } } @Test void percentilesWithNoSamples() { - DistributionStatisticConfig config = DistributionStatisticConfig.builder().percentiles(0.5).build() - .merge(DistributionStatisticConfig.DEFAULT); + DistributionStatisticConfig config = DistributionStatisticConfig.builder() + .percentiles(0.5) + .build() + .merge(DistributionStatisticConfig.DEFAULT); try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), config, false)) { @@ -114,8 +125,10 @@ void percentilesWithNoSamples() { @Test void percentilesChangeWithMoreRecentSamples() { - DistributionStatisticConfig config = DistributionStatisticConfig.builder().percentiles(0.5).build() - .merge(DistributionStatisticConfig.DEFAULT); + DistributionStatisticConfig config = DistributionStatisticConfig.builder() + .percentiles(0.5) + .build() + .merge(DistributionStatisticConfig.DEFAULT); try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), config, false)) { @@ -126,7 +139,7 @@ void percentilesChangeWithMoreRecentSamples() { // baseline median assertThat(histogram.takeSnapshot(0, 0, 0).percentileValues()) - .anyMatch(p -> percentileValueIsApproximately(p, 0.5, 5e6)); + .anyMatch(p -> percentileValueIsApproximately(p, 0.5, 5e6)); for (int i = 11; i <= 20; i++) { histogram.recordLong((long) millisToUnit(i, TimeUnit.NANOSECONDS)); @@ -134,7 +147,7 @@ void percentilesChangeWithMoreRecentSamples() { // median should have moved after seeing 10 more samples assertThat(histogram.takeSnapshot(0, 0, 0).percentileValues()) - .anyMatch(p -> percentileValueIsApproximately(p, 0.5, 10e6)); + .anyMatch(p -> percentileValueIsApproximately(p, 0.5, 10e6)); } } @@ -148,8 +161,11 @@ private boolean percentileValueIsApproximately(ValueAtPercentile vp, double perc @Test void timeBasedSlidingWindow() { final DistributionStatisticConfig config = DistributionStatisticConfig.builder() - .percentiles(0.0, 0.5, 0.75, 0.9, 0.99, 0.999, 1.0).expiry(Duration.ofSeconds(4)).bufferLength(4) - .build().merge(DistributionStatisticConfig.DEFAULT); + .percentiles(0.0, 0.5, 0.75, 0.9, 0.99, 0.999, 1.0) + .expiry(Duration.ofSeconds(4)) + .bufferLength(4) + .build() + .merge(DistributionStatisticConfig.DEFAULT); MockClock clock = new MockClock(); // Start from 0 for more comprehensive timing calculation. diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowRotationTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowRotationTest.java index b8e1dcbf58..72fbd1df0f 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowRotationTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowRotationTest.java @@ -38,16 +38,16 @@ private static void expectValidationFailure(Class newHistogram(histogramType, new MockClock(), badConfig.merge(DistributionStatisticConfig.DEFAULT))) - .hasRootCauseExactlyInstanceOf(InvalidConfigurationException.class) - .satisfies(cause -> assertThat(cause.getCause()) - .hasMessageStartingWith("Invalid distribution configuration:")); + .hasRootCauseExactlyInstanceOf(InvalidConfigurationException.class) + .satisfies(cause -> assertThat(cause.getCause()) + .hasMessageStartingWith("Invalid distribution configuration:")); } private static AbstractTimeWindowHistogram newHistogram( Class> histogramType, MockClock clock, DistributionStatisticConfig config) throws Exception { return histogramType.getDeclaredConstructor(Clock.class, DistributionStatisticConfig.class, Boolean.TYPE) - .newInstance(clock, config, false); + .newInstance(clock, config, false); } @ParameterizedTest diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/dropwizard/DropwizardMeterRegistryTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/dropwizard/DropwizardMeterRegistryTest.java index 2d7c261346..3e889f3c4b 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/dropwizard/DropwizardMeterRegistryTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/dropwizard/DropwizardMeterRegistryTest.java @@ -68,16 +68,19 @@ void gaugeOnNullValue() { @Test void customMeasurementsThatDifferOnlyInTagValue() { - Meter.builder("my.custom", Meter.Type.GAUGE, - Arrays.asList(new Measurement(() -> 1.0, Statistic.COUNT), new Measurement(() -> 2.0, Statistic.TOTAL))) - .register(registry); + Meter + .builder("my.custom", Meter.Type.GAUGE, + Arrays.asList(new Measurement(() -> 1.0, Statistic.COUNT), + new Measurement(() -> 2.0, Statistic.TOTAL))) + .register(registry); } @Issue("#370") @Test void serviceLevelObjectivesOnlyNoPercentileHistogram() { - DistributionSummary summary = DistributionSummary.builder("my.summary").serviceLevelObjectives(1.0, 2) - .register(registry); + DistributionSummary summary = DistributionSummary.builder("my.summary") + .serviceLevelObjectives(1.0, 2) + .register(registry); summary.record(1); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/logging/LoggingMeterRegistryTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/logging/LoggingMeterRegistryTest.java index f6ebdb782b..8e4b7daefc 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/logging/LoggingMeterRegistryTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/logging/LoggingMeterRegistryTest.java @@ -46,7 +46,8 @@ void defaultMeterIdPrinter() { @Test void customMeterIdPrinter() { LoggingMeterRegistry registry = LoggingMeterRegistry.builder(LoggingRegistryConfig.DEFAULT) - .meterIdPrinter(meter -> meter.getId().getName()).build(); + .meterIdPrinter(meter -> meter.getId().getName()) + .build(); Counter counter = registry.counter("my.gauage", "tag-1", "tag-2"); LoggingMeterRegistry.Printer printer = registry.new Printer(counter); @@ -96,8 +97,11 @@ void writeMeterMultipleValues() { Measurement m1 = new Measurement(() -> 5d, Statistic.VALUE); Measurement m2 = new Measurement(() -> 1023d, Statistic.MAX); Measurement m3 = new Measurement(() -> 1100d, Statistic.TOTAL_TIME); - Meter meter = Meter.builder("sheepWatch", Meter.Type.OTHER, Arrays.asList(m1, m2, m3)).tag("color", "black") - .description("Meter for shepherds.").baseUnit("sheep").register(registry); + Meter meter = Meter.builder("sheepWatch", Meter.Type.OTHER, Arrays.asList(m1, m2, m3)) + .tag("color", "black") + .description("Meter for shepherds.") + .baseUnit("sheep") + .register(registry); LoggingMeterRegistry.Printer printer = registry.new Printer(meter); assertThat(registry.writeMeter(meter, printer)).isEqualTo(expectedResult); } @@ -112,7 +116,8 @@ void writeMeterByteValues() { Measurement m4 = new Measurement(() -> (double) (1 << 23), Statistic.VALUE); Measurement m5 = new Measurement(() -> (double) (1 << 30), Statistic.VALUE); Meter meter = Meter.builder("bus-throughput", Meter.Type.OTHER, Arrays.asList(m1, m2, m3, m4, m5)) - .baseUnit(BaseUnits.BYTES).register(registry); + .baseUnit(BaseUnits.BYTES) + .register(registry); LoggingMeterRegistry.Printer printer = registry.new Printer(meter); assertThat(registry.writeMeter(meter, printer)).isEqualTo(expectedResult); } diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/push/PushMeterRegistryTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/push/PushMeterRegistryTest.java index 2596f77e08..7c5e51f93f 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/push/PushMeterRegistryTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/push/PushMeterRegistryTest.java @@ -67,7 +67,8 @@ void cleanUp() { void whenUncaughtExceptionInPublish_taskStillScheduled() throws InterruptedException { pushMeterRegistry.start(threadFactory); assertThat(latch.await(500, TimeUnit.MILLISECONDS)) - .as("publish should continue to be scheduled even if an uncaught exception is thrown").isTrue(); + .as("publish should continue to be scheduled even if an uncaught exception is thrown") + .isTrue(); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/search/RequiredSearchTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/search/RequiredSearchTest.java index 494e5b9973..27e0fbab61 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/search/RequiredSearchTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/search/RequiredSearchTest.java @@ -56,97 +56,98 @@ void allMetersWithTag() { assertThat(RequiredSearch.in(registry).tag("k2", "v2").meters()).hasSize(1); assertThatThrownBy(() -> RequiredSearch.in(registry).tag("k2", "WRONG").meters()) - .isInstanceOf(MeterNotFoundException.class); + .isInstanceOf(MeterNotFoundException.class); assertThatThrownBy(() -> RequiredSearch.in(registry).tag("WRONG", "v2").meters()) - .isInstanceOf(MeterNotFoundException.class); + .isInstanceOf(MeterNotFoundException.class); assertThat(RequiredSearch.in(registry).tags("k2", "v2").meters()).hasSize(1); assertThat(RequiredSearch.in(registry).tags("k", "v", "k2", "v2").meters()).hasSize(1); assertThatThrownBy(() -> RequiredSearch.in(registry).tags("k", "k2", "k3")) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); } @Test void multipleNamesMatchMultipleWrongTypes() { assertThatThrownBy(() -> RequiredSearch.in(registry).name(n -> n.startsWith("my")).gauge()) - .isInstanceOf(MeterNotFoundException.class) - .hasMessageContaining("Meters with names ['my.counter', 'my.other.counter', 'my.timer'] were found") - .hasMessageContaining("Expected to find a gauge. Types found were [counter, timer]"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("Meters with names ['my.counter', 'my.other.counter', 'my.timer'] were found") + .hasMessageContaining("Expected to find a gauge. Types found were [counter, timer]"); } @Test void nameMatchesSingleWrongType() { assertThatThrownBy(() -> RequiredSearch.in(registry).name(n -> n.contains("counter")).gauge()) - .isInstanceOf(MeterNotFoundException.class) - .hasMessageContaining("Expected to find a gauge. The only type found was a counter"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("Expected to find a gauge. The only type found was a counter"); } @Test void noMatchingExactName() { assertThatThrownBy(() -> RequiredSearch.in(registry).name("does.not.exist").counter()) - .isInstanceOf(MeterNotFoundException.class) - .hasMessageContaining("No meter with name 'does.not.exist' was found") - .hasMessageContaining("Meters with type counter were found"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("No meter with name 'does.not.exist' was found") + .hasMessageContaining("Meters with type counter were found"); } @Test void noMatchingNamePredicate() { assertThatThrownBy(() -> RequiredSearch.in(registry).name(n -> n.equals("does.not.exist")).counter()) - .isInstanceOf(MeterNotFoundException.class) - .hasMessageContaining("No meter that matches the name predicate was found") - .hasMessageContaining("Meters with type counter were found"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("No meter that matches the name predicate was found") + .hasMessageContaining("Meters with type counter were found"); } @Test void matchingAndNoMatchingRequiredTagKey() { assertThatThrownBy(() -> RequiredSearch.in(registry).tagKeys("k", "k2").timer()) - .isInstanceOf(MeterNotFoundException.class) - .hasMessageContaining("A meter with name 'my.timer' has the required tag 'k'") - .hasMessageContaining("No meters have the required tag 'k2'"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("A meter with name 'my.timer' has the required tag 'k'") + .hasMessageContaining("No meters have the required tag 'k2'"); } @Test void multipleMatchingRequiredTagKey() { assertThatThrownBy(() -> RequiredSearch.in(registry).tagKeys("k", "does.not.exist").counter()) - .isInstanceOf(MeterNotFoundException.class) - .hasMessageContaining("Meters with names ['my.counter', 'my.other.counter'] have the required tag 'k'"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("Meters with names ['my.counter', 'my.other.counter'] have the required tag 'k'"); } @Test void multipleNonMatchingRequiredTag() { assertThatThrownBy(() -> RequiredSearch.in(registry).name("my.counter").tag("k", "does.not.exist").counter()) - .isInstanceOf(MeterNotFoundException.class).hasMessageContaining( - "No meters have a tag 'k' with value 'does.not.exist'. The only value found was 'v'"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("No meters have a tag 'k' with value 'does.not.exist'. The only value found was 'v'"); } @Test void multipleNonMatchingRequiredTagWithMultipleOtherValues() { assertThatThrownBy(() -> RequiredSearch.in(registry).tag("k2", "does.not.exist").counter()) - .isInstanceOf(MeterNotFoundException.class).hasMessageContaining( - "No meters have a tag 'k2' with value 'does.not.exist'. Tag values found were ['v2', 'v3']"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining( + "No meters have a tag 'k2' with value 'does.not.exist'. Tag values found were ['v2', 'v3']"); } @Test void singleMatchingRequiredTag() { assertThatThrownBy(() -> RequiredSearch.in(registry).tag("k", "v").tagKeys("does.not.exist").timer()) - .isInstanceOf(MeterNotFoundException.class) - .hasMessageContaining("A meter with name 'my.timer' has a tag 'k' with value 'v'"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("A meter with name 'my.timer' has a tag 'k' with value 'v'"); } @Test void multipleMatchingRequiredTag() { assertThatThrownBy(() -> RequiredSearch.in(registry).tag("k", "v").tagKeys("does.not.exist").counter()) - .isInstanceOf(MeterNotFoundException.class).hasMessageContaining( - "Meters with names ['my.counter', 'my.other.counter'] have a tag 'k' with value 'v'"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("Meters with names ['my.counter', 'my.other.counter'] have a tag 'k' with value 'v'"); } @Test void noMatchingType() { assertThatThrownBy(() -> RequiredSearch.in(registry).functionCounter()) - .isInstanceOf(MeterNotFoundException.class) - .hasMessageContaining("No meters with type function counter were found"); + .isInstanceOf(MeterNotFoundException.class) + .hasMessageContaining("No meters with type function counter were found"); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/search/SearchTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/search/SearchTest.java index aeb5592349..68b90c59cc 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/search/SearchTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/search/SearchTest.java @@ -59,7 +59,7 @@ void allMetersWithTag() { assertThat(Search.in(registry).tags("k", "v", "k2", "v2").meters()).hasSize(1); assertThatThrownBy(() -> Search.in(registry).tags("k", "k2", "k3")) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/simple/SimpleMeterRegistryTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/simple/SimpleMeterRegistryTest.java index e6de23e509..3f982165ea 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/simple/SimpleMeterRegistryTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/simple/SimpleMeterRegistryTest.java @@ -59,8 +59,9 @@ class SimpleMeterRegistryTest { @Issue("#370") @Test void serviceLevelObjectivesOnlyNoPercentileHistogram() { - DistributionSummary summary = DistributionSummary.builder("my.summary").serviceLevelObjectives(1.0, 2) - .register(registry); + DistributionSummary summary = DistributionSummary.builder("my.summary") + .serviceLevelObjectives(1.0, 2) + .register(registry); summary.record(1); @@ -129,11 +130,15 @@ void stringRepresentationOfMetersShouldBeOk() { Counter incorrectAnswers = Counter.builder("answers").tag("correct", "false").register(registry); incorrectAnswers.increment(); - Timer latency = Timer.builder("latency").tag("service", "test").tag("method", "GET").tag("uri", "/api/people") - .register(registry); + Timer latency = Timer.builder("latency") + .tag("service", "test") + .tag("method", "GET") + .tag("uri", "/api/people") + .register(registry); - DistributionSummary requestSize = DistributionSummary.builder("request.size").baseUnit("bytes") - .register(registry); + DistributionSummary requestSize = DistributionSummary.builder("request.size") + .baseUnit("bytes") + .register(registry); for (int i = 0; i < 10; i++) { latency.record(Duration.ofMillis(20 + i * 2)); @@ -152,10 +157,13 @@ void stringRepresentationOfMetersShouldBeOk() { AtomicLong cacheLatency = new AtomicLong(100); FunctionTimer.builder("cache.latency", cacheLatency, obj -> 5, AtomicLong::doubleValue, MILLISECONDS) - .register(registry); + .register(registry); - Meter.builder("custom.meter", Meter.Type.OTHER, Arrays.asList(new Measurement(() -> 42d, Statistic.VALUE), - new Measurement(() -> 21d, Statistic.UNKNOWN))).register(registry); + Meter + .builder("custom.meter", Meter.Type.OTHER, + Arrays.asList(new Measurement(() -> 42d, Statistic.VALUE), + new Measurement(() -> 21d, Statistic.UNKNOWN))) + .register(registry); assertThat(registry.getMetersAsString()).isEqualTo("answers(COUNTER)[correct='true']; count=2.0\n" + "answers(COUNTER)[correct='false']; count=1.0\n" diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/step/StepMeterRegistryTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/step/StepMeterRegistryTest.java index 1649d92ae2..5cc31a308d 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/step/StepMeterRegistryTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/step/StepMeterRegistryTest.java @@ -70,8 +70,9 @@ protected TimeUnit getBaseTimeUnit() { @Issue("#370") @Test void serviceLevelObjectivesOnlyNoPercentileHistogram() { - DistributionSummary summary = DistributionSummary.builder("my.summary").serviceLevelObjectives(1.0, 2) - .register(registry); + DistributionSummary summary = DistributionSummary.builder("my.summary") + .serviceLevelObjectives(1.0, 2) + .register(registry); summary.record(1); @@ -104,14 +105,20 @@ void publishOneLastTimeOnClose() { @Issue("#1993") @Test void timerMaxValueDecays() { - Timer timerStep1Length2 = Timer.builder("timer1x2").distributionStatisticBufferLength(2) - .distributionStatisticExpiry(config.step()).register(registry); - - Timer timerStep2Length2 = Timer.builder("timer2x2").distributionStatisticBufferLength(2) - .distributionStatisticExpiry(config.step().multipliedBy(2)).register(registry); - - Timer timerStep1Length6 = Timer.builder("timer1x6").distributionStatisticBufferLength(6) - .distributionStatisticExpiry(config.step()).register(registry); + Timer timerStep1Length2 = Timer.builder("timer1x2") + .distributionStatisticBufferLength(2) + .distributionStatisticExpiry(config.step()) + .register(registry); + + Timer timerStep2Length2 = Timer.builder("timer2x2") + .distributionStatisticBufferLength(2) + .distributionStatisticExpiry(config.step().multipliedBy(2)) + .register(registry); + + Timer timerStep1Length6 = Timer.builder("timer1x6") + .distributionStatisticBufferLength(6) + .distributionStatisticExpiry(config.step()) + .register(registry); List timers = Arrays.asList(timerStep1Length2, timerStep2Length2, timerStep1Length6); diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/util/HierarchicalNameMapperTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/util/HierarchicalNameMapperTest.java index 7801e0c901..9a09756452 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/util/HierarchicalNameMapperTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/util/HierarchicalNameMapperTest.java @@ -42,7 +42,7 @@ void buildHierarchicalNameFromDimensionalId() { @Test void noTags() { assertThat(mapper.toHierarchicalName(id("http.requests"), NamingConvention.camelCase)) - .isEqualTo("httpRequests"); + .isEqualTo("httpRequests"); } private Meter.Id id(String name, String... tags) { diff --git a/micrometer-core/src/test/java/io/micrometer/core/ipc/http/HttpUrlConnectionSenderTests.java b/micrometer-core/src/test/java/io/micrometer/core/ipc/http/HttpUrlConnectionSenderTests.java index 657f06f639..11f1f6735f 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/ipc/http/HttpUrlConnectionSenderTests.java +++ b/micrometer-core/src/test/java/io/micrometer/core/ipc/http/HttpUrlConnectionSenderTests.java @@ -36,7 +36,7 @@ void customReadTimeoutHonored(WireMockRuntimeInfo wmInfo) { stubFor(any(urlEqualTo("/metrics")).willReturn(ok().withFixedDelay(5))); assertThatExceptionOfType(SocketTimeoutException.class) - .isThrownBy(() -> httpSender.post(wmInfo.getHttpBaseUrl() + "/metrics").send()); + .isThrownBy(() -> httpSender.post(wmInfo.getHttpBaseUrl() + "/metrics").send()); } } diff --git a/micrometer-core/src/test/java/io/micrometer/core/ipc/http/OkHttpSenderTests.java b/micrometer-core/src/test/java/io/micrometer/core/ipc/http/OkHttpSenderTests.java index 3eb8c0ca0f..6abc58cf14 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/ipc/http/OkHttpSenderTests.java +++ b/micrometer-core/src/test/java/io/micrometer/core/ipc/http/OkHttpSenderTests.java @@ -37,7 +37,7 @@ void customReadTimeoutHonored(WireMockRuntimeInfo wmInfo) { stubFor(any(urlEqualTo("/metrics")).willReturn(ok().withFixedDelay(5))); assertThatExceptionOfType(SocketTimeoutException.class) - .isThrownBy(() -> httpSender.post(wmInfo.getHttpBaseUrl() + "/metrics").send()); + .isThrownBy(() -> httpSender.post(wmInfo.getHttpBaseUrl() + "/metrics").send()); } @Test diff --git a/micrometer-core/src/test/java/io/micrometer/core/testsupport/classpath/ModifiedClassPathClassLoader.java b/micrometer-core/src/test/java/io/micrometer/core/testsupport/classpath/ModifiedClassPathClassLoader.java index 5cd07552c3..f6189ea4d5 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/testsupport/classpath/ModifiedClassPathClassLoader.java +++ b/micrometer-core/src/test/java/io/micrometer/core/testsupport/classpath/ModifiedClassPathClassLoader.java @@ -115,7 +115,7 @@ private static Stream doExtractUrls(ClassLoader classLoader) { return Stream.of(urlClassLoader.getURLs()); } return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) - .map(ModifiedClassPathClassLoader::toURL); + .map(ModifiedClassPathClassLoader::toURL); } private static URL toURL(String entry) { @@ -198,7 +198,8 @@ private static List resolveCoordinates(String[] coordinates) { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); LocalRepository localRepository = new LocalRepository(System.getProperty("user.home") + "/.m2/repository"); RemoteRepository remoteRepository = new RemoteRepository.Builder("central", "default", - "https://repo.maven.apache.org/maven2").build(); + "https://repo.maven.apache.org/maven2") + .build(); session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(session, localRepository)); for (int i = 0; i < MAX_RESOLUTION_ATTEMPTS; i++) { CollectRequest collectRequest = new CollectRequest(null, Arrays.asList(remoteRepository)); @@ -238,8 +239,9 @@ private static final class ClassPathEntryFilter { private final AntPathMatcher matcher = new AntPathMatcher(); private ClassPathEntryFilter(MergedAnnotation annotation) { - this.exclusions = annotation.getValue(MergedAnnotation.VALUE, String[].class).map(Arrays::asList) - .orElse(Collections.emptyList()); + this.exclusions = annotation.getValue(MergedAnnotation.VALUE, String[].class) + .map(Arrays::asList) + .orElse(Collections.emptyList()); } private boolean isExcluded(URL url) { diff --git a/micrometer-core/src/test/java/io/micrometer/core/testsupport/classpath/ModifiedClassPathExtension.java b/micrometer-core/src/test/java/io/micrometer/core/testsupport/classpath/ModifiedClassPathExtension.java index b5daaa56a1..5f43f87c87 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/testsupport/classpath/ModifiedClassPathExtension.java +++ b/micrometer-core/src/test/java/io/micrometer/core/testsupport/classpath/ModifiedClassPathExtension.java @@ -101,7 +101,8 @@ private void runTest(ClassLoader classLoader, String testClassName, String testM Class testClass = classLoader.loadClass(testClassName); Method testMethod = findMethod(testClass, testMethodName); LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(DiscoverySelectors.selectMethod(testClass, testMethod)).build(); + .selectors(DiscoverySelectors.selectMethod(testClass, testMethod)) + .build(); Launcher launcher = LauncherFactory.create(); TestPlan testPlan = launcher.discover(request); SummaryGeneratingListener listener = new SummaryGeneratingListener(); diff --git a/micrometer-test/src/main/java/io/micrometer/core/instrument/HttpClientTimingInstrumentationVerificationTests.java b/micrometer-test/src/main/java/io/micrometer/core/instrument/HttpClientTimingInstrumentationVerificationTests.java index 52a38eac67..876aa005f4 100644 --- a/micrometer-test/src/main/java/io/micrometer/core/instrument/HttpClientTimingInstrumentationVerificationTests.java +++ b/micrometer-test/src/main/java/io/micrometer/core/instrument/HttpClientTimingInstrumentationVerificationTests.java @@ -106,8 +106,9 @@ void getTemplatedPathForUri(WireMockRuntimeInfo wmRuntimeInfo) { String templatedPath = "/customers/{customerId}/carts/{cartId}"; sendHttpRequest(HttpMethod.GET, null, URI.create(wmRuntimeInfo.getHttpBaseUrl()), templatedPath, "112", "5"); - Timer timer = getRegistry().get(timerName()).tags("method", "GET", "status", "200", "uri", templatedPath) - .timer(); + Timer timer = getRegistry().get(timerName()) + .tags("method", "GET", "status", "200", "uri", templatedPath) + .timer(); assertThat(timer.count()).isEqualTo(1); assertThat(timer.totalTime(TimeUnit.NANOSECONDS)).isPositive(); } diff --git a/micrometer-test/src/main/java/io/micrometer/core/instrument/HttpServerTimingInstrumentationVerificationTests.java b/micrometer-test/src/main/java/io/micrometer/core/instrument/HttpServerTimingInstrumentationVerificationTests.java index 92ca9fd37f..b1df460e33 100644 --- a/micrometer-test/src/main/java/io/micrometer/core/instrument/HttpServerTimingInstrumentationVerificationTests.java +++ b/micrometer-test/src/main/java/io/micrometer/core/instrument/HttpServerTimingInstrumentationVerificationTests.java @@ -91,15 +91,17 @@ void uriIsNotFound_whenRouteIsUnmapped() throws Throwable { @Test void uriTemplateIsTagged() throws Throwable { sender.get(baseUri + "hello/world").send(); - checkTimer(rs -> rs.tags("uri", InstrumentedRoutes.TEMPLATED_ROUTE, "status", "200", "method", "GET").timer() - .count() == 1); + checkTimer(rs -> rs.tags("uri", InstrumentedRoutes.TEMPLATED_ROUTE, "status", "200", "method", "GET") + .timer() + .count() == 1); } @Test void redirect() throws Throwable { sender.get(baseUri + "foundRedirect").send(); - checkTimer(rs -> rs.tags("uri", InstrumentedRoutes.REDIRECT, "status", "302", "method", "GET").timer() - .count() == 1); + checkTimer(rs -> rs.tags("uri", InstrumentedRoutes.REDIRECT, "status", "302", "method", "GET") + .timer() + .count() == 1); } @Test @@ -111,8 +113,9 @@ void errorResponse() throws Throwable { private void checkTimer(Function timerCheck) { // jersey instrumentation finishes after response is sent, creating a race - await().atLeast(Duration.ofMillis(25)).atMost(Duration.ofMillis(150)) - .until(() -> timerCheck.apply(getRegistry().get(timerName()))); + await().atLeast(Duration.ofMillis(25)) + .atMost(Duration.ofMillis(150)) + .until(() -> timerCheck.apply(getRegistry().get(timerName()))); } /** diff --git a/micrometer-test/src/main/java/io/micrometer/core/instrument/binder/cache/CacheMeterBinderCompatibilityKit.java b/micrometer-test/src/main/java/io/micrometer/core/instrument/binder/cache/CacheMeterBinderCompatibilityKit.java index f4368377ea..ba4c84b42d 100644 --- a/micrometer-test/src/main/java/io/micrometer/core/instrument/binder/cache/CacheMeterBinderCompatibilityKit.java +++ b/micrometer-test/src/main/java/io/micrometer/core/instrument/binder/cache/CacheMeterBinderCompatibilityKit.java @@ -91,7 +91,7 @@ void gets() { assertThat(binder.hitCount()).isEqualTo(1); assertThat(registry.get("cache.gets").tag("result", "hit").tag("cache", "mycache").functionCounter().count()) - .isEqualTo(1); + .isEqualTo(1); if (binder.missCount() != null) { // will be 2 for Guava/Caffeine caches where LoadingCache considers a get @@ -100,7 +100,7 @@ void gets() { assertThat( registry.get("cache.gets").tag("result", "miss").tag("cache", "mycache").functionCounter().count()) - .isIn(1.0, 2.0); + .isIn(1.0, 2.0); } } diff --git a/micrometer-test/src/main/java/io/micrometer/core/ipc/http/HttpSenderCompatibilityKit.java b/micrometer-test/src/main/java/io/micrometer/core/ipc/http/HttpSenderCompatibilityKit.java index 9ce971eadc..a81ecc24ea 100644 --- a/micrometer-test/src/main/java/io/micrometer/core/ipc/http/HttpSenderCompatibilityKit.java +++ b/micrometer-test/src/main/java/io/micrometer/core/ipc/http/HttpSenderCompatibilityKit.java @@ -78,24 +78,28 @@ void successfulRequestSentWithBody(HttpSender.Method method, @WiremockResolver.W throws Throwable { server.stubFor(any(urlEqualTo("/metrics")).willReturn(ok("a body"))); - HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics").withMethod(method) - .accept("customAccept").withContent("custom/type", "this is a line").send(); + HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics") + .withMethod(method) + .accept("customAccept") + .withContent("custom/type", "this is a line") + .send(); assertThat(response.code()).isEqualTo(200); assertThat(response.body()).isEqualTo("a body"); server.verify(WireMock - .requestMadeFor(request -> MatchResult.aggregate( - MatchResult.of(request.getMethod().getName().equals(method.name())), - MatchResult.of(request.getUrl().equals("/metrics")))) - .withHeader("Accept", equalTo("customAccept")).withHeader("Content-Type", containing("custom/type")) // charset - // may - // be - // added - // to - // the - // type - .withRequestBody(equalTo("this is a line"))); + .requestMadeFor(request -> MatchResult.aggregate( + MatchResult.of(request.getMethod().getName().equals(method.name())), + MatchResult.of(request.getUrl().equals("/metrics")))) + .withHeader("Accept", equalTo("customAccept")) + .withHeader("Content-Type", containing("custom/type")) // charset + // may + // be + // added + // to + // the + // type + .withRequestBody(equalTo("this is a line"))); } @ParameterizedTest @@ -121,16 +125,18 @@ void errorResponseReceived(HttpSender.Method method, @WiremockResolver.Wiremock void basicAuth(HttpSender.Method method, @WiremockResolver.Wiremock WireMockServer server) throws Throwable { server.stubFor(any(urlEqualTo("/metrics")).willReturn(unauthorized())); - HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics").withMethod(method) - .withBasicAuthentication("superuser", "superpassword").send(); + HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics") + .withMethod(method) + .withBasicAuthentication("superuser", "superpassword") + .send(); assertThat(response.code()).isEqualTo(401); server.verify(WireMock - .requestMadeFor(request -> MatchResult.aggregate( - MatchResult.of(request.getMethod().getName().equals(method.name())), - MatchResult.of(request.getUrl().equals("/metrics")))) - .withBasicAuth(new BasicCredentials("superuser", "superpassword"))); + .requestMadeFor(request -> MatchResult.aggregate( + MatchResult.of(request.getMethod().getName().equals(method.name())), + MatchResult.of(request.getUrl().equals("/metrics")))) + .withBasicAuth(new BasicCredentials("superuser", "superpassword"))); } @ParameterizedTest @@ -138,16 +144,18 @@ void basicAuth(HttpSender.Method method, @WiremockResolver.Wiremock WireMockServ void customHeader(HttpSender.Method method, @WiremockResolver.Wiremock WireMockServer server) throws Throwable { server.stubFor(any(urlEqualTo("/metrics")).willReturn(unauthorized())); - HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics").withMethod(method) - .withHeader("customHeader", "customHeaderValue").send(); + HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics") + .withMethod(method) + .withHeader("customHeader", "customHeaderValue") + .send(); assertThat(response.code()).isEqualTo(401); server.verify(WireMock - .requestMadeFor(request -> MatchResult.aggregate( - MatchResult.of(request.getMethod().getName().equals(method.name())), - MatchResult.of(request.getUrl().equals("/metrics")))) - .withHeader("customHeader", equalTo("customHeaderValue"))); + .requestMadeFor(request -> MatchResult.aggregate( + MatchResult.of(request.getMethod().getName().equals(method.name())), + MatchResult.of(request.getUrl().equals("/metrics")))) + .withHeader("customHeader", equalTo("customHeaderValue"))); } @Test @@ -155,15 +163,17 @@ void authenticationHeader(@WiremockResolver.Wiremock WireMockServer server) thro server.stubFor(any(urlEqualTo("/metrics")).willReturn(unauthorized())); HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics") - .withMethod(HttpSender.Method.POST).withAuthentication("Bearer", "mF_9.B5f-4.1JqM").send(); + .withMethod(HttpSender.Method.POST) + .withAuthentication("Bearer", "mF_9.B5f-4.1JqM") + .send(); assertThat(response.code()).isEqualTo(401); server.verify(WireMock - .requestMadeFor( - request -> MatchResult.aggregate(MatchResult.of(request.getMethod().getName().equals("POST")), - MatchResult.of(request.getUrl().equals("/metrics")))) - .withHeader("Authorization", equalTo("Bearer mF_9.B5f-4.1JqM"))); + .requestMadeFor( + request -> MatchResult.aggregate(MatchResult.of(request.getMethod().getName().equals("POST")), + MatchResult.of(request.getUrl().equals("/metrics")))) + .withHeader("Authorization", equalTo("Bearer mF_9.B5f-4.1JqM"))); } } diff --git a/micrometer-test/src/main/java/io/micrometer/core/tck/DefaultLongTaskTimerTest.java b/micrometer-test/src/main/java/io/micrometer/core/tck/DefaultLongTaskTimerTest.java index 63039c8660..d92e6830ba 100644 --- a/micrometer-test/src/main/java/io/micrometer/core/tck/DefaultLongTaskTimerTest.java +++ b/micrometer-test/src/main/java/io/micrometer/core/tck/DefaultLongTaskTimerTest.java @@ -42,8 +42,8 @@ public class DefaultLongTaskTimerTest { void histogram() { MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); LongTaskTimer t = LongTaskTimer.builder("my.timer") - .serviceLevelObjectives(Duration.ofSeconds(10), Duration.ofSeconds(40), Duration.ofMinutes(1)) - .register(registry); + .serviceLevelObjectives(Duration.ofSeconds(10), Duration.ofSeconds(40), Duration.ofMinutes(1)) + .register(registry); List samples = Arrays.asList(48, 42, 40, 35, 22, 16, 13, 8, 6, 4, 2); int prior = samples.get(0); diff --git a/micrometer-test/src/main/java/io/micrometer/core/tck/MeterRegistryCompatibilityKit.java b/micrometer-test/src/main/java/io/micrometer/core/tck/MeterRegistryCompatibilityKit.java index e54f329f34..7bad5afbab 100644 --- a/micrometer-test/src/main/java/io/micrometer/core/tck/MeterRegistryCompatibilityKit.java +++ b/micrometer-test/src/main/java/io/micrometer/core/tck/MeterRegistryCompatibilityKit.java @@ -160,8 +160,10 @@ void functionTimerUnits() { @Test @DisplayName("meters with synthetics can be removed without causing deadlocks") void removeMeterWithSynthetic() { - Timer timer = Timer.builder("my.timer").publishPercentiles(0.95).serviceLevelObjectives(Duration.ofMillis(10)) - .register(registry); + Timer timer = Timer.builder("my.timer") + .publishPercentiles(0.95) + .serviceLevelObjectives(Duration.ofMillis(10)) + .register(registry); registry.remove(timer); } @@ -277,8 +279,9 @@ void percentiles() { @Deprecated @Test void histogramCounts() { - DistributionSummary s = DistributionSummary.builder("my.summmary").serviceLevelObjectives(1.0) - .register(registry); + DistributionSummary s = DistributionSummary.builder("my.summmary") + .serviceLevelObjectives(1.0) + .register(registry); s.record(1); assertThat(s.histogramCountAtValue(1)).isEqualTo(1); @@ -339,7 +342,7 @@ void mapSizeGauge() { void garbageCollectedSourceObject() { registry.gauge("my.gauge", emptyList(), (Map) null, Map::size); assertThat(registry.get("my.gauge").gauge().value()) - .matches(val -> val == null || Double.isNaN(val) || val == 0.0); + .matches(val -> val == null || Double.isNaN(val) || val == 0.0); } @Test @@ -393,8 +396,9 @@ void record() { @Test @DisplayName("supports sending the Nth percentile active task duration") void percentiles() { - LongTaskTimer t = LongTaskTimer.builder("my.timer").publishPercentiles(0.5, 0.7, 0.91, 0.999, 1) - .register(registry); + LongTaskTimer t = LongTaskTimer.builder("my.timer") + .publishPercentiles(0.5, 0.7, 0.91, 0.999, 1) + .register(registry); // Using the example of percentile interpolation from // https://statisticsbyjim.com/basics/percentiles/ @@ -433,8 +437,8 @@ void percentiles() { @DisplayName("supports sending histograms of active task duration") void histogram() { LongTaskTimer t = LongTaskTimer.builder("my.timer") - .serviceLevelObjectives(Duration.ofSeconds(10), Duration.ofSeconds(40), Duration.ofMinutes(1)) - .register(registry); + .serviceLevelObjectives(Duration.ofSeconds(10), Duration.ofSeconds(40), Duration.ofMinutes(1)) + .register(registry); List samples = Arrays.asList(48, 42, 40, 35, 22, 16, 13, 8, 6, 4, 2); int prior = samples.get(0); @@ -488,8 +492,9 @@ class TimerTck { @CsvSource({ "success", "error" }) @Issue("#1425") void closeable(String outcome) { - try (Timer.ResourceSample sample = Timer.resource(registry, "requests").description("This is an operation") - .publishPercentileHistogram()) { + try (Timer.ResourceSample sample = Timer.resource(registry, "requests") + .description("This is an operation") + .publishPercentileHistogram()) { try { if (outcome.equals("error")) { throw new IllegalArgumentException("boom"); @@ -638,7 +643,7 @@ void recordMax() { // noinspection ConstantConditions clock(registry) - .add(Duration.ofMillis(step().toMillis() * DistributionStatisticConfig.DEFAULT.getBufferLength())); + .add(Duration.ofMillis(step().toMillis() * DistributionStatisticConfig.DEFAULT.getBufferLength())); assertThat(timer.max(TimeUnit.SECONDS)).isEqualTo(0); } diff --git a/micrometer-test/src/test/java/io/micrometer/core/instrument/ApacheHttpClientTimingInstrumentationVerificationTests.java b/micrometer-test/src/test/java/io/micrometer/core/instrument/ApacheHttpClientTimingInstrumentationVerificationTests.java index e1cb680036..a5a7cb21e9 100644 --- a/micrometer-test/src/test/java/io/micrometer/core/instrument/ApacheHttpClientTimingInstrumentationVerificationTests.java +++ b/micrometer-test/src/test/java/io/micrometer/core/instrument/ApacheHttpClientTimingInstrumentationVerificationTests.java @@ -32,7 +32,8 @@ class ApacheHttpClientTimingInstrumentationVerificationTests extends HttpClientTimingInstrumentationVerificationTests { private final HttpClient httpClient = HttpClientBuilder.create() - .setRequestExecutor(MicrometerHttpRequestExecutor.builder(getRegistry()).build()).build(); + .setRequestExecutor(MicrometerHttpRequestExecutor.builder(getRegistry()).build()) + .build(); @Override protected String timerName() { diff --git a/micrometer-test/src/test/java/io/micrometer/core/instrument/JettyClientTimingInstrumentationVerificationTests.java b/micrometer-test/src/test/java/io/micrometer/core/instrument/JettyClientTimingInstrumentationVerificationTests.java index 794e1f4412..ee42a614af 100644 --- a/micrometer-test/src/test/java/io/micrometer/core/instrument/JettyClientTimingInstrumentationVerificationTests.java +++ b/micrometer-test/src/test/java/io/micrometer/core/instrument/JettyClientTimingInstrumentationVerificationTests.java @@ -37,8 +37,10 @@ protected String timerName() { @BeforeEach void setup() throws Exception { - httpClient.getRequestListeners().add(JettyClientMetrics - .builder(getRegistry(), result -> result.getRequest().getHeaders().get(HEADER_URI_PATTERN)).build()); + httpClient.getRequestListeners() + .add(JettyClientMetrics + .builder(getRegistry(), result -> result.getRequest().getHeaders().get(HEADER_URI_PATTERN)) + .build()); httpClient.start(); } @@ -47,7 +49,8 @@ protected void sendHttpRequest(HttpMethod method, @Nullable byte[] body, URI bas String... pathVariables) { try { Request request = httpClient.newRequest(baseUri + substitutePathVariables(templatedPath, pathVariables)) - .method(method.name()).header(HEADER_URI_PATTERN, templatedPath); + .method(method.name()) + .header(HEADER_URI_PATTERN, templatedPath); if (body != null) { request.content(new BytesContentProvider(body)); } diff --git a/micrometer-test/src/test/java/io/micrometer/core/instrument/OkHttpClientTimingInstrumentationVerificationTests.java b/micrometer-test/src/test/java/io/micrometer/core/instrument/OkHttpClientTimingInstrumentationVerificationTests.java index fcb2075cdf..d59e2219d5 100644 --- a/micrometer-test/src/test/java/io/micrometer/core/instrument/OkHttpClientTimingInstrumentationVerificationTests.java +++ b/micrometer-test/src/test/java/io/micrometer/core/instrument/OkHttpClientTimingInstrumentationVerificationTests.java @@ -28,14 +28,16 @@ class OkHttpClientTimingInstrumentationVerificationTests extends HttpClientTimingInstrumentationVerificationTests { OkHttpClient httpClient = new OkHttpClient.Builder() - .eventListener(OkHttpMetricsEventListener.builder(getRegistry(), timerName()).build()).build(); + .eventListener(OkHttpMetricsEventListener.builder(getRegistry(), timerName()).build()) + .build(); @Override protected void sendHttpRequest(HttpMethod method, @Nullable byte[] body, URI baseUri, String templatedPath, String... pathVariables) { Request request = new Request.Builder().method(method.name(), body == null ? null : RequestBody.create(body)) - .url(baseUri + substitutePathVariables(templatedPath, pathVariables)) - .header(OkHttpMetricsEventListener.URI_PATTERN, templatedPath).build(); + .url(baseUri + substitutePathVariables(templatedPath, pathVariables)) + .header(OkHttpMetricsEventListener.URI_PATTERN, templatedPath) + .build(); try (Response ignored = httpClient.newCall(request).execute()) { } catch (IOException e) { diff --git a/micrometer-test/src/test/java/io/micrometer/core/instrument/binder/cache/JCacheMetricsCompatibilityTest.java b/micrometer-test/src/test/java/io/micrometer/core/instrument/binder/cache/JCacheMetricsCompatibilityTest.java index 3d40c3b35d..931194b5d5 100644 --- a/micrometer-test/src/test/java/io/micrometer/core/instrument/binder/cache/JCacheMetricsCompatibilityTest.java +++ b/micrometer-test/src/test/java/io/micrometer/core/instrument/binder/cache/JCacheMetricsCompatibilityTest.java @@ -33,7 +33,8 @@ public Cache createCache() { MutableConfiguration configuration = new MutableConfiguration<>(); configuration.setTypes(String.class, String.class) - .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(ONE_HOUR)).setStatisticsEnabled(true); + .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(ONE_HOUR)) + .setStatisticsEnabled(true); return cacheManager.createCache("mycache", configuration); } diff --git a/micrometer-test/src/test/java/io/micrometer/core/util/internal/logging/LogEventTest.java b/micrometer-test/src/test/java/io/micrometer/core/util/internal/logging/LogEventTest.java index d6e320b7c3..51cd6aeb11 100644 --- a/micrometer-test/src/test/java/io/micrometer/core/util/internal/logging/LogEventTest.java +++ b/micrometer-test/src/test/java/io/micrometer/core/util/internal/logging/LogEventTest.java @@ -31,7 +31,8 @@ class LogEventTest { void logLevelShouldBeMandatory() { assertThatCode(() -> new LogEvent(INFO, null, null)).doesNotThrowAnyException(); assertThatThrownBy(() -> new LogEvent(null, null, null)).isInstanceOf(NullPointerException.class) - .hasMessage(null).hasNoCause(); + .hasMessage(null) + .hasNoCause(); } @Test diff --git a/samples/micrometer-samples-boot2/src/main/java/io/micrometer/boot2/samples/components/HttpMetricsTagConfiguration.java b/samples/micrometer-samples-boot2/src/main/java/io/micrometer/boot2/samples/components/HttpMetricsTagConfiguration.java index 7e1593734f..85c4d51369 100644 --- a/samples/micrometer-samples-boot2/src/main/java/io/micrometer/boot2/samples/components/HttpMetricsTagConfiguration.java +++ b/samples/micrometer-samples-boot2/src/main/java/io/micrometer/boot2/samples/components/HttpMetricsTagConfiguration.java @@ -42,8 +42,11 @@ @Configuration public class HttpMetricsTagConfiguration { - private final Map responseTags = CacheBuilder.newBuilder().maximumSize(10_000) - .expireAfterWrite(Duration.ofSeconds(10)).build().asMap(); + private final Map responseTags = CacheBuilder.newBuilder() + .maximumSize(10_000) + .expireAfterWrite(Duration.ofSeconds(10)) + .build() + .asMap(); @Bean OncePerRequestFilter extractCountry() { diff --git a/samples/micrometer-samples-boot2/src/main/java/io/micrometer/boot2/samples/components/ServiceLevelObjectiveConfiguration.java b/samples/micrometer-samples-boot2/src/main/java/io/micrometer/boot2/samples/components/ServiceLevelObjectiveConfiguration.java index 9c47a3d7a1..2ac72eb89f 100644 --- a/samples/micrometer-samples-boot2/src/main/java/io/micrometer/boot2/samples/components/ServiceLevelObjectiveConfiguration.java +++ b/samples/micrometer-samples-boot2/src/main/java/io/micrometer/boot2/samples/components/ServiceLevelObjectiveConfiguration.java @@ -52,14 +52,17 @@ public ServiceLevelObjectiveConfiguration(GenericApplicationContext applicationC @Bean HealthMeterRegistry healthMeterRegistry() { HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) - .serviceLevelObjectives(JvmServiceLevelObjectives.MEMORY) - .serviceLevelObjectives(OperatingSystemServiceLevelObjectives.DISK) - .serviceLevelObjectives(ServiceLevelObjective.build("api.error.ratio").failedMessage("API error ratio") - .baseUnit(BaseUnits.PERCENT).tag("uri.matches", "/api/**").tag("error.outcome", "SERVER_ERROR") - .errorRatio(s -> s.name("http.server.requests").tag("uri", uri -> uri.startsWith("/api")), - all -> all.tag("outcome", "SERVER_ERROR")) - .isLessThan(0.01)) - .build(); + .serviceLevelObjectives(JvmServiceLevelObjectives.MEMORY) + .serviceLevelObjectives(OperatingSystemServiceLevelObjectives.DISK) + .serviceLevelObjectives(ServiceLevelObjective.build("api.error.ratio") + .failedMessage("API error ratio") + .baseUnit(BaseUnits.PERCENT) + .tag("uri.matches", "/api/**") + .tag("error.outcome", "SERVER_ERROR") + .errorRatio(s -> s.name("http.server.requests").tag("uri", uri -> uri.startsWith("/api")), + all -> all.tag("outcome", "SERVER_ERROR")) + .isLessThan(0.01)) + .build(); for (ServiceLevelObjective slo : registry.getServiceLevelObjectives()) { applicationContext.registerBean(camelCasedHealthIndicatorNames.name(slo.getName(), Type.GAUGE), @@ -76,8 +79,8 @@ private HealthContributor toHealthContributor(HealthMeterRegistry registry, Serv protected void doHealthCheck(Health.Builder builder) { ServiceLevelObjective.SingleIndicator singleIndicator = (ServiceLevelObjective.SingleIndicator) slo; builder.status(slo.healthy(registry) ? Status.UP : Status.OUT_OF_SERVICE) - .withDetail("value", singleIndicator.getValueAsString(registry)) - .withDetail("mustBe", singleIndicator.getTestDescription()); + .withDetail("value", singleIndicator.getValueAsString(registry)) + .withDetail("mustBe", singleIndicator.getTestDescription()); for (Tag tag : slo.getTags()) { builder.withDetail(camelCasedHealthIndicatorNames.tagKey(tag.getKey()), tag.getValue()); @@ -92,9 +95,9 @@ protected void doHealthCheck(Health.Builder builder) { else { ServiceLevelObjective.MultipleIndicator multipleIndicator = (ServiceLevelObjective.MultipleIndicator) slo; Map objectiveIndicators = Arrays.stream(multipleIndicator.getObjectives()) - .collect(Collectors.toMap( - indicator -> camelCasedHealthIndicatorNames.name(indicator.getName(), Type.GAUGE), - indicator -> toHealthContributor(registry, indicator))); + .collect(Collectors.toMap( + indicator -> camelCasedHealthIndicatorNames.name(indicator.getName(), Type.GAUGE), + indicator -> toHealthContributor(registry, indicator))); return CompositeHealthContributor.fromMap(objectiveIndicators); } } diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/CacheSample.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/CacheSample.java index 5d7d64b64d..a9d6e02d31 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/CacheSample.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/CacheSample.java @@ -36,31 +36,42 @@ public class CacheSample { private static final int CACHE_SIZE = 10000; - private static final Cache guavaCache = CacheBuilder.newBuilder().maximumSize(CACHE_SIZE) - .recordStats() // required - .build(); + private static final Cache guavaCache = CacheBuilder.newBuilder() + .maximumSize(CACHE_SIZE) + .recordStats() // required + .build(); public static void main(String[] args) { MeterRegistry registry = SampleConfig.myMonitoringSystem(); GuavaCacheMetrics.monitor(registry, guavaCache, "book.guava"); // read all of Frankenstein - HttpClient.create().baseUrl("www.gutenberg.org").doOnRequest((req, conn) -> conn.addHandlerLast(wordDecoder())) - .get().uri("/files/84/84-0.txt").responseContent().asString().delayElements(Duration.ofMillis(10)) // one - // word - // per - // 10 - // ms - .filter(word -> !word.isEmpty()).doOnNext(word -> { - if (guavaCache.getIfPresent(word) == null) - guavaCache.put(word, 1); - }).blockLast(); + HttpClient.create() + .baseUrl("www.gutenberg.org") + .doOnRequest((req, conn) -> conn.addHandlerLast(wordDecoder())) + .get() + .uri("/files/84/84-0.txt") + .responseContent() + .asString() + .delayElements(Duration.ofMillis(10)) // one + // word + // per + // 10 + // ms + .filter(word -> !word.isEmpty()) + .doOnNext(word -> { + if (guavaCache.getIfPresent(word) == null) + guavaCache.put(word, 1); + }) + .blockLast(); } // skip things that aren't words, roughly private static DelimiterBasedFrameDecoder wordDecoder() { - return new DelimiterBasedFrameDecoder(256, IntStream.of('\r', '\n', ' ', '\t', '.', ',', ';', ':', '-') - .mapToObj(delim -> wrappedBuffer(new byte[] { (byte) delim })).toArray(ByteBuf[]::new)); + return new DelimiterBasedFrameDecoder(256, + IntStream.of('\r', '\n', ' ', '\t', '.', ',', ';', ':', '-') + .mapToObj(delim -> wrappedBuffer(new byte[] { (byte) delim })) + .toArray(ByteBuf[]::new)); } } diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/FunctionCounterSample.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/FunctionCounterSample.java index 460f75a9ed..3701b95951 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/FunctionCounterSample.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/FunctionCounterSample.java @@ -31,11 +31,15 @@ public static void main(String[] args) { AtomicInteger n = new AtomicInteger(); - FunctionCounter.builder("my.fcounter", n, AtomicInteger::get).baseUnit("happiness") - .description("A counter derived from a monotonically increasing value").register(registry); - - Counter counter = Counter.builder("my.counter").baseUnit("happiness").description("A normal counter") - .register(registry); + FunctionCounter.builder("my.fcounter", n, AtomicInteger::get) + .baseUnit("happiness") + .description("A counter derived from a monotonically increasing value") + .register(registry); + + Counter counter = Counter.builder("my.counter") + .baseUnit("happiness") + .description("A normal counter") + .register(registry); Flux.interval(Duration.ofMillis(10)).doOnEach(i -> { n.incrementAndGet(); diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/FunctionTimerSample.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/FunctionTimerSample.java index 41df77d2b5..e89d8ad26b 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/FunctionTimerSample.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/FunctionTimerSample.java @@ -44,8 +44,8 @@ public static void main(String[] args) { AtomicLong totalCount = new AtomicLong(); FunctionTimer - .builder("ftimer", placeholder, p -> totalCount.get(), p -> totalTimeNanos.get(), TimeUnit.NANOSECONDS) - .register(registry); + .builder("ftimer", placeholder, p -> totalCount.get(), p -> totalTimeNanos.get(), TimeUnit.NANOSECONDS) + .register(registry); RandomEngine r = new MersenneTwister64(0); Normal incomingRequests = new Normal(0, 1, r); @@ -62,7 +62,7 @@ public static void main(String[] args) { timer.record(latencyForThisSecond.get(), TimeUnit.MILLISECONDS); totalCount.incrementAndGet(); totalTimeNanos - .addAndGet((long) TimeUtils.millisToUnit(latencyForThisSecond.get(), TimeUnit.NANOSECONDS)); + .addAndGet((long) TimeUtils.millisToUnit(latencyForThisSecond.get(), TimeUnit.NANOSECONDS)); } }).blockLast(); } diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/GrpcMetricsSample.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/GrpcMetricsSample.java index f9b2b3757f..5516b21694 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/GrpcMetricsSample.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/GrpcMetricsSample.java @@ -44,16 +44,19 @@ public static void main(final String... args) throws IOException { final HealthStatusManager service = new HealthStatusManager(); - final Server server = InProcessServerBuilder.forName("sample").addService(service.getHealthService()) // Or - // any - // other - // service(s) - .intercept(new MetricCollectingServerInterceptor(registry)).build(); + final Server server = InProcessServerBuilder.forName("sample") + .addService(service.getHealthService()) // Or + // any + // other + // service(s) + .intercept(new MetricCollectingServerInterceptor(registry)) + .build(); server.start(); final ManagedChannel channel = InProcessChannelBuilder.forName("sample") - .intercept(new MetricCollectingClientInterceptor(registry)).build(); + .intercept(new MetricCollectingClientInterceptor(registry)) + .build(); final HealthBlockingStub healthClient = HealthGrpc.newBlockingStub(channel); // Or // any diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/KafkaMetricsSample.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/KafkaMetricsSample.java index 9f7b062697..8d699c78f3 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/KafkaMetricsSample.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/KafkaMetricsSample.java @@ -47,8 +47,9 @@ public static void main(String[] args) throws Exception { consumer.subscribe(singletonList(TOPIC)); - Flux.interval(Duration.ofMillis(10)).doOnEach(n -> producer.send(new ProducerRecord<>(TOPIC, "hello", "world"))) - .subscribe(); + Flux.interval(Duration.ofMillis(10)) + .doOnEach(n -> producer.send(new ProducerRecord<>(TOPIC, "hello", "world"))) + .subscribe(); for (;;) { consumer.poll(Duration.ofMillis(100)); diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/PrometheusExemplarsSample.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/PrometheusExemplarsSample.java index a27a1568b3..e0f86cf703 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/PrometheusExemplarsSample.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/PrometheusExemplarsSample.java @@ -46,7 +46,8 @@ public static void main(String[] args) throws InterruptedException { timer.record(Duration.ofSeconds(60)); DistributionSummary distributionSummary = DistributionSummary.builder("test.distribution") - .publishPercentileHistogram().register(registry); + .publishPercentileHistogram() + .register(registry); distributionSummary.record(0.15); distributionSummary.record(15); distributionSummary.record(5E18); diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/QuantileDecaySample.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/QuantileDecaySample.java index 4daaa26331..7b79e0c03d 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/QuantileDecaySample.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/QuantileDecaySample.java @@ -27,8 +27,9 @@ public class QuantileDecaySample { public static void main(String[] args) { MeterRegistry registry = SampleConfig.myMonitoringSystem(); - DistributionSummary summary = DistributionSummary.builder("my.summary").publishPercentiles(0.9) - .register(registry); + DistributionSummary summary = DistributionSummary.builder("my.summary") + .publishPercentiles(0.9) + .register(registry); range(1, 10).forEach(summary::record); diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/SimulatedEndpointInstrumentation.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/SimulatedEndpointInstrumentation.java index 4221aaee0f..b637d661ee 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/SimulatedEndpointInstrumentation.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/SimulatedEndpointInstrumentation.java @@ -32,17 +32,29 @@ public class SimulatedEndpointInstrumentation { public static void main(String[] args) { MeterRegistry registry = SampleConfig.myMonitoringSystem(); - Timer e1Success = Timer.builder("http.server.requests").tags("uri", "/api/bar").tags("response", "200") - .publishPercentiles(0.5, 0.95).register(registry); + Timer e1Success = Timer.builder("http.server.requests") + .tags("uri", "/api/bar") + .tags("response", "200") + .publishPercentiles(0.5, 0.95) + .register(registry); - Timer e2Success = Timer.builder("http.server.requests").tags("uri", "/api/foo").tags("response", "200") - .publishPercentiles(0.5, 0.95).register(registry); + Timer e2Success = Timer.builder("http.server.requests") + .tags("uri", "/api/foo") + .tags("response", "200") + .publishPercentiles(0.5, 0.95) + .register(registry); - Timer e1Fail = Timer.builder("http.server.requests").tags("uri", "/api/bar").tags("response", "500") - .publishPercentiles(0.5, 0.95).register(registry); + Timer e1Fail = Timer.builder("http.server.requests") + .tags("uri", "/api/bar") + .tags("response", "500") + .publishPercentiles(0.5, 0.95) + .register(registry); - Timer e2Fail = Timer.builder("http.server.requests").tags("uri", "/api/foo").tags("response", "500") - .publishPercentiles(0.5, 0.95).register(registry); + Timer e2Fail = Timer.builder("http.server.requests") + .tags("uri", "/api/foo") + .tags("response", "500") + .publishPercentiles(0.5, 0.95) + .register(registry); RandomEngine r = new MersenneTwister64(0); Normal incomingRequests = new Normal(0, 1, r); diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerMaximumThroughputSample.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerMaximumThroughputSample.java index 8a60ff4acb..3a20c64c1c 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerMaximumThroughputSample.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerMaximumThroughputSample.java @@ -36,11 +36,13 @@ public class TimerMaximumThroughputSample { public static void main(String[] args) { MeterRegistry registry = SampleConfig.myMonitoringSystem(); - Timer timer = Timer.builder("timer").publishPercentileHistogram() - // .publishPercentiles(0.5, 0.95, 0.99) - .serviceLevelObjectives(Duration.ofMillis(275), Duration.ofMillis(300), Duration.ofMillis(500)) - .distributionStatisticExpiry(Duration.ofSeconds(10)).distributionStatisticBufferLength(3) - .register(registry); + Timer timer = Timer.builder("timer") + .publishPercentileHistogram() + // .publishPercentiles(0.5, 0.95, 0.99) + .serviceLevelObjectives(Duration.ofMillis(275), Duration.ofMillis(300), Duration.ofMillis(500)) + .distributionStatisticExpiry(Duration.ofSeconds(10)) + .distributionStatisticBufferLength(3) + .register(registry); RandomEngine r = new MersenneTwister64(0); Normal duration = new Normal(250, 50, r); @@ -49,8 +51,11 @@ public static void main(String[] args) { Flux.interval(Duration.ofSeconds(1)).doOnEach(d -> latencyForThisSecond.set(duration.nextInt())).subscribe(); Stream infiniteStream = Stream.iterate(0, i -> (i + 1) % 1000); - Flux.fromStream(infiniteStream).parallel(4).runOn(Schedulers.parallel()) - .doOnEach(d -> timer.record(latencyForThisSecond.get(), TimeUnit.MILLISECONDS)).subscribe(); + Flux.fromStream(infiniteStream) + .parallel(4) + .runOn(Schedulers.parallel()) + .doOnEach(d -> timer.record(latencyForThisSecond.get(), TimeUnit.MILLISECONDS)) + .subscribe(); Flux.never().blockLast(); } diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerMemory.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerMemory.java index 2961384bf6..30273adfcd 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerMemory.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerMemory.java @@ -31,11 +31,15 @@ public static void main(String[] args) throws InterruptedException { Timer t = null; for (Integer i = 0; i < 80; i++) { - t = Timer.builder("my.timer").tag("index", i.toString()) - // .publishPercentileHistogram() - .serviceLevelObjectives(Stream.of(1, 150, 300, 500, 900, 1000, 1200, 1500, 2000, 3000, 4000) - .map(Duration::ofMillis).toArray(Duration[]::new)) - .publishPercentiles(0.95).percentilePrecision(1).register(registry); + t = Timer.builder("my.timer") + .tag("index", i.toString()) + // .publishPercentileHistogram() + .serviceLevelObjectives(Stream.of(1, 150, 300, 500, 900, 1000, 1200, 1500, 2000, 3000, 4000) + .map(Duration::ofMillis) + .toArray(Duration[]::new)) + .publishPercentiles(0.95) + .percentilePrecision(1) + .register(registry); } // Breakpoint somewhere after the first couple outputs to test pause detection diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerSample.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerSample.java index c23191495b..5f50691d11 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerSample.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/TimerSample.java @@ -33,15 +33,18 @@ public class TimerSample { public static void main(String[] args) { MeterRegistry registry = SampleConfig.myMonitoringSystem(); - Timer timer = Timer.builder("timer").publishPercentileHistogram().publishPercentiles(0.5, 0.95, 0.99) - .serviceLevelObjectives(Duration.ofMillis(275), Duration.ofMillis(300), Duration.ofMillis(500)) - .distributionStatisticExpiry(Duration.ofSeconds(10)).distributionStatisticBufferLength(3) - .register(registry); + Timer timer = Timer.builder("timer") + .publishPercentileHistogram() + .publishPercentiles(0.5, 0.95, 0.99) + .serviceLevelObjectives(Duration.ofMillis(275), Duration.ofMillis(300), Duration.ofMillis(500)) + .distributionStatisticExpiry(Duration.ofSeconds(10)) + .distributionStatisticBufferLength(3) + .register(registry); AtomicLong totalCount = new AtomicLong(); AtomicLong totalTime = new AtomicLong(); FunctionTimer.builder("ftimer", totalCount, t -> totalCount.get(), t -> totalTime.get(), TimeUnit.MILLISECONDS) - .register(registry); + .register(registry); RandomEngine r = new MersenneTwister64(0); Normal incomingRequests = new Normal(0, 1, r); diff --git a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/utils/SampleRegistries.java b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/utils/SampleRegistries.java index 45d2508cd9..983c9e6e5d 100644 --- a/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/utils/SampleRegistries.java +++ b/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/utils/SampleRegistries.java @@ -520,10 +520,12 @@ public String get(String key) { public Duration step() { return Duration.ofSeconds(10); } - }).metricServiceSettings(() -> MetricServiceSettings.newBuilder() + }) + .metricServiceSettings(() -> MetricServiceSettings.newBuilder() .setCredentialsProvider( FixedCredentialsProvider.create(ServiceAccountCredentials.fromStream(credentials))) - .build()).build(); + .build()) + .build(); } catch (IOException e) { throw new UncheckedIOException(e); diff --git a/samples/micrometer-samples-javalin/src/main/java/io/micrometer/javalin/samples/PrometheusSample.java b/samples/micrometer-samples-javalin/src/main/java/io/micrometer/javalin/samples/PrometheusSample.java index 0431715134..146a256445 100644 --- a/samples/micrometer-samples-javalin/src/main/java/io/micrometer/javalin/samples/PrometheusSample.java +++ b/samples/micrometer-samples-javalin/src/main/java/io/micrometer/javalin/samples/PrometheusSample.java @@ -129,12 +129,16 @@ public Iterable getTags(HttpServletRequest request, HttpServletResponse res String exceptionName = response.getHeader(EXCEPTION_HEADER); response.setHeader(EXCEPTION_HEADER, null); - String uri = app.javalinServlet().getMatcher() - .findEntries(HandlerType.valueOf(request.getMethod()), request.getPathInfo()).stream().findAny() - .map(HandlerEntry::getPath) - .map(path -> path.equals("/") || StringUtils.isBlank(path) ? "root" : path) - .map(path -> response.getStatus() >= 300 && response.getStatus() < 400 ? "REDIRECTION" : path) - .map(path -> response.getStatus() == 404 ? "NOT_FOUND" : path).orElse("unknown"); + String uri = app.javalinServlet() + .getMatcher() + .findEntries(HandlerType.valueOf(request.getMethod()), request.getPathInfo()) + .stream() + .findAny() + .map(HandlerEntry::getPath) + .map(path -> path.equals("/") || StringUtils.isBlank(path) ? "root" : path) + .map(path -> response.getStatus() >= 300 && response.getStatus() < 400 ? "REDIRECTION" : path) + .map(path -> response.getStatus() == 404 ? "NOT_FOUND" : path) + .orElse("unknown"); return Tags.concat(super.getTags(request, response), "uri", uri, "exception", exceptionName == null ? "None" : exceptionName); diff --git a/samples/micrometer-samples-jersey3/src/main/java/io/micrometer/samples/jersey3/Jersey3Main.java b/samples/micrometer-samples-jersey3/src/main/java/io/micrometer/samples/jersey3/Jersey3Main.java index 9903859703..e695a64047 100644 --- a/samples/micrometer-samples-jersey3/src/main/java/io/micrometer/samples/jersey3/Jersey3Main.java +++ b/samples/micrometer-samples-jersey3/src/main/java/io/micrometer/samples/jersey3/Jersey3Main.java @@ -48,8 +48,8 @@ public Duration step() { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); Runtime.getRuntime().addShutdownHook(new Thread(() -> server.stop(0))); Application application = new ResourceConfig(HelloWorldResource.class) - .register(new MetricsApplicationEventListener(registry, new DefaultJerseyTagsProvider(), - "http.server.requests", true)); + .register(new MetricsApplicationEventListener(registry, new DefaultJerseyTagsProvider(), + "http.server.requests", true)); server.createContext("/", RuntimeDelegate.getInstance().createEndpoint(application, HttpHandler.class)); server.start(); diff --git a/samples/micrometer-samples-jersey3/src/test/java/io/micrometer/samples/jersey3/Jersey3Test.java b/samples/micrometer-samples-jersey3/src/test/java/io/micrometer/samples/jersey3/Jersey3Test.java index 64dd5ebca0..56f59a8cbb 100644 --- a/samples/micrometer-samples-jersey3/src/test/java/io/micrometer/samples/jersey3/Jersey3Test.java +++ b/samples/micrometer-samples-jersey3/src/test/java/io/micrometer/samples/jersey3/Jersey3Test.java @@ -47,8 +47,9 @@ protected Application configure() { void helloResourceIsTimed() { String response = target("hello/Jersey").request().get(String.class); assertThat(response).isEqualTo("Hello, Jersey"); - Timer timer = registry.get(TIMER_METRIC_NAME).tags("method", "GET", "uri", "/hello/{name}", "status", "200", - "exception", "None", "outcome", "SUCCESS").timer(); + Timer timer = registry.get(TIMER_METRIC_NAME) + .tags("method", "GET", "uri", "/hello/{name}", "status", "200", "exception", "None", "outcome", "SUCCESS") + .timer(); assertThat(timer.count()).isEqualTo(1); assertThat(timer.totalTime(TimeUnit.NANOSECONDS)).isPositive(); } diff --git a/samples/micrometer-samples-spring-integration/src/main/java/io/micrometer/spring/integration/samples/SpringIntegrationApplication.java b/samples/micrometer-samples-spring-integration/src/main/java/io/micrometer/spring/integration/samples/SpringIntegrationApplication.java index 447eaab673..72e4911445 100644 --- a/samples/micrometer-samples-spring-integration/src/main/java/io/micrometer/spring/integration/samples/SpringIntegrationApplication.java +++ b/samples/micrometer-samples-spring-integration/src/main/java/io/micrometer/spring/integration/samples/SpringIntegrationApplication.java @@ -48,14 +48,14 @@ public static void main(String[] args) throws InterruptedException { @Bean public IntegrationFlow convert() { return f -> f - .transform(payload -> "" + "" - + payload + "" + "", e -> e.id("toXml")) - .enrichHeaders(h -> h.header(WebServiceHeaders.SOAP_ACTION, - "https://www.w3schools.com/xml/FahrenheitToCelsius")) - .handle(new SimpleWebServiceOutboundGateway("https://www.w3schools.com/xml/tempconvert.asmx"), - e -> e.id("w3schools")) - .transform(new XPathTransformer("/*[local-name()=\"FahrenheitToCelsiusResponse\"]" - + "/*[local-name()=\"FahrenheitToCelsiusResult\"]"), e -> e.id("toResponse")); + .transform(payload -> "" + "" + + payload + "" + "", e -> e.id("toXml")) + .enrichHeaders( + h -> h.header(WebServiceHeaders.SOAP_ACTION, "https://www.w3schools.com/xml/FahrenheitToCelsius")) + .handle(new SimpleWebServiceOutboundGateway("https://www.w3schools.com/xml/tempconvert.asmx"), + e -> e.id("w3schools")) + .transform(new XPathTransformer("/*[local-name()=\"FahrenheitToCelsiusResponse\"]" + + "/*[local-name()=\"FahrenheitToCelsiusResult\"]"), e -> e.id("toResponse")); } @MessagingGateway