org.springframework.boot.actuate.health.HealthEndpoint#io.prometheus.client.CollectorRegistry源码实例Demo

下面列出了org.springframework.boot.actuate.health.HealthEndpoint#io.prometheus.client.CollectorRegistry 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hadoop-ozone   文件: PrometheusServlet.java
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  String securityToken =
      (String) getServletContext().getAttribute(SECURITY_TOKEN);
  if (securityToken != null) {
    String authorizationHeader = req.getHeader("Authorization");
    if (authorizationHeader == null
        || !authorizationHeader.startsWith(BEARER)
        || !securityToken.equals(
            authorizationHeader.substring(BEARER.length() + 1))) {
      resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
      return;
    }
  }
  DefaultMetricsSystem.instance().publishMetricsNow();
  PrintWriter writer = resp.getWriter();
  getPrometheusSink().writeMetrics(writer);
  writer.write("\n\n#Dropwizard metrics\n\n");
  //print out dropwizard metrics used by ratis.
  TextFormat.write004(writer,
      CollectorRegistry.defaultRegistry.metricFamilySamples());
  writer.flush();
}
 
源代码2 项目: nifi   文件: PrometheusMetricsUtil.java
public static CollectorRegistry createJvmMetrics(JvmMetricsRegistry jvmMetricsRegistry, JvmMetrics jvmMetrics, String instId) {
    final String instanceId = StringUtils.isEmpty(instId) ? DEFAULT_LABEL_STRING : instId;
    jvmMetricsRegistry.setDataPoint(jvmMetrics.heapUsed(DataUnit.B), "JVM_HEAP_USED", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.heapUsage(), "JVM_HEAP_USAGE", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.nonHeapUsage(), "JVM_HEAP_NON_USAGE", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.threadCount(), "JVM_THREAD_COUNT", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.daemonThreadCount(), "JVM_DAEMON_THREAD_COUNT", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.uptime(), "JVM_UPTIME", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.fileDescriptorUsage(), "JVM_FILE_DESCRIPTOR_USAGE", instanceId);

    jvmMetrics.garbageCollectors()
            .forEach((name, stat) -> {
                jvmMetricsRegistry.setDataPoint(stat.getRuns(), "JVM_GC_RUNS", instanceId, name);
                jvmMetricsRegistry.setDataPoint(stat.getTime(TimeUnit.MILLISECONDS), "JVM_GC_TIME", instanceId, name);
            });

    return jvmMetricsRegistry.getRegistry();
}
 
源代码3 项目: pulsar   文件: JavaInstanceStarter.java
private void registerDefaultCollectors(CollectorRegistry registry) {
    // Add the JMX exporter for functionality similar to the kafka connect JMX metrics
    try {
        new JmxCollector("{}").register(registry);
    } catch (MalformedObjectNameException ex) {
        System.err.println(ex);
    }
    // Add the default exports from io.prometheus.client.hotspot.DefaultExports
    new StandardExports().register(registry);
    new MemoryPoolsExports().register(registry);
    new BufferPoolsExports().register(registry);
    new GarbageCollectorExports().register(registry);
    new ThreadExports().register(registry);
    new ClassLoadingExports().register(registry);
    new VersionInfoExports().register(registry);
}
 
public static CollectorRegistry createNifiMetrics(ProcessGroupStatus status, String applicationId) {
    String processGroupName = status.getName();
    AMOUNT_FLOWFILES_TOTAL.labels("sent", applicationId, processGroupName).set(status.getFlowFilesSent());
    AMOUNT_FLOWFILES_TOTAL.labels("transferred", applicationId, processGroupName).set(status.getFlowFilesTransferred());
    AMOUNT_FLOWFILES_TOTAL.labels("received", applicationId, processGroupName).set(status.getFlowFilesReceived());

    AMOUNT_BYTES_TOTAL.labels("sent", applicationId, processGroupName).set(status.getBytesSent());
    AMOUNT_BYTES_TOTAL.labels("read", applicationId, processGroupName).set(status.getBytesRead());
    AMOUNT_BYTES_TOTAL.labels("written", applicationId, processGroupName).set(status.getBytesWritten());
    AMOUNT_BYTES_TOTAL.labels("received", applicationId, processGroupName).set(status.getBytesReceived());
    AMOUNT_BYTES_TOTAL.labels("transferred", applicationId, processGroupName).set(status.getBytesTransferred());

    SIZE_CONTENT_TOTAL.labels("output", applicationId, processGroupName).set(status.getOutputContentSize());
    SIZE_CONTENT_TOTAL.labels("input", applicationId, processGroupName).set(status.getInputContentSize());
    SIZE_CONTENT_TOTAL.labels("queued", applicationId, processGroupName).set(status.getQueuedContentSize());

    AMOUNT_ITEMS.labels("output", applicationId, processGroupName).set(status.getOutputCount());
    AMOUNT_ITEMS.labels("input", applicationId, processGroupName).set(status.getInputCount());
    AMOUNT_ITEMS.labels("queued", applicationId, processGroupName).set(status.getQueuedCount());

    AMOUNT_THREADS_TOTAL.labels("nano", applicationId, processGroupName).set(status.getActiveThreadCount());

    return NIFI_METRICS_REGISTRY;
}
 
@Override
public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) {
  this.globalRegistry = globalRegistry;

  //prometheus default port allocation is here : https://github.com/prometheus/prometheus/wiki/Default-port-allocations
  String address =
      DynamicPropertyFactory.getInstance().getStringProperty(METRICS_PROMETHEUS_ADDRESS, "0.0.0.0:9696").get();

  try {
    InetSocketAddress socketAddress = getSocketAddress(address);
    register();
    this.httpServer = new HTTPServer(socketAddress, CollectorRegistry.defaultRegistry, true);

    LOGGER.info("Prometheus httpServer listened : {}.", address);
  } catch (Exception e) {
    throw new ServiceCombException("create http publish server failed,may bad address : " + address, e);
  }
}
 
源代码6 项目: client_java   文件: Graphite.java
/**
 * Push samples from the given registry to Graphite.
 */
public void push(CollectorRegistry registry) throws IOException {
  Socket s = new Socket(host, port);
  BufferedWriter writer = new BufferedWriter(new PrintWriter(s.getOutputStream()));
  Matcher m = INVALID_GRAPHITE_CHARS.matcher("");
  long now = System.currentTimeMillis() / 1000;
  for (Collector.MetricFamilySamples metricFamilySamples: Collections.list(registry.metricFamilySamples())) {
    for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) {
      m.reset(sample.name);
      writer.write(m.replaceAll("_"));
      for (int i = 0; i < sample.labelNames.size(); ++i) {
        m.reset(sample.labelValues.get(i));
        writer.write("." + sample.labelNames.get(i) + "." + m.replaceAll("_"));
      }
      writer.write(" " + sample.value + " " + now + "\n");
    }
  }
  writer.close();
  s.close();
}
 
源代码7 项目: flink   文件: PrometheusReporterTaskScopeTest.java
@Test
public void gaugesCanBeAddedSeveralTimesIfTheyDifferInLabels() throws UnirestException {
	Gauge<Integer> gauge1 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 3;
		}
	};
	Gauge<Integer> gauge2 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 4;
		}
	};

	taskMetricGroup1.gauge("my_gauge", gauge1);
	taskMetricGroup2.gauge("my_gauge", gauge2);

	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_gauge", LABEL_NAMES, labelValues1),
		equalTo(3.));
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_gauge", LABEL_NAMES, labelValues2),
		equalTo(4.));
}
 
@Test
public void customMetricNamesOverrideDefaultOnes() {
    TimeLimiterMetricsCollector.MetricNames names = TimeLimiterMetricsCollector.MetricNames
        .custom()
        .callsMetricName("custom_calls")
        .build();
    CollectorRegistry customRegistry = new CollectorRegistry();
    TimeLimiterMetricsCollector.ofTimeLimiterRegistry(names, timeLimiterRegistry)
        .register(customRegistry);
    timeLimiter.onSuccess();
    timeLimiter.onError(new RuntimeException());
    timeLimiter.onError(new TimeoutException());

    Double successfulCalls = getSampleValue(customRegistry, "custom_calls", KIND_SUCCESSFUL);
    Double failedCalls = getSampleValue(customRegistry, "custom_calls", KIND_FAILED);
    Double timeoutCalls = getSampleValue(customRegistry, "custom_calls", KIND_TIMEOUT);

    assertThat(successfulCalls).isNotNull();
    assertThat(failedCalls).isNotNull();
    assertThat(timeoutCalls).isNotNull();
}
 
源代码9 项目: client_java   文件: StandardExportsTest.java
@Test
public void testStandardExports() {
  CollectorRegistry registry = new CollectorRegistry();
  new StandardExports(new StatusReaderTest(), osBean, runtimeBean).register(registry);

  assertEquals(123 / 1.0E9,
      registry.getSampleValue("process_cpu_seconds_total", new String[]{}, new String[]{}), .0000001);
  assertEquals(10,
      registry.getSampleValue("process_open_fds", new String[]{}, new String[]{}), .001);
  assertEquals(20,
      registry.getSampleValue("process_max_fds", new String[]{}, new String[]{}), .001);
  assertEquals(456 / 1.0E3,
      registry.getSampleValue("process_start_time_seconds", new String[]{}, new String[]{}), .0000001);
  assertEquals(5900 * 1024,
      registry.getSampleValue("process_virtual_memory_bytes", new String[]{}, new String[]{}), .001);
  assertEquals(360 * 1024,
      registry.getSampleValue("process_resident_memory_bytes", new String[]{}, new String[]{}), .001);
}
 
源代码10 项目: sofa-lookout   文件: PushDemo.java
static void executeBatchJob() throws Exception {
    CollectorRegistry registry = CollectorRegistry.defaultRegistry;
    Counter requests = Counter.build()
            .name("my_library_requests_total").help("Total requests.")
            .labelNames("method").register();
    requests.labels("get").inc();


    PushGateway pushgateway = new PushGateway("127.0.0.1:7200/prom");
    // pushgateway.setConnectionFactory(new BasicAuthHttpConnectionFactory("my_user", "my_password"));
    Map<String, String> groupingkeys = new HashMap<>();
    groupingkeys.put("app", "xx");
    pushgateway.pushAdd(registry, "my_batch_job", groupingkeys);
    //  pushgateway.pushAdd(registry, "my_batch_job");
}
 
@Before
public void setup() {
    registry = new CollectorRegistry();
    circuitBreakerMetricsPublisher = new CircuitBreakerMetricsPublisher();
    circuitBreakerMetricsPublisher.register(registry);
    circuitBreakerRegistry = CircuitBreakerRegistry
        .of(CircuitBreakerConfig.ofDefaults(), circuitBreakerMetricsPublisher);

    CircuitBreakerConfig configWithSlowCallThreshold = CircuitBreakerConfig.custom()
        .slowCallDurationThreshold(Duration.ofSeconds(1)).build();
    circuitBreaker = circuitBreakerRegistry
        .circuitBreaker("backendA", configWithSlowCallThreshold);

    // record some basic stats
    // SLOW_SUCCESS
    circuitBreaker.onSuccess(2000, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(100, TimeUnit.NANOSECONDS, new RuntimeException("oops"));
    circuitBreaker.transitionToOpenState();
}
 
@Before
public void setup() {
    registry = new CollectorRegistry();
    circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();

    CircuitBreakerConfig configWithSlowCallThreshold = CircuitBreakerConfig.custom()
        .slowCallDurationThreshold(Duration.ofSeconds(1)).build();
    circuitBreaker = circuitBreakerRegistry
        .circuitBreaker("backendA", configWithSlowCallThreshold);

    CircuitBreakerMetricsCollector.ofCircuitBreakerRegistry(circuitBreakerRegistry)
        .register(registry);

    // record some basic stats
    // SLOW_SUCCESS
    circuitBreaker.onSuccess(2000, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(100, TimeUnit.NANOSECONDS, new RuntimeException("oops"));
    circuitBreaker.transitionToOpenState();
}
 
源代码13 项目: java-grpc-prometheus   文件: RegistryHelper.java
public static int countSamples(
    String metricName, String sampleName, CollectorRegistry collectorRegistry) {
  Enumeration<Collector.MetricFamilySamples> samples = collectorRegistry.metricFamilySamples();
  while (samples.hasMoreElements()) {
    Collector.MetricFamilySamples sample = samples.nextElement();
    if (sample.name.equals(metricName)) {
      int result = 0;
      for (Collector.MetricFamilySamples.Sample s : sample.samples) {
        if (s.name.equals(sampleName)) {
          ++result;
        }
      }
      return result;
    }
  }
  throw new IllegalArgumentException("Could not find sample family with name: " + metricName);
}
 
源代码14 项目: flink   文件: PrometheusReporterTaskScopeTest.java
@Test
public void removingSingleInstanceOfMetricDoesNotBreakOtherInstances() throws UnirestException {
	Counter counter1 = new SimpleCounter();
	counter1.inc(1);
	Counter counter2 = new SimpleCounter();
	counter2.inc(2);

	taskMetricGroup1.counter("my_counter", counter1);
	taskMetricGroup2.counter("my_counter", counter2);

	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_counter", LABEL_NAMES, labelValues1),
		equalTo(1.));
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_counter", LABEL_NAMES, labelValues2),
		equalTo(2.));

	taskMetricGroup2.close();
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_counter", LABEL_NAMES, labelValues1),
		equalTo(1.));

	taskMetricGroup1.close();
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_counter", LABEL_NAMES, labelValues1),
		nullValue());
}
 
源代码15 项目: nifi   文件: PrometheusServer.java
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("PrometheusServer Do get called");
    }

    ServletOutputStream response = resp.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(response);

    for(Function<ReportingContext, CollectorRegistry> mc : metricsCollectors) {
        CollectorRegistry collectorRegistry = mc.apply(getReportingContext());
        TextFormat.write004(osw, collectorRegistry.metricFamilySamples());
    }

    osw.flush();
    osw.close();
    response.flush();
    response.close();
    resp.setHeader("Content-Type", TextFormat.CONTENT_TYPE_004);
    resp.setStatus(HttpURLConnection.HTTP_OK);
    resp.flushBuffer();
}
 
源代码16 项目: hadoop-ozone   文件: RatisDropwizardExports.java
private static void deregisterDropwizard(RatisMetricRegistry registry,
    Map<String, RatisDropwizardExports> ratisMetricsMap) {
  String name = registry.getMetricRegistryInfo().getName();
  Collector c = ratisMetricsMap.remove(name);
  if (c != null) {
    CollectorRegistry.defaultRegistry.unregister(c);
  }
}
 
源代码17 项目: flink   文件: PrometheusReporterTaskScopeTest.java
@Test
public void metersCanBeAddedSeveralTimesIfTheyDifferInLabels() throws UnirestException {
	Meter meter = new TestMeter();

	taskMetricGroup1.meter("my_meter", meter);
	taskMetricGroup2.meter("my_meter", meter);

	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_meter", LABEL_NAMES, labelValues1),
		equalTo(5.));
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_meter", LABEL_NAMES, labelValues2),
		equalTo(5.));
}
 
@Test
public void testServletRequestMetrics() throws Exception {
    // servlet response times
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("servlet_request_seconds_bucket", new String[]{"context", "method", "le"}, new String[]{CONTEXT_PATH, "GET", "0.01"}), is(notNullValue()));
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("servlet_request_seconds_bucket", new String[]{"context", "method", "le"}, new String[]{CONTEXT_PATH, "GET", "+Inf"}), is(greaterThan(0.0)));
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("servlet_request_seconds_count", new String[]{"context", "method"}, new String[]{CONTEXT_PATH, "GET"}), is(greaterThan(0.0)));

    // concurrent invocation count
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("servlet_request_concurrent_total", new String[]{"context"}, new String[]{CONTEXT_PATH}), is(notNullValue()));
}
 
源代码19 项目: java-grpc-prometheus   文件: ServerMetrics.java
Factory(Configuration configuration) {
  CollectorRegistry registry = configuration.getCollectorRegistry();
  this.serverStarted = serverStartedBuilder.register(registry);
  this.serverHandled = serverHandledBuilder.register(registry);
  this.serverStreamMessagesReceived = serverStreamMessagesReceivedBuilder.register(registry);
  this.serverStreamMessagesSent = serverStreamMessagesSentBuilder.register(registry);

  if (configuration.isIncludeLatencyHistograms()) {
    this.serverHandledLatencySeconds = Optional.of(serverHandledLatencySecondsBuilder
        .buckets(configuration.getLatencyBuckets())
        .register(registry));
  } else {
    this.serverHandledLatencySeconds = Optional.empty();
  }
}
 
源代码20 项目: apicurio-studio   文件: PrometheusApiMetrics.java
/**
 * @see io.apicurio.hub.api.metrics.IApiMetrics#getCurrentMetricsInfo()
 */
@Override
public String getCurrentMetricsInfo() throws IOException {
    StringWriter writer = new StringWriter();
    TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());

    String content = writer.getBuffer().toString();
    return content;
}
 
源代码21 项目: pulsar   文件: FunctionsMetricsResource.java
@Path("metrics")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getMetrics() throws IOException {

    WorkerService workerService = get();
    ByteBuf buf = ByteBufAllocator.DEFAULT.heapBuffer();
    // if request, also attach the prometheus metrics
    if (workerService.getWorkerConfig().isIncludeStandardPrometheusMetrics()) {
        Writer writer = new BufWriter(buf);
        TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
    }

    try {
        SimpleTextOutputStream stream = new SimpleTextOutputStream(buf);
        FunctionsStatsGenerator.generate(workerService,"default", stream);
        byte[] payload = buf.array();
        int arrayOffset = buf.arrayOffset();
        int readableBytes = buf.readableBytes();
        StreamingOutput streamOut = out -> {
            out.write(payload, arrayOffset, readableBytes);
            out.flush();
        };
        return Response
            .ok(streamOut)
            .type(MediaType.TEXT_PLAIN_TYPE)
            .build();
    } finally {
        buf.release();
    }
}
 
源代码22 项目: nifi   文件: PrometheusMetricsUtil.java
public static CollectorRegistry createConnectionStatusAnalyticsMetrics(ConnectionAnalyticsMetricsRegistry connectionAnalyticsMetricsRegistry, StatusAnalytics statusAnalytics,
                                                                       String instId, String connComponentType, String connName,
                                                                       String connId, String pgId, String srcId, String srcName, String destId, String destName) {
    if(statusAnalytics != null) {
        final String instanceId = StringUtils.isEmpty(instId) ? DEFAULT_LABEL_STRING : instId;
        final String connComponentId = StringUtils.isEmpty(connId) ? DEFAULT_LABEL_STRING : connId;
        final String connComponentName = StringUtils.isEmpty(connName) ? DEFAULT_LABEL_STRING : connName;
        final String sourceId = StringUtils.isEmpty(srcId) ? DEFAULT_LABEL_STRING : srcId;
        final String sourceName = StringUtils.isEmpty(srcName) ? DEFAULT_LABEL_STRING : srcName;
        final String destinationId = StringUtils.isEmpty(destId) ? DEFAULT_LABEL_STRING : destId;
        final String destinationName = StringUtils.isEmpty(destName) ? DEFAULT_LABEL_STRING : destName;
        final String parentId = StringUtils.isEmpty(pgId) ? DEFAULT_LABEL_STRING : pgId;


        Map<String, Long> predictions = statusAnalytics.getPredictions();
        connectionAnalyticsMetricsRegistry.setDataPoint(predictions.get("timeToBytesBackpressureMillis"),
                "TIME_TO_BYTES_BACKPRESSURE_PREDICTION",
                instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName);
        connectionAnalyticsMetricsRegistry.setDataPoint(predictions.get("timeToCountBackpressureMillis"),
                "TIME_TO_COUNT_BACKPRESSURE_PREDICTION",
                instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName);
        connectionAnalyticsMetricsRegistry.setDataPoint(predictions.get("nextIntervalBytes"),
                "BYTES_AT_NEXT_INTERVAL_PREDICTION",
                instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName);
        connectionAnalyticsMetricsRegistry.setDataPoint(predictions.get("nextIntervalCount"),
                "COUNT_AT_NEXT_INTERVAL_PREDICTION",
                instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName);
    }

    return connectionAnalyticsMetricsRegistry.getRegistry();
}
 
源代码23 项目: java-metrics   文件: PrometheusMetricsReporter.java
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);
}
 
@Before
public void setup() {
    registry = new CollectorRegistry();
    timeLimiterMetricsPublisher = new TimeLimiterMetricsPublisher();
    timeLimiterMetricsPublisher.register(registry);
    timeLimiterRegistry = TimeLimiterRegistry
        .of(TimeLimiterConfig.ofDefaults(), timeLimiterMetricsPublisher);
    timeLimiter = timeLimiterRegistry.timeLimiter("backendA");
}
 
/**
 * Register an instance of this publisher, for the given namespace, with the
 * {@link com.netflix.hystrix.strategy.HystrixPlugins} singleton. The publisher
 * registered by this method will NOT attempt to export properties.
 */
public static void register(String namespace, CollectorRegistry registry) {
    HystrixPrometheusMetricsPublisher.builder()
            .withNamespace(namespace)
            .withRegistry(registry)
            .buildAndRegister();
}
 
源代码26 项目: client_java   文件: MethodTimerTest.java
@Test
public void timeMethodInSubClassModel() throws Exception {
    Timeable cprime = new MockCglibProxyTestClass();
    AspectJProxyFactory factory = new AspectJProxyFactory(cprime);
    factory.addAspect(MethodTimer.class);
    Timeable proxy = factory.getProxy();

    proxy.timeMe();

    final Double tot = CollectorRegistry.defaultRegistry.getSampleValue("test_sub_class_sum");
    Assert.assertNotNull(tot);
    assertEquals(0.02, tot, 0.01);
}
 
public StreamingOutput metrics() {

        return output -> {
            try (final Writer writer = new OutputStreamWriter(output)) {
                TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
            }
        };
    }
 
源代码28 项目: pulsar   文件: ThreadRuntimeFactory.java
@VisibleForTesting
public ThreadRuntimeFactory(String threadGroupName, PulsarClient pulsarClient, String storageServiceUrl,
                            SecretsProvider secretsProvider, CollectorRegistry collectorRegistry,
                            String narExtractionDirectory, ClassLoader rootClassLoader) {

    initialize(threadGroupName, pulsarClient, storageServiceUrl,
            null, secretsProvider, collectorRegistry, narExtractionDirectory, rootClassLoader);
}
 
源代码29 项目: nifi   文件: PrometheusRecordSink.java
@OnEnabled
public void onScheduled(final ConfigurationContext context) {
    RECORD_REGISTRY.clear();
    SSLContextService sslContextService = context.getProperty(SSL_CONTEXT).asControllerService(SSLContextService.class);
    final String metricsEndpointPort = context.getProperty(PrometheusMetricsUtil.METRICS_ENDPOINT_PORT).getValue();

    try {
        List<Function<ReportingContext, CollectorRegistry>> metricsCollectors = new ArrayList<>();
        if (sslContextService == null) {
            prometheusServer = new PrometheusServer(new InetSocketAddress(Integer.parseInt(metricsEndpointPort)), getLogger());
        } else {
            final String clientAuthValue = context.getProperty(PrometheusMetricsUtil.CLIENT_AUTH).getValue();
            final boolean need;
            final boolean want;
            if (PrometheusMetricsUtil.CLIENT_NEED.getValue().equals(clientAuthValue)) {
                need = true;
                want = false;
            } else if (PrometheusMetricsUtil.CLIENT_WANT.getValue().equals(clientAuthValue)) {
                need = false;
                want = true;
            } else {
                need = false;
                want = false;
            }
            prometheusServer = new PrometheusServer(Integer.parseInt(metricsEndpointPort), sslContextService, getLogger(), need, want);
        }
        Function<ReportingContext, CollectorRegistry> nifiMetrics = (reportingContext) -> RECORD_REGISTRY;
        metricsCollectors.add(nifiMetrics);

        prometheusServer.setMetricsCollectors(metricsCollectors);
        getLogger().info("Started JETTY server");
    } catch (Exception e) {
        getLogger().error("Failed to start Jetty server", e);
    }
}
 
源代码30 项目: kardio   文件: PrometheusMetricService.java
/**
 * Constructs the Push Metric and push it to Prometheus end point.
 * 
 * @param req
 * @param httpStatusCode
 */
public void pushMetric(HttpServletRequest req) {
    if (prometheusPushEnabled == null || !prometheusPushEnabled.equalsIgnoreCase("true")) {
        return;
    }

    String requestStatus = (String) req.getAttribute(Constants.PROMETHEUS_REQ_STATUS);
    String endPointName = (String) req.getAttribute(Constants.PROMETHEUS_APP_ENDPOINT_NAME);
    Date reqStartTime = (Date) req.getAttribute(Constants.PROMETHEUS_REQ_TIMER);
    CollectorRegistry registry = createRegistry();

    setDurationTimerWithStatus(registry, reqStartTime, requestStatus);
    pushMetricToPrometheus(registry, endPointName);
}