io.prometheus.client.Histogram Java Examples

The following examples show how to use io.prometheus.client.Histogram. 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: MetricsFilter.java    From client_java with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;

    String path = request.getRequestURI();

    Histogram.Timer timer = histogram
        .labels(getComponents(path), request.getMethod())
        .startTimer();

    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        timer.observeDuration();
    }
}
 
Example #2
Source File: HystrixMetricsCollector.java    From prometheus-hystrix with Apache License 2.0 6 votes vote down vote up
public Histogram.Child addHistogram(String subsystem, String metric, String helpDoc,
                                    SortedMap<String, String> labels) {
    lock.writeLock().lock();
    try {
        String name = name(subsystem, metric);
        Histogram histogram = histograms.get(name);
        if (histogram == null) {
            Histogram.Builder histogramBuilder = Histogram.build().name(name).help(helpDoc)
                    .labelNames(labels.keySet().toArray(new String[]{}));
            histogramParameterizer.accept(histogramBuilder);
            histogram = histogramBuilder.create();
            histogram.register(registry);
            histograms.put(name, histogram);
        }
        return histogram.labels(labels.values().toArray(new String[]{}));
    } finally {
        lock.writeLock().unlock();
    }
}
 
Example #3
Source File: CallMeterImpl.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Override
public Timer startTimer() {

    final Histogram.Timer timer = collectors.histogram.startTimer();
    collectors.totalCounter.inc();

    return new Timer() {
        @Override
        public void onError() {
            collectors.errorCounter.inc();
        }

        @Override
        public void onSuccess() {
            timer.observeDuration();
        }
    };
}
 
Example #4
Source File: CallMeterChildImpl.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Override
public Timer startTimer() {
    final Histogram.Timer timer = histogram.startTimer();
    totalCounter.inc();

    return new Timer() {
        @Override
        public void onError() {
            errorCounter.inc();
        }

        @Override
        public void onSuccess() {
            timer.observeDuration();
        }
    };
}
 
Example #5
Source File: AggregatedTypeUpdater.java    From jmeter-prometheus-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void update(SampleEvent event) {
	try {
		Collector collector = registry.getOrCreateAndRegister(this.config);
		
		String[] labels = this.labelValues(event);
		long measurement = this.measure(event);
		
		if(collector instanceof Histogram) {
			Histogram hist = (Histogram) collector;
			hist.labels(labels).observe(measurement);
			
		}else if(collector instanceof Summary) {
			Summary sum = (Summary) collector;
			sum.labels(labels).observe(measurement);
		}
		
	} catch(Exception e) {
		log.error("Did not update {} because of error: {}", this.config.getMetricName(), e.getMessage());
		log.debug(e.getMessage(), e);
	}

}
 
Example #6
Source File: ClientMetrics.java    From java-grpc-prometheus with Apache License 2.0 5 votes vote down vote up
private ClientMetrics(
    GrpcMethod method,
    Counter rpcStarted,
    Counter rpcCompleted,
    Counter streamMessagesReceived,
    Counter streamMessagesSent,
    Optional<Histogram> completedLatencySeconds) {
  this.method = method;
  this.rpcStarted = rpcStarted;
  this.rpcCompleted = rpcCompleted;
  this.streamMessagesReceived = streamMessagesReceived;
  this.streamMessagesSent = streamMessagesSent;
  this.completedLatencySeconds = completedLatencySeconds;
}
 
Example #7
Source File: PrometheusClientInstanceProfiler.java    From canal with Apache License 2.0 5 votes vote down vote up
private PrometheusClientInstanceProfiler() {
    this.outboundCounter = Counter.build()
            .labelNames(DEST_LABELS)
            .name(OUTBOUND_BYTES)
            .help("Total bytes sent to client.")
            .create();
    this.packetsCounter = Counter.build()
            .labelNames(new String[]{DEST, "packetType"})
            .name(PACKET_TYPE)
            .help("Total packets sent to client.")
            .create();
    this.emptyBatchesCounter = Counter.build()
            .labelNames(DEST_LABELS)
            .name(EMPTY_BATCHES)
            .help("Total empty batches sent to client.")
            .create();
    this.errorsCounter = Counter.build()
            .labelNames(new String[]{DEST, "errorCode"})
            .name(ERRORS)
            .help("Total client request errors.")
            .create();
    this.responseLatency = Histogram.build()
            .labelNames(DEST_LABELS)
            .name(LATENCY)
            .help("Client request latency.")
            // buckets in milliseconds
            .buckets(2.5, 10.0, 25.0, 100.0)
            .create();
}
 
