io.micrometer.core.instrument.Clock Java Examples

The following examples show how to use io.micrometer.core.instrument.Clock. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MoreNamingConventionsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static DropwizardMeterRegistry newDropwizardRegistry() {
    return new DropwizardMeterRegistry(new DropwizardConfig() {
        @Override
        public String prefix() {
            return "dropwizard";
        }

        @Override
        @Nullable
        public String get(String k) {
            return null;
        }
    }, new MetricRegistry(), HierarchicalNameMapper.DEFAULT, Clock.SYSTEM) {
        @Override
        protected Double nullGaugeValue() {
            return 0.0;
        }
    };
}
 
Example #2
Source File: SampleRegistries.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static KairosMeterRegistry kairos() {
    return new KairosMeterRegistry(new KairosConfig() {
        @Override
        public String get(String key) {
            return null;
        }

        @Override
        public String uri() {
            return "http://localhost:8083/api/v1/datapoints";
        }

        @Override
        public Duration step() {
            return Duration.ofSeconds(10);
        }
    }, Clock.SYSTEM);
}
 
Example #3
Source File: JHipsterLoggingMetricsExportConfiguration.java    From jhipster with Apache License 2.0 6 votes vote down vote up
/**
 * <p>consoleLoggingRegistry.</p>
 *
 * @param dropwizardRegistry a {@link com.codahale.metrics.MetricRegistry} object.
 * @return a {@link io.micrometer.core.instrument.MeterRegistry} object.
 */
@Bean
public MeterRegistry consoleLoggingRegistry(MetricRegistry dropwizardRegistry) {
    DropwizardConfig dropwizardConfig = new DropwizardConfig() {
        @Override
        public String prefix() {
            return "console";
        }

        @Override
        public String get(String key) {
            return null;
        }
    };

    return new DropwizardMeterRegistry(dropwizardConfig, dropwizardRegistry, HierarchicalNameMapper.DEFAULT, Clock.SYSTEM) {
        @Override
        protected Double nullGaugeValue() {
            return null;
        }
    };
}
 
Example #4
Source File: AtlasMeterRegistryTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Issue("#484")
@Test
void publishOneLastTimeOnClose(@WiremockResolver.Wiremock WireMockServer server) {
    AtlasConfig config = new AtlasConfig() {
        @Nullable
        @Override
        public String get(String k) {
            return null;
        }

        @Override
        public String uri() {
            return server.baseUrl() + "/api/v1/publish";
        }
    };

    server.stubFor(any(anyUrl()));
    new AtlasMeterRegistry(config, Clock.SYSTEM).close();
    server.verify(postRequestedFor(urlEqualTo("/api/v1/publish")));
}
 
Example #5
Source File: MonitoringConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
@Bean
public MetricsExporter graphiteExporter(GraphiteConfig graphiteConfig, Clock clock) {
    NamingConvention namingConvention = namingConvention();
    GraphiteMeterRegistry registry = new GraphiteMeterRegistry(graphiteConfig, (id, convention) -> {
        String prefix = "bookpub.app.";
        String tags = "";

        if (id.getTags().iterator().hasNext()) {
            tags = "." + id.getConventionTags(convention).stream()
                    .map(t -> t.getKey() + "." + t.getValue())
                    .map(nameSegment -> nameSegment.replace(" ", "_"))
                    .collect(Collectors.joining("."));
        }

        return prefix + id.getConventionName(convention) + tags;
    }, clock);
    registry.config().namingConvention(namingConvention);
    registry.start();
    return () -> registry;
}
 
Example #6
Source File: MonitoringConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
@Bean
public MetricsExporter graphiteExporter(GraphiteConfig graphiteConfig, Clock clock) {
    NamingConvention namingConvention = namingConvention();
    GraphiteMeterRegistry registry = new GraphiteMeterRegistry(graphiteConfig, (id, convention) -> {
        String prefix = "bookpub.app.";
        String tags = "";

        if (id.getTags().iterator().hasNext()) {
            tags = "." + id.getConventionTags(convention).stream()
                    .map(t -> t.getKey() + "." + t.getValue())
                    .map(nameSegment -> nameSegment.replace(" ", "_"))
                    .collect(Collectors.joining("."));
        }

        return prefix + id.getConventionName(convention) + tags;
    }, clock);
    registry.config().namingConvention(namingConvention);
    registry.start();
    return () -> registry;
}
 
Example #7
Source File: MetricsClientHttpRequestInterceptor.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
    throws IOException {
    final String urlTemplate = urlTemplateHolder.get();
    urlTemplateHolder.remove();
    final Clock clock = meterRegistry.config().clock();
    final long startTime = clock.monotonicTime();
    IOException ex = null;
    ClientHttpResponse response = null;
    try {
        response = execution.execute(request, body);
        return response;
    } catch (IOException e) {
        ex = e;
        throw e;
    } finally {
        getTimeBuilder(urlTemplate, request, response, ex).register(this.meterRegistry)
            .record(clock.monotonicTime() - startTime, TimeUnit.NANOSECONDS);
    }
}
 
Example #8
Source File: SampleRegistries.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static StatsdMeterRegistry etsyStatsd() {
    return new StatsdMeterRegistry(new StatsdConfig() {
        @Override
        public Duration step() {
            return Duration.ofSeconds(10);
        }

        @Override
        @Nullable
        public String get(String k) {
            return null;
        }

        @Override
        public StatsdFlavor flavor() {
            return StatsdFlavor.ETSY;
        }
    }, Clock.SYSTEM);
}
 
Example #9
Source File: StatsdMeterRegistryPublishTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@EnumSource(StatsdProtocol.class)
void receiveMetricsSuccessfully(StatsdProtocol protocol) throws InterruptedException {
    serverLatch = new CountDownLatch(3);
    server = startServer(protocol, 0);

    final int port = server.address().getPort();

    meterRegistry = new StatsdMeterRegistry(getUnbufferedConfig(protocol, port), Clock.SYSTEM);
    startRegistryAndWaitForClient();
    Counter counter = Counter.builder("my.counter").register(meterRegistry);
    counter.increment();
    counter.increment();
    counter.increment();
    assertThat(serverLatch.await(3, TimeUnit.SECONDS)).isTrue();
}
 
Example #10
Source File: SampleRegistries.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static DatadogMeterRegistry datadog(String apiKey, String applicationKey) {
    DatadogConfig config = new DatadogConfig() {
        @Override
        public String apiKey() {
            return apiKey;
        }

        @Override
        public String applicationKey() {
            return applicationKey;
        }

        @Override
        public Duration step() {
            return Duration.ofSeconds(10);
        }

        @Override
        @Nullable
        public String get(String k) {
            return null;
        }
    };

    return new DatadogMeterRegistry(config, Clock.SYSTEM);
}
 
Example #11
Source File: SkywalkingDistributionSummary.java    From skywalking with Apache License 2.0 6 votes vote down vote up
protected SkywalkingDistributionSummary(Id id, MeterId meterId, SkywalkingConfig config, Clock clock,
                                        DistributionStatisticConfig distributionStatisticConfig, double scale,
                                        boolean supportsAggregablePercentiles) {
    super(id, clock, distributionStatisticConfig, scale, supportsAggregablePercentiles);

    // meter base name
    String baseName = meterId.getName();

    this.counter = MeterBuilder.buildCounter(meterId.copyTo(baseName + "_count", MeterId.MeterType.COUNTER), config);
    this.sum = MeterBuilder.buildCounter(meterId.copyTo(baseName + "_sum", MeterId.MeterType.COUNTER), config);
    this.maxAdder = new DoubleAccumulator((a, b) -> a > b ? a : b, 0.000);
    this.max = MeterFactory.gauge(meterId.copyTo(baseName + "_max", MeterId.MeterType.GAUGE),
        () -> maxAdder.doubleValue()).build();

    this.histogram = MeterBuilder.buildHistogram(meterId, supportsAggregablePercentiles, distributionStatisticConfig, false);
}
 
Example #12
Source File: ActionTimer.java    From java-dcp-client with Apache License 2.0 6 votes vote down vote up
private ActionTimer(MeterRegistry registry, String name, Iterable<Tag> tags, Clock clock,
                    LogLevel successLogLevel, LogLevel failureLogLevel) {
  this.registry = requireNonNull(registry);
  this.name = requireNonNull(name);
  this.clock = requireNonNull(clock);
  this.successLogLevel = requireNonNull(successLogLevel);
  this.failureLogLevel = requireNonNull(failureLogLevel);
  this.logger = LoggerFactory.getLogger(ActionTimer.class.getName() + "." + name);

  List<Tag> tagList = new ArrayList<>();
  tags.forEach(tagList::add);
  this.baseTags = Collections.unmodifiableList(tagList);

  List<Tag> successTags = new ArrayList<>(baseTags);
  successTags.add(Tag.of("result", "success"));
  successTags.add(Tag.of("exception", "none"));
  this.successTimer = registry.timer(name, successTags);
}
 
Example #13
Source File: DatadogMetricMetadataTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@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(),
        false);

    assertThat(metricMetadata.editDescriptionMetadataBody()).isNull();
}
 
Example #14
Source File: DestinationPublishingMetricsAutoConfiguration.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public DefaultDestinationPublishingMeterRegistry defaultDestinationPublishingMeterRegistry(
		ApplicationMetricsProperties applicationMetricsProperties,
		MetersPublisherBinding publisherBinding,
		MetricsPublisherConfig metricsPublisherConfig, Clock clock) {
	DefaultDestinationPublishingMeterRegistry registry = new DefaultDestinationPublishingMeterRegistry(
			applicationMetricsProperties, publisherBinding, metricsPublisherConfig,
			clock);

	if (StringUtils.hasText(applicationMetricsProperties.getMeterFilter())) {
		registry.config()
				.meterFilter(MeterFilter.denyUnless(id -> PatternMatchUtils
						.simpleMatch(applicationMetricsProperties.getMeterFilter(),
								id.getName())));
	}
	return registry;
}
 
Example #15
Source File: SampleRegistries.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static InfluxMeterRegistry influx() {
    return new InfluxMeterRegistry(new InfluxConfig() {
        @Override
        public String userName() {
            return "admin";
        }

        @Override
        public String password() {
            return "admin";
        }

        @Override
        public Duration step() {
            return Duration.ofSeconds(10);
        }

        @Override
        @Nullable
        public String get(String k) {
            return null;
        }
    }, Clock.SYSTEM);
}
 
Example #16
Source File: SampleRegistries.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static StatsdMeterRegistry telegrafStatsd() {
    return new StatsdMeterRegistry(new StatsdConfig() {
        @Override
        public Duration step() {
            return Duration.ofSeconds(10);
        }

        @Override
        @Nullable
        public String get(String k) {
            return null;
        }

        @Override
        public StatsdFlavor flavor() {
            return StatsdFlavor.TELEGRAF;
        }
    }, Clock.SYSTEM);
}
 
Example #17
Source File: SampleRegistries.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static NewRelicMeterRegistry newRelic(String accountId, String apiKey) {
    return new NewRelicMeterRegistry(new NewRelicConfig() {
        @Override
        public String accountId() {
            return accountId;
        }

        @Override
        public String apiKey() {
            return apiKey;
        }

        @Override
        public Duration step() {
            return Duration.ofSeconds(10);
        }

        @Override
        @Nullable
        public String get(String k) {
            return null;
        }
    }, Clock.SYSTEM);
}
 
Example #18
Source File: AbstractTimeWindowHistogram.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
AbstractTimeWindowHistogram(Clock clock, DistributionStatisticConfig distributionStatisticConfig, Class<T> bucketType,
                            boolean supportsAggregablePercentiles) {
    this.clock = clock;
    this.distributionStatisticConfig = validateDistributionConfig(distributionStatisticConfig);
    this.supportsAggregablePercentiles = supportsAggregablePercentiles;

    final int ageBuckets = distributionStatisticConfig.getBufferLength();
    if (ageBuckets <= 0) {
        rejectHistogramConfig("bufferLength (" + ageBuckets + ") must be greater than 0.");
    }

    ringBuffer = (T[]) Array.newInstance(bucketType, ageBuckets);

    durationBetweenRotatesMillis = distributionStatisticConfig.getExpiry().toMillis() / ageBuckets;
    if (durationBetweenRotatesMillis <= 0) {
        rejectHistogramConfig("expiry (" + distributionStatisticConfig.getExpiry().toMillis() +
                "ms) / bufferLength (" + ageBuckets + ") must be greater than 0.");
    }

    currentBucket = 0;
    lastRotateTimestampMillis = clock.wallTime();
}
 
Example #19
Source File: DropwizardMeterRegistries.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a newly-created {@link DropwizardMeterRegistry} instance with the specified
 * {@link MetricRegistry}, {@link HierarchicalNameMapper} and {@link Clock}.
 */
public static DropwizardMeterRegistry newRegistry(MetricRegistry registry,
                                                  HierarchicalNameMapper nameMapper,
                                                  Clock clock) {
    final DropwizardMeterRegistry meterRegistry = new DropwizardMeterRegistry(
            DEFAULT_DROPWIZARD_CONFIG,
            requireNonNull(registry, "registry"),
            requireNonNull(nameMapper, "nameMapper"),
            requireNonNull(clock, "clock")) {

        @Override
        protected Double nullGaugeValue() {
            return 0.0;
        }
    };

    return configureRegistry(meterRegistry);
}
 
Example #20
Source File: DefaultDestinationPublishingMeterRegistry.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
DefaultDestinationPublishingMeterRegistry(
		ApplicationMetricsProperties applicationProperties,
		MetersPublisherBinding publisherBinding,
		MetricsPublisherConfig metricsPublisherConfig, Clock clock) {
	super(clock);
	this.metricsPublisherConfig = metricsPublisherConfig;
	this.metricsConsumer = new MessageChannelPublisher(publisherBinding);
	this.applicationProperties = applicationProperties;
}
 
Example #21
Source File: SpectatorDistributionSummary.java    From micrometer with Apache License 2.0 5 votes vote down vote up
SpectatorDistributionSummary(Id id,
                             com.netflix.spectator.api.DistributionSummary distributionSummary,
                             Clock clock,
                             DistributionStatisticConfig distributionStatisticConfig,
                             double scale) {
    super(id, clock, distributionStatisticConfig, scale, false);
    this.summary = distributionSummary;
}
 
Example #22
Source File: WavefrontDistributionSummary.java    From micrometer with Apache License 2.0 5 votes vote down vote up
WavefrontDistributionSummary(Id id, Clock clock,
                             DistributionStatisticConfig distributionStatisticConfig,
                             double scale) {
    super(id, clock, distributionStatisticConfig, scale, false);
    delegate = distributionStatisticConfig.isPublishingHistogram() ?
        new WavefrontHistogramImpl(clock::wallTime) : null;
}
 
Example #23
Source File: StepTuple2.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public StepTuple2(Clock clock, long stepMillis,
                 T1 t1NoValue,
                 T2 t2NoValue,
                 Supplier<T1> t1Supplier,
                 Supplier<T2> t2Supplier) {
    this.clock = clock;
    this.stepMillis = stepMillis;
    this.t1NoValue = t1NoValue;
    this.t2NoValue = t2NoValue;
    this.t1Supplier = t1Supplier;
    this.t2Supplier = t2Supplier;
    this.t1Previous = t1NoValue;
    this.t2Previous = t2NoValue;
    lastInitPos = new AtomicLong(clock.wallTime() / stepMillis);
}
 
Example #24
Source File: OpenTSDBTimer.java    From micrometer with Apache License 2.0 5 votes vote down vote up
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);

    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), true);
        }
        else if (OpenTSDBFlavor.VictoriaMetrics.equals(flavor)) {
            histogram = new FixedBoundaryVictoriaMetricsHistogram();
        } else {
            histogram = null;
        }
    } else {
        histogram = null;
    }
}
 
Example #25
Source File: FluxMetrics.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
MetricsSubscriber(CoreSubscriber<? super T> actual,
		MeterRegistry registry,
		Clock clock,
		String sequenceName,
		Tags commonTags) {
	this.actual = actual;
	this.clock = clock;
	this.commonTags = commonTags;
	this.registry = registry;


	this.onNextIntervalTimer = Timer.builder(METER_ON_NEXT_DELAY)
	                                .tags(commonTags)
	                                .description(
			                                "Measures delays between onNext signals (or between onSubscribe and first onNext)")
	                                .register(registry);

	if (!REACTOR_DEFAULT_NAME.equals(sequenceName)) {
		this.requestedCounter = DistributionSummary.builder(METER_REQUESTED)
		                                           .tags(commonTags)
		                                           .description(
				                                           "Counts the amount requested to a named Flux by all subscribers, until at least one requests an unbounded amount")
		                                           .baseUnit("requested amount")
		                                           .register(registry);
	}
	else {
		requestedCounter = null;
	}
}
 
Example #26
Source File: TimeSeriesMeterRegistry.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
public TimeSeriesMeterRegistry(TimeSeriesManager timeSeriesManager,
                               TimeSeriesMetric metric,
                               TimeSeriesRegistryProperties config,
                               Map<String, String> customTags,String ...tagKeys) {
    super(new TimeSeriesPropertiesPropertiesConfigAdapter(config), Clock.SYSTEM);
    this.timeSeriesManager = timeSeriesManager;
    this.metric = metric;
    this.customTags = customTags;
    keys.addAll(customTags.keySet());
    keys.addAll(Arrays.asList(tagKeys));
    keys.addAll(config.getCustomTagKeys());
    start(DEFAULT_THREAD_FACTORY);
}
 
Example #27
Source File: SampleRegistries.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public static DynatraceMeterRegistry dynatrace(String apiToken, String uri) {
    return new DynatraceMeterRegistry(new DynatraceConfig() {
        @Override
        public String get(String key) {
            return null;
        }

        @Override
        public String apiToken() {
            return apiToken;
        }

        @Override
        public String uri() {
            return uri;
        }

        @Override
        public String deviceId() {
            return "sample";
        }

        @Override
        public Duration step() {
            return Duration.ofSeconds(10);
        }
    }, Clock.SYSTEM);
}
 
Example #28
Source File: TimeWindowMax.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public TimeWindowMax(Clock clock, long rotateFrequencyMillis, int bufferLength) {
    this.clock = clock;
    this.durationBetweenRotatesMillis = rotateFrequencyMillis;
    this.lastRotateTimestampMillis = clock.wallTime();
    this.currentBucket = 0;

    this.ringBuffer = new AtomicLong[bufferLength];
    for (int i = 0; i < bufferLength; i++) {
        this.ringBuffer[i] = new AtomicLong();
    }
}
 
Example #29
Source File: StatsdTimer.java    From micrometer with Apache License 2.0 5 votes vote down vote up
StatsdTimer(Id id, StatsdLineBuilder lineBuilder, FluxSink<String> sink, Clock clock,
            DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetector, TimeUnit baseTimeUnit, long stepMillis) {
    super(id, clock, distributionStatisticConfig, pauseDetector, baseTimeUnit, false);
    this.max = new StepDouble(clock, stepMillis);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
}
 
Example #30
Source File: MonoMetrics.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
MetricsSubscriber(CoreSubscriber<? super T> actual,
		MeterRegistry registry, Clock clock, Tags commonTags) {
	this.actual = actual;
	this.clock = clock;
	this.commonTags = commonTags;
	this.registry = registry;
}