Java源码示例:io.micrometer.core.instrument.MeterRegistry
示例1
@Override
protected void bindImplementationSpecificMetrics(MeterRegistry registry) {
if (cache == null) return;
Gauge.builder("cache.start", cache, cache -> cache.getAdvancedCache().getStats().getTimeSinceStart())
.baseUnit(TimeUnit.SECONDS.name())
.tags(getTagsWithCacheName())
.description("Time elapsed since start")
.register(registry);
Gauge.builder("cache.reset", cache, cache -> cache.getAdvancedCache().getStats().getTimeSinceReset())
.baseUnit(TimeUnit.SECONDS.name())
.tags(getTagsWithCacheName())
.description("Time elapsed since the last statistics reset")
.register(registry);
memory(registry);
averages(registry);
}
示例2
/**
* Wraps a {@link ThreadFactory} with an explicit name and records the number of created, running
* and terminated threads.
*
* @param delegate {@link ThreadFactory} to wrap.
* @param registry {@link MeterRegistry} that will contain the metrics.
* @param name name for this delegate.
* @param tags tags that can provide additional context.
*/
public CountedThreadFactory(
ThreadFactory delegate, MeterRegistry registry, String name, Iterable<Tag> tags) {
this.delegate = delegate;
this.created =
Counter.builder("thread.factory.created")
.tags(Tags.concat(tags, "name", name))
.description(
"The approximate number of threads which were created with a thread factory")
.baseUnit(BaseUnits.THREADS)
.register(registry);
this.terminated =
Counter.builder("thread.factory.terminated")
.tags(Tags.concat(tags, "name", name))
.description("The approximate number of threads which have finished execution")
.baseUnit(BaseUnits.THREADS)
.register(registry);
Gauge.builder("thread.factory.running", running, AtomicInteger::get)
.tags(Tags.concat(tags, "name", name))
.description(
"The approximate number of threads which have started to execute, but have not terminated")
.baseUnit(BaseUnits.THREADS)
.register(registry);
}
示例3
/**
* Verifies that the payload size is calculated based on the configured minimum message size
* when reporting command messages.
*
* @param registry The registry that the tests should be run against.
*/
@ParameterizedTest
@MethodSource("registries")
public void testPayloadSizeForCommandMessages(final MeterRegistry registry) {
final Metrics metrics = new MicrometerBasedMetrics(registry, mock(Vertx.class));
final TenantObject tenantObject = TenantObject.from("TEST_TENANT", true)
.setMinimumMessageSize(4 * 1024);
metrics.reportCommand(
MetricsTags.Direction.REQUEST,
"tenant",
tenantObject,
MetricsTags.ProcessingOutcome.FORWARDED,
1 * 1024,
metrics.startTimer());
assertEquals(4 * 1024,
registry.find(MicrometerBasedMetrics.METER_COMMANDS_PAYLOAD).summary().totalAmount());
}
示例4
@Issue("#1968")
@Test
void shouldRemoveOlderMeterWithLessTagsWhenCommonTagsConfigured() {
//Given
Map<String, String> tags = new LinkedHashMap<>();
Supplier<Map<MetricName, ? extends Metric>> supplier = () -> {
MetricName metricName = new MetricName("a", "b", "c", tags);
KafkaMetric metric = new KafkaMetric(this, metricName, new Value(), new MetricConfig(), Time.SYSTEM);
return Collections.singletonMap(metricName, metric);
};
kafkaMetrics = new KafkaMetrics(supplier);
MeterRegistry registry = new SimpleMeterRegistry();
registry.config().commonTags("common", "value");
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
tags.put("key0", "value0");
kafkaMetrics.checkAndBindMetrics(registry);
assertThat(registry.getMeters()).hasSize(1);
assertThat(registry.getMeters().get(0).getId().getTags()).containsExactlyInAnyOrder(Tag.of("kafka-version", "unknown"), Tag.of("key0", "value0"), Tag.of("common", "value"));
}
示例5
@Test
void httpFailure() {
final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
final ClientRequestContext ctx = setupClientRequestCtx(registry);
ctx.logBuilder().requestFirstBytesTransferred();
ctx.logBuilder().responseHeaders(ResponseHeaders.of(500));
ctx.logBuilder().responseFirstBytesTransferred();
ctx.logBuilder().responseLength(456);
ctx.logBuilder().endRequest();
ctx.logBuilder().endResponse();
final Map<String, Double> measurements = measureAll(registry);
assertThat(measurements)
.containsEntry("foo.active.requests#value{method=POST}", 0.0)
.containsEntry("foo.requests#count{http.status=500,method=POST,result=success}", 0.0)
.containsEntry("foo.requests#count{http.status=500,method=POST,result=failure}", 1.0)
.containsEntry("foo.response.duration#count{http.status=500,method=POST}", 1.0)
.containsEntry("foo.response.length#count{http.status=500,method=POST}", 1.0)
.containsEntry("foo.total.duration#count{http.status=500,method=POST}", 1.0);
}
示例6
@Test
void timeMethodFailureWithLongTaskTimer() {
MeterRegistry failingRegistry = new FailingMeterRegistry();
AspectJProxyFactory pf = new AspectJProxyFactory(new TimedService());
pf.addAspect(new TimedAspect(failingRegistry));
TimedService service = pf.getProxy();
service.longCall();
assertThatExceptionOfType(MeterNotFoundException.class).isThrownBy(() -> {
failingRegistry.get("longCall")
.tag("class", "io.micrometer.core.aop.TimedAspectTest$TimedService")
.tag("method", "longCall")
.tag("extra", "tag")
.longTaskTimer();
});
}
示例7
public LdapSearchMetrics(MeterRegistry meterRegistry) {
Gauge.builder("totalCallsCounter", this,
LdapSearchMetrics::getTotalCallsCounterAndReset)
.tags("class", this.getClass().getSimpleName())
.register(meterRegistry);
Gauge.builder("failedCallsCounter", this,
LdapSearchMetrics::getFailedCallsCounterAndReset)
.tags("class", this.getClass().getSimpleName())
.register(meterRegistry);
Gauge.builder("unexpectedExceptionCounter", this,
LdapSearchMetrics::getUnexpectedExceptionCounterAndReset)
.tags("class", this.getClass().getSimpleName())
.register(meterRegistry);
Gauge.builder("retriesExhaustedExceptionCounter", this,
LdapSearchMetrics::getRetriesExhaustedExceptionCounterAndReset)
.tags("class", this.getClass().getSimpleName())
.register(meterRegistry);
}
示例8
@Test
void verifyConsumerMetricsWithExpectedTags() {
try (Consumer<Long, String> consumer = createConsumer()) {
MeterRegistry registry = new SimpleMeterRegistry();
kafkaConsumerMetrics.bindTo(registry);
// consumer coordinator metrics
Gauge assignedPartitions = registry.get("kafka.consumer.assigned.partitions").tags(tags).gauge();
assertThat(assignedPartitions.getId().getTag("client.id")).isEqualTo("consumer-" + consumerCount);
// global connection metrics
Gauge connectionCount = registry.get("kafka.consumer.connection.count").tags(tags).gauge();
assertThat(connectionCount.getId().getTag("client.id")).startsWith("consumer-" + consumerCount);
}
}
示例9
@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);
}
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);
}
}
示例10
@Test
public void shouldFilterMetric() {
MeterRegistry registry = new SimpleMeterRegistry();
BackendRegistries.registerMatchers(registry, EnumSet.allOf(Label.class), Collections.singletonList(new Match()
.setLabel("address")
.setType(MatchType.EQUALS)
.setValue("addr1")));
Counters counters = new Counters("my_counter", "", registry, Label.EB_ADDRESS);
counters.get("addr1").increment();
counters.get("addr2").increment();
Counter c = registry.find("my_counter").tags("address", "addr1").counter();
assertThat(c.count()).isEqualTo(1d);
c = registry.find("my_counter").tags("address", "addr2").counter();
assertThat(c).isNull();
}
示例11
@Test
public void shouldIgnoreGaugeLabel() {
MeterRegistry registry = new SimpleMeterRegistry();
BackendRegistries.registerMatchers(registry, ALL_LABELS, Collections.singletonList(new Match()
.setLabel("address")
.setType(MatchType.REGEX)
.setValue(".*")
.setAlias("_")));
Gauges<LongAdder> gauges = new Gauges<>("my_gauge", "", LongAdder::new, LongAdder::doubleValue, registry, Label.EB_ADDRESS);
gauges.get("addr1").increment();
gauges.get("addr1").increment();
gauges.get("addr2").increment();
Gauge g = registry.find("my_gauge").tags("address", "_").gauge();
assertThat(g.value()).isEqualTo(3d);
g = registry.find("my_gauge").tags("address", "addr1").gauge();
assertThat(g).isNull();
g = registry.find("my_gauge").tags("address", "addr2").gauge();
assertThat(g).isNull();
}
示例12
@Test
@DisplayName("callable task that throws exception is still recorded")
default void recordCallableException(MeterRegistry registry) {
Timer t = registry.timer("myTimer");
assertThrows(Exception.class, () -> {
t.recordCallable(() -> {
clock(registry).add(10, TimeUnit.NANOSECONDS);
throw new Exception("uh oh");
});
});
clock(registry).add(step());
assertAll(() -> assertEquals(1L, t.count()),
() -> assertEquals(10, t.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
}
示例13
private TransferManager(
final ControlStreamManager controlStreamsManager,
final TaskScheduler taskScheduler,
final AgentFileStreamProperties properties,
final MeterRegistry registry
) {
this.controlStreamsManager = controlStreamsManager;
this.taskScheduler = taskScheduler;
this.properties = properties;
this.registry = registry;
this.transferTimeOutCounter = registry.counter(TRANSFER_TIMEOUT_COUNTER);
this.transferSizeDistribution = registry.summary(TRANSFER_SIZE_DISTRIBUTION);
this.taskScheduler.scheduleAtFixedRate(
this::reapStalledTransfers,
this.properties.getStalledTransferCheckInterval()
);
}
示例14
/**
* Create a {@link JobFinishedSNSPublisher} unless one exists in the context already.
*
* @param properties configuration properties
* @param registry the metrics registry
* @param snsClient the Amazon SNS client
* @param dataServices The {@link DataServices} instance to use
* @return a {@link JobFinishedSNSPublisher}
*/
@Bean
@ConditionalOnProperty(value = SNSNotificationsProperties.ENABLED_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(JobFinishedSNSPublisher.class)
public JobFinishedSNSPublisher jobFinishedSNSPublisher(
final SNSNotificationsProperties properties,
final MeterRegistry registry,
final AmazonSNS snsClient,
final DataServices dataServices
) {
return new JobFinishedSNSPublisher(
snsClient,
properties,
dataServices,
registry,
GenieObjectMapper.getMapper()
);
}
示例15
@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);
}
示例16
MetricsSubscriber(CoreSubscriber<? super T> actual,
MeterRegistry registry, Clock clock, Tags commonTags) {
this.actual = actual;
this.clock = clock;
this.commonTags = commonTags;
this.registry = registry;
}
示例17
@Test
void uptimeMetricsMock() {
MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock());
RuntimeMXBean runtimeMXBean = mock(RuntimeMXBean.class);
when(runtimeMXBean.getUptime()).thenReturn(1337L);
when(runtimeMXBean.getStartTime()).thenReturn(4711L);
new UptimeMetrics(runtimeMXBean, emptyList()).bindTo(registry);
assertThat(registry.get("process.uptime").timeGauge().value()).isEqualTo(1.337);
assertThat(registry.get("process.start.time").timeGauge().value()).isEqualTo(4.711);
}
示例18
@Autowired
public void bindEntityManagerFactoriesToRegistry( Map<String, EntityManagerFactory> entityManagerFactories,
MeterRegistry registry )
{
entityManagerFactories
.forEach( ( name, factory ) -> bindEntityManagerFactoryToRegistry( name, factory, registry ) );
}
示例19
@Deprecated
@Test
default void histogramCounts(MeterRegistry registry) {
DistributionSummary s = DistributionSummary.builder("my.summmary")
.serviceLevelObjectives(1.0)
.register(registry);
s.record(1);
assertThat(s.histogramCountAtValue(1)).isEqualTo(1);
assertThat(s.histogramCountAtValue(2)).isNaN();
}
示例20
private void registerTimeGaugeForObject(MeterRegistry registry, ObjectName o, String jmxMetricName,
String meterName, Tags allTags, String description) {
TimeGauge
.builder(METRIC_NAME_PREFIX + meterName, getMBeanServer(), TimeUnit.MILLISECONDS,
s -> safeDouble(() -> s.getAttribute(o, jmxMetricName)))
.description(description).tags(allTags).register(registry);
}
示例21
/**
* Create an setup Task bean that does initial setup before any of the tasks start.
*
* @param registry The metrics registry to use
* @return An initial setup task object
*/
@Bean
@Order(value = 1)
@ConditionalOnMissingBean(InitialSetupTask.class)
public InitialSetupTask initialSetupTask(final MeterRegistry registry) {
return new InitialSetupTask(registry);
}
示例22
/**
* Constructor.
*
* @param execution The job execution object including the pid
* @param stdOut The std out output file
* @param stdErr The std err output file
* @param genieEventBus The event bus implementation to use
* @param registry The metrics event registry
* @param jobsProperties The properties for jobs
* @param processChecker The process checker
*/
JobMonitor(
@Valid final JobExecution execution,
@NotNull final File stdOut,
@NotNull final File stdErr,
@NonNull final GenieEventBus genieEventBus,
@NotNull final MeterRegistry registry,
@NotNull final JobsProperties jobsProperties,
@NotNull final ProcessChecker processChecker
) {
if (!SystemUtils.IS_OS_UNIX) {
throw new UnsupportedOperationException("Genie doesn't currently support " + SystemUtils.OS_NAME);
}
this.errorCount = 0;
this.id = execution.getId().orElseThrow(IllegalArgumentException::new);
this.execution = execution;
this.genieEventBus = genieEventBus;
this.processChecker = processChecker;
this.stdOut = stdOut;
this.stdErr = stdErr;
this.maxStdOutLength = jobsProperties.getMax().getStdOutSize();
this.maxStdErrLength = jobsProperties.getMax().getStdErrSize();
this.trigger = new ExponentialBackOffTrigger(
ExponentialBackOffTrigger.DelayType.FROM_PREVIOUS_SCHEDULING,
jobsProperties.getCompletionCheckBackOff().getMinInterval(),
execution.getCheckDelay().orElse(jobsProperties.getCompletionCheckBackOff().getMaxInterval()),
jobsProperties.getCompletionCheckBackOff().getFactor()
);
this.successfulCheckRate = registry.counter("genie.jobs.successfulStatusCheck.rate");
this.timeoutRate = registry.counter("genie.jobs.timeout.rate");
this.finishedRate = registry.counter("genie.jobs.finished.rate");
this.unsuccessfulCheckRate = registry.counter("genie.jobs.unsuccessfulStatusCheck.rate");
this.stdOutTooLarge = registry.counter("genie.jobs.stdOutTooLarge.rate");
this.stdErrTooLarge = registry.counter("genie.jobs.stdErrTooLarge.rate");
}
示例23
@Test void shouldCreateMeters() {
try (AdminClient adminClient = createAdmin()) {
metrics = new KafkaClientMetrics(adminClient);
MeterRegistry registry = new SimpleMeterRegistry();
metrics.bindTo(registry);
assertThat(registry.getMeters())
.hasSizeGreaterThan(0)
.extracting(meter -> meter.getId().getName())
.allMatch(s -> s.startsWith(METRIC_NAME_PREFIX));
}
}
示例24
@Test void shouldCreateMetersWithTags() {
try (Producer<String, String> producer = createProducer()) {
metrics = new KafkaClientMetrics(producer, tags);
MeterRegistry registry = new SimpleMeterRegistry();
metrics.bindTo(registry);
assertThat(registry.getMeters())
.hasSizeGreaterThan(0)
.extracting(meter -> meter.getId().getTag("app"))
.allMatch(s -> s.equals("myapp"));
}
}
示例25
@Test
public void testKstreamWordCountFunction() throws Exception {
SpringApplication app = new SpringApplication(WordCountProcessorApplication.class);
app.setWebApplicationType(WebApplicationType.NONE);
try (ConfigurableApplicationContext context = app.run(
"--server.port=0",
"--spring.jmx.enabled=false",
"--spring.cloud.stream.bindings.process-in-0.destination=words",
"--spring.cloud.stream.bindings.process-out-0.destination=counts",
"--spring.cloud.stream.kafka.streams.default.consumer.application-id=testKstreamWordCountFunction",
"--spring.cloud.stream.kafka.streams.binder.configuration.commit.interval.ms=1000",
"--spring.cloud.stream.kafka.streams.binder.configuration.default.key.serde" +
"=org.apache.kafka.common.serialization.Serdes$StringSerde",
"--spring.cloud.stream.kafka.streams.binder.configuration.default.value.serde" +
"=org.apache.kafka.common.serialization.Serdes$StringSerde",
"--spring.cloud.stream.kafka.streams.binder.brokers=" + embeddedKafka.getBrokersAsString())) {
receiveAndValidate("words", "counts");
final MeterRegistry meterRegistry = context.getBean(MeterRegistry.class);
Thread.sleep(100);
assertThat(meterRegistry.get("stream.thread.metrics.commit.total").gauge().value()).isEqualTo(1.0);
assertThat(meterRegistry.get("app.info.start.time.ms").gauge().value()).isNotNaN();
Assert.isTrue(LATCH.await(5, TimeUnit.SECONDS), "Failed to call customizers");
//Testing topology endpoint
final KafkaStreamsRegistry kafkaStreamsRegistry = context.getBean(KafkaStreamsRegistry.class);
final KafkaStreamsTopologyEndpoint kafkaStreamsTopologyEndpoint = new KafkaStreamsTopologyEndpoint(kafkaStreamsRegistry);
final String topology1 = kafkaStreamsTopologyEndpoint.kafkaStreamsTopology();
final String topology2 = kafkaStreamsTopologyEndpoint.kafkaStreamsTopology("testKstreamWordCountFunction");
assertThat(topology1).isNotEmpty();
assertThat(topology1).isEqualTo(topology2);
}
}
示例26
public WebMvcMetricsFilter(MeterRegistry registry, WebMvcTagsProvider tagsProvider,
String metricName, boolean autoTimeRequests,
HandlerMappingIntrospector mappingIntrospector) {
this.registry = registry;
this.tagsProvider = tagsProvider;
this.metricName = metricName;
this.autoTimeRequests = autoTimeRequests;
this.mappingIntrospector = mappingIntrospector;
}
示例27
@Test
default void recordMax(MeterRegistry registry) {
Timer timer = registry.timer("my.timer");
timer.record(10, TimeUnit.MILLISECONDS);
timer.record(1, TimeUnit.SECONDS);
clock(registry).add(step()); // for Atlas, which is step rather than ring-buffer based
assertThat(timer.max(TimeUnit.SECONDS)).isEqualTo(1);
assertThat(timer.max(TimeUnit.MILLISECONDS)).isEqualTo(1000);
//noinspection ConstantConditions
clock(registry).add(Duration.ofMillis(step().toMillis() * DistributionStatisticConfig.DEFAULT.getBufferLength()));
assertThat(timer.max(TimeUnit.SECONDS)).isEqualTo(0);
}
示例28
VertxEventBusMetrics(MeterRegistry registry) {
super(registry, MetricsDomain.EVENT_BUS);
handlers = longGauges("handlers", "Number of event bus handlers in use", Label.EB_ADDRESS);
pending = longGauges("pending", "Number of messages not processed yet", Label.EB_ADDRESS, Label.EB_SIDE);
processed = counters("processed", "Number of processed messages", Label.EB_ADDRESS, Label.EB_SIDE);
published = counters("published", "Number of messages published (publish / subscribe)", Label.EB_ADDRESS, Label.EB_SIDE);
sent = counters("sent", "Number of messages sent (point-to-point)", Label.EB_ADDRESS, Label.EB_SIDE);
received = counters("received", "Number of messages received", Label.EB_ADDRESS, Label.EB_SIDE);
delivered = counters("delivered", "Number of messages delivered to handlers", Label.EB_ADDRESS, Label.EB_SIDE);
discarded = counters("discarded", "Number of discarded messages", Label.EB_ADDRESS, Label.EB_SIDE);
replyFailures = counters("replyFailures", "Number of message reply failures", Label.EB_ADDRESS, Label.EB_FAILURE);
bytesRead = summaries("bytesRead", "Number of bytes received while reading messages from event bus cluster peers", Label.EB_ADDRESS);
bytesWritten = summaries("bytesWritten", "Number of bytes sent while sending messages to event bus cluster peers", Label.EB_ADDRESS);
}
示例29
@Test
@DisplayName("supports sending histograms of active task duration")
default void histogram(MeterRegistry registry) {
LongTaskTimer t = LongTaskTimer.builder("my.timer")
.serviceLevelObjectives(Duration.ofSeconds(10), Duration.ofSeconds(40), Duration.ofMinutes(1))
.register(registry);
List<Integer> samples = Arrays.asList(48, 42, 40, 35, 22, 16, 13, 8, 6, 4, 2);
int prior = samples.get(0);
for (Integer value : samples) {
clock(registry).add(prior - value, TimeUnit.SECONDS);
t.start();
prior = value;
}
clock(registry).add(samples.get(samples.size() - 1), TimeUnit.SECONDS);
CountAtBucket[] countAtBuckets = t.takeSnapshot().histogramCounts();
assertThat(countAtBuckets[0].bucket(TimeUnit.SECONDS)).isEqualTo(10);
assertThat(countAtBuckets[0].count()).isEqualTo(4);
assertThat(countAtBuckets[1].bucket(TimeUnit.SECONDS)).isEqualTo(40);
assertThat(countAtBuckets[1].count()).isEqualTo(9);
assertThat(countAtBuckets[2].bucket(TimeUnit.MINUTES)).isEqualTo(1);
assertThat(countAtBuckets[2].count()).isEqualTo(11);
}
示例30
@Test
public void testClientPreRegistration() {
log.info("--- Starting tests with client pre-registration ---");
final MeterRegistry meterRegistry = new SimpleMeterRegistry();
assertEquals(0, meterRegistry.getMeters().size());
final MetricCollectingClientInterceptor mcci = new MetricCollectingClientInterceptor(meterRegistry);
mcci.preregisterService(TestServiceGrpc.getServiceDescriptor());
MetricTestHelper.logMeters(meterRegistry.getMeters());
assertEquals(METHOD_COUNT * 3, meterRegistry.getMeters().size());
log.info("--- Test completed ---");
}