Example #8
Source File: OMetricsRequestCycleListener.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void onBeginRequest(RequestCycle cycle) {
	Histogram.Timer requestTimer = HISTOGRAM_REQUESTS
									.labels(Boolean.toString(((WebRequest)cycle.getRequest()).isAjax()))
									.startTimer();
	cycle.setMetaData(REQUESTS_HISTOGRAM_KEY, requestTimer);
}
 
Example #9
Source File: PrometheusHistogramMetrics.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
protected Histogram create(String[] labelNames) {
    Histogram.Builder builder = Histogram.build().name(name).help(tips);
    if (builder != null && buckets.length > 0) {
        builder = builder.buckets(buckets);
    }
    return builder.labelNames(labelNames).register();
}
 
Example #10
Source File: PrometheusHistogramMetrics.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void observe(double value) {
    Histogram.Child metrics = inner.getMetric();
    if (metrics != null) {
        metrics.observe(value);
    }
}
 
Example #11
Source File: CallMeter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
private CallCollectors createMetrics() {
    final Counter totalCounter = Counter
        .build()
        .namespace(namespace)
        .subsystem(subsystem)
        .name(name + "_total")
        .help(help + " total")
        .labelNames(labelNames)
        .create();

    final Counter errorCounter = Counter
        .build()
        .namespace(namespace)
        .subsystem(subsystem)
        .name(name + "_failures_total")
        .help(help + " failures total")
        .labelNames(labelNames)
        .create();

    final Histogram histogram = Histogram
        .build()
        .namespace(namespace)
        .subsystem(subsystem)
        .name(name + "_latency")
        .help(help + " latency")
        .labelNames(labelNames)
        .create();

    return new CallCollectors(histogram, totalCounter, errorCounter);
}
 
Example #12
Source File: AbstractCircuitBreakerMetrics.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
protected AbstractCircuitBreakerMetrics(MetricNames names, MetricOptions options) {
    this.names = requireNonNull(names);
    requireNonNull(options);
    callsHistogram = Histogram
        .build(names.getCallsMetricName(), "Total number of calls by kind")
        .labelNames("name", "kind")
        .buckets(options.getBuckets())
        .create().register(collectorRegistry);
}
 
Example #13
Source File: ServerMetrics.java    From java-grpc-prometheus with Apache License 2.0 5 votes vote down vote up
private ServerMetrics(
    GrpcMethod method,
    Counter serverStarted,
    Counter serverHandled,
    Counter serverStreamMessagesReceived,
    Counter serverStreamMessagesSent,
    Optional<Histogram> serverHandledLatencySeconds) {
  this.method = method;
  this.serverStarted = serverStarted;
  this.serverHandled = serverHandled;
  this.serverStreamMessagesReceived = serverStreamMessagesReceived;
  this.serverStreamMessagesSent = serverStreamMessagesSent;
  this.serverHandledLatencySeconds = serverHandledLatencySeconds;
}
 
Example #14
Source File: PrometheusMetrics.java    From vertx-kafka-service with Apache License 2.0 5 votes vote down vote up
public InProgressMessage messageStarted() {
    MESSAGES.labels(topic, consumerGroup, instanceId).inc();
    IN_PROGRESS_MESSAGES.labels(topic, consumerGroup, instanceId).inc();
    final Histogram.Timer timer = DURATION_HISTOGRAM.labels(topic, consumerGroup, instanceId).startTimer();
    return () -> {
        timer.observeDuration();
        IN_PROGRESS_MESSAGES.labels(topic, consumerGroup, instanceId).dec();
    };
}
 
Example #15
Source File: MetricsCollectorFilter.java    From Architecting-Modern-Java-EE-Applications with MIT License 5 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    if (!(req instanceof HttpServletRequest)) {
        chain.doFilter(req, res);
        return;
    }

    String url = ((HttpServletRequest) req).getRequestURI();
    try (Histogram.Timer ignored = requestDuration.labels(url).startTimer()) {
        chain.doFilter(req, res);
    }
}
 
Example #16
Source File: PrometheusReporter.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Override
public void observeTime(Object timer) {
    try {
        ((Histogram.Timer) timer).observeDuration();
    } catch (ClassCastException e) {
        log.error("Error in casting timer object to Prometheus Histogram timer", e);
    }
}
 
Example #17
Source File: PrometheusClientInstanceProfiler.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
private PrometheusClientInstanceProfiler() {
    this.outboundCounter = Counter.build()
            .labelNames(DEST_LABELS)
            .name(OUTBOUND_BYTES)
            .help("Total bytes sent to client.")
            .create();
    this.packetsCounter = Counter.build()
            .labelNames(new String[]{DEST, "packetType"})
            .name(PACKET_TYPE)
            .help("Total packets sent to client.")
            .create();
    this.emptyBatchesCounter = Counter.build()
            .labelNames(DEST_LABELS)
            .name(EMPTY_BATCHES)
            .help("Total empty batches sent to client.")
            .create();
    this.errorsCounter = Counter.build()
            .labelNames(new String[]{DEST, "errorCode"})
            .name(ERRORS)
            .help("Total client request errors.")
            .create();
    this.responseLatency = Histogram.build()
            .labelNames(DEST_LABELS)
            .name(LATENCY)
            .help("Client request latency.")
            // buckets in milliseconds
            .buckets(2.5, 10.0, 25.0, 100.0)
            .create();
}
 
Example #18
Source File: PrometheusMetricsReporter.java    From java-metrics with Apache License 2.0 5 votes vote down vote up
private PrometheusMetricsReporter(String name,
        CollectorRegistry registry, List<MetricLabel> labels) {
    super(labels);

    String[] labelNames = getLabelNames();
    this.histogram = Histogram.build().name(name).help("The span metrics")
            .labelNames(labelNames).register(registry);
}
 
Example #19
Source File: MetricsFetcherMetrics.java    From promregator with Apache License 2.0 5 votes vote down vote up
public Histogram.Child getLatencyRequest() {
	if (requestLatency == null)
		return null;
	
	if (!this.requestLatencyEnabled)
		return null;
	
	return requestLatency.labels(this.ownTelemetryLabels);
}
 
Example #20
Source File: MetricsCollectorFilter.java    From Architecting-Modern-Java-EE-Applications with MIT License 5 votes vote down vote up
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    requestDuration = Histogram.build("request_duration_seconds", "Duration of HTTP requests in seconds")
            .buckets(0.1, 0.4, 1.0)
            .labelNames("request_uri")
            .register();
}
 
Example #21
Source File: InternalMetrics.java    From promregator with Apache License 2.0 5 votes vote down vote up
@PostConstruct
@SuppressWarnings("PMD.UnusedPrivateMethod")
// method is required and called by the Spring Framework
private void registerMetrics() {
	if (!this.enabled)
		return;
	
	this.latencyCFFetch = Histogram.build("promregator_cffetch_latency", "Latency on retrieving CF values")
			.labelNames("request_type").linearBuckets(0.1, 0.1, 50).register();
	
	this.autoRefreshingCacheMapSize = Gauge.build("promregator_autorefreshingcachemap_size", "The size of objects stored in an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	
	this.autoRefreshingCacheMapExpiry = Counter.build("promregator_autorefreshingcachemap_expiry", "The number of objects having expired so far in an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	this.autoRefreshingCacheMapRefreshSuccess = Counter.build("promregator_autorefreshingcachemap_refresh_success", "The number of successful refreshes of object so far in an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	this.autoRefreshingCacheMapRefreshFailure = Counter.build("promregator_autorefreshingcachemap_refresh_failure", "The number of failed refreshes of object so far in an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	
	this.autoRefreshingCacheMapErroneousEntryDisplaced = Counter.build("promregator_autorefreshingcachemap_erroneous_entry_displaced", "The number of cache items displaced in an AutoRefreshingCacheMap, because they were detected to be erroneous")
			.labelNames(CACHE_MAP_NAME).register();

	this.autoRefreshingCacheMapLastScan = Gauge.build("promregator_autorefreshingcachemap_scantimestamp", "The timestamp of the last execution of the RefreshThread execution of an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	
	this.connectionWatchdogReconnects = Counter.build("promregator_connection_watchdog_reconnect", "The number of reconnection attempts made by the Connection Watchdog")
			.register();
	
	this.caffeineCacheMetricsCollector = new CacheMetricsCollector().register();
	
	this.rateLimitWaitTime = Histogram.build("promregator_cffetch_ratelimit_waittime", "Wait time due to CFCC rate limiting")
			.labelNames("request_type").linearBuckets(0.0, 0.05, 50).register();
	
	CollectorRegistry.defaultRegistry.register(new InternalCollector());
}
 
Example #22
Source File: CallCollectors.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
CallCollectors(Histogram histogram, Counter totalCounter, Counter errorCounter) {
    this.histogram = histogram;
    this.totalCounter = totalCounter;
    this.errorCounter = errorCounter;
}
 
Example #23
Source File: PrometheusReporter.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
@Override
public Object getTimer(String metricName,  String[] properties) {
    Histogram timer = (Histogram) metricMap.get(metricName);
    return timer.labels(properties).startTimer();
}
 
Example #24
Source File: MetricsFilter.java    From client_java with Apache License 2.0 4 votes vote down vote up
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    Histogram.Builder builder = Histogram.build()
            .labelNames("path", "method");

    if (filterConfig == null && isEmpty(metricName)) {
        throw new ServletException("No configuration object provided, and no metricName passed via constructor");
    }

    if (filterConfig != null) {
        if (isEmpty(metricName)) {
            metricName = filterConfig.getInitParameter(METRIC_NAME_PARAM);
            if (isEmpty(metricName)) {
                throw new ServletException("Init parameter \"" + METRIC_NAME_PARAM + "\" is required; please supply a value");
            }
        }

        if (!isEmpty(filterConfig.getInitParameter(HELP_PARAM))) {
            help = filterConfig.getInitParameter(HELP_PARAM);
        }

        // Allow overriding of the path "depth" to track
        if (!isEmpty(filterConfig.getInitParameter(PATH_COMPONENT_PARAM))) {
            pathComponents = Integer.valueOf(filterConfig.getInitParameter(PATH_COMPONENT_PARAM));
        }

        // Allow users to override the default bucket configuration
        if (!isEmpty(filterConfig.getInitParameter(BUCKET_CONFIG_PARAM))) {
            String[] bucketParams = filterConfig.getInitParameter(BUCKET_CONFIG_PARAM).split(",");
            buckets = new double[bucketParams.length];

            for (int i = 0; i < bucketParams.length; i++) {
                buckets[i] = Double.parseDouble(bucketParams[i]);
            }
        }
    }

    if (buckets != null) {
        builder = builder.buckets(buckets);
    }

    histogram = builder
            .help(help)
            .name(metricName)
            .register();
}
 
Example #25
Source File: OMetricsRequestCycleListener.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
@Override
public void onEndRequest(RequestCycle cycle) {
	Histogram.Timer requestTimer = cycle.getMetaData(REQUESTS_HISTOGRAM_KEY);
	requestTimer.observeDuration();
}
 
Example #26
Source File: PrometheusMetrics.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public static Histogram getDroolsEvaluationTimeHistogram() {
    return droolsEvaluationTimeHistogram;
}
 
Example #27
Source File: HystrixMetricsCollector.java    From prometheus-hystrix with Apache License 2.0 4 votes vote down vote up
public HystrixMetricsCollector(String namespace, Consumer<Histogram.Builder> histogramParameterizer) {
    this.namespace = namespace;
    this.histogramParameterizer = histogramParameterizer;
}
 
Example #28
Source File: HystrixPrometheusMetricsPublisherCommand.java    From prometheus-hystrix with Apache License 2.0 4 votes vote down vote up
private Histogram.Child addHistogram(String metric, String helpDoc) {
    return collector.addHistogram("hystrix_command", metric, helpDoc, labels);
}
 
Example #29
Source File: HystrixPrometheusMetricsPublisher.java    From prometheus-hystrix with Apache License 2.0 4 votes vote down vote up
public void buildAndRegister() {
    HystrixPlugins plugins = HystrixPlugins.getInstance();

    // memorize the registered plugins
    HystrixCommandExecutionHook commandExecutionHook = plugins.getCommandExecutionHook();
    HystrixEventNotifier eventNotifier = plugins.getEventNotifier();
    HystrixMetricsPublisher metricsPublisher = plugins.getMetricsPublisher();
    HystrixPropertiesStrategy propertiesStrategy = plugins.getPropertiesStrategy();
    HystrixConcurrencyStrategy concurrencyStrategy = plugins.getConcurrencyStrategy();

    HystrixMetricsCollector collector = new HystrixMetricsCollector(namespace,
            new Consumer<Histogram.Builder>() {
                @Override
                public void accept(Histogram.Builder builder) {
                    if (metrics == MetricsType.EXPONENTIAL) {
                        builder.exponentialBuckets(exponentialStart, exponentialFactor, exponentialCount);
                    } else if (metrics == MetricsType.LINEAR) {
                        builder.linearBuckets(linearStart, linearWidth, linearCount);
                    } else if (metrics == MetricsType.DISTINCT) {
                        builder.buckets(distinctBuckets);
                    } else if (metrics == MetricsType.DEFAULT) {
                        // nothing to do
                    } else {
                        throw new IllegalStateException("unknown enum state " + metrics);
                    }
                }
            }).register(registry);

    // wrap the metrics publisher plugin
    HystrixPrometheusMetricsPublisher wrappedMetricsPublisher =
            new HystrixPrometheusMetricsPublisher(exportProperties,
                    exportDeprecatedMetrics, collector, metricsPublisher);

    // reset all plugins
    HystrixPlugins.reset();
    // the following statement wouldn't be necessary, but I'm paranoid that reset might
    // change the plugin instance.
    plugins = HystrixPlugins.getInstance();

    // set previous values for all plugins, but not if they would use the default implementation,
    // as this would block the slot for plugins to be registered.

    // REASON: if there was no previous setting, Hystrix would have returned the default implementation
    // and not all other plugin use the reset-and-wrap approach we do here.

    // ASSUMPTION: the default strategies/hooks can't wrap a different strategy/hook

    // CAVEAT: instead of a default implementation there is a sophisticated Archaius configuration mechanism
    // to determine a class from property settings. There is a corner case where someone would register a
    // default implementation manually overriding an Archaius configuration. Therefore this is configurable
    // using "registerDefaultPlugins".

    if (registerDefaultPlugins || concurrencyStrategy.getClass() != HystrixConcurrencyStrategyDefault.class) {
        plugins.registerConcurrencyStrategy(concurrencyStrategy);
    }
    if (registerDefaultPlugins || commandExecutionHook.getClass() != HystrixCommandExecutionHookDefault.class) {
        plugins.registerCommandExecutionHook(commandExecutionHook);
    }
    if (registerDefaultPlugins || eventNotifier.getClass() != HystrixEventNotifierDefault.class) {
        plugins.registerEventNotifier(eventNotifier);
    }
    if (registerDefaultPlugins || propertiesStrategy.getClass() != HystrixPropertiesStrategyDefault.class) {
        plugins.registerPropertiesStrategy(propertiesStrategy);
    }

    // ... except for the metrics publisher that will now be wrapped
    plugins.registerMetricsPublisher(wrappedMetricsPublisher);
}
 
Example #30
Source File: RequestLatencyHistogramMetricsTracker.java    From soul with Apache License 2.0 4 votes vote down vote up
@Override
public HistogramMetricsTrackerDelegate startTimer(final String... labelValues) {
    Histogram.Timer timer = REQUEST_LATENCY.startTimer();
    return new PrometheusHistogramMetricsTrackerDelegate(timer);
}