當前位置: 首頁>>代碼示例>>Java>>正文


Java CollectorRegistry類代碼示例

本文整理匯總了Java中io.prometheus.client.CollectorRegistry的典型用法代碼示例。如果您正苦於以下問題:Java CollectorRegistry類的具體用法?Java CollectorRegistry怎麽用?Java CollectorRegistry使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


CollectorRegistry類屬於io.prometheus.client包,在下文中一共展示了CollectorRegistry類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: run

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
public void run(Configuration configuration, Environment environment) throws Exception {
  final CollectorRegistry collectorRegistry = new CollectorRegistry();
  collectorRegistry.register(new DropwizardExports(environment.metrics()));
  environment.admin()
      .addServlet("metrics", new MetricsServlet(collectorRegistry))
      .addMapping("/metrics");

  final PrometheusMetricsReporter reporter = PrometheusMetricsReporter.newMetricsReporter()
      .withCollectorRegistry(collectorRegistry)
      .withConstLabel("service", getName())
      .build();

  final Tracer tracer = getTracer();
  final Tracer metricsTracer = io.opentracing.contrib.metrics.Metrics.decorate(tracer, reporter);
  GlobalTracer.register(metricsTracer);

  final DynamicFeature tracing = new ServerTracingDynamicFeature.Builder(metricsTracer).build();
  environment.jersey().register(tracing);

  final Properties producerConfigs = new Properties();
  producerConfigs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "tweets-kafka:9092");
  producerConfigs.put(ProducerConfig.ACKS_CONFIG, "all");
  producerConfigs.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
  final KafkaProducer<Long, String> kafkaProducer =
      new KafkaProducer<>(producerConfigs, new LongSerializer(), new StringSerializer());
  final Producer<Long, String> tracingKafkaProducer =
      new TracingKafkaProducer<>(kafkaProducer, metricsTracer);
  final ObjectMapper objectMapper = environment.getObjectMapper();
  final TweetEventRepository tweetRepository = new KafkaTweetEventRepository(tracingKafkaProducer, objectMapper);
  final TweetsService tweetsService = new TweetsService(tweetRepository);
  final TweetsResource tweetsResource = new TweetsResource(tweetsService);
  environment.jersey().register(tweetsResource);
}
 
開發者ID:jeqo,項目名稱:talk-observing-distributed-systems,代碼行數:34,代碼來源:WorkerServiceApplication.java

示例2: run

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
static void run(String host, String portString, CollectorRegistry registry) throws Exception {
    try {
        int port = Integer.parseInt(portString);
        InetSocketAddress address = host == null ? new InetSocketAddress(port) : new InetSocketAddress(host, port);
        HttpServer httpServer = HttpServer.create(address, 10);
        httpServer.createContext("/", httpExchange -> {
            if ("/metrics".equals(httpExchange.getRequestURI().getPath())) {
                respondMetrics(registry, httpExchange);
            } else {
                respondRedirect(httpExchange);
            }
        });
        httpServer.start();
    } catch (NumberFormatException e) {
        throw new RuntimeException("Failed to parse command line arguments: '" + portString + "' is not a valid port number.");
    }
}
 
開發者ID:fstab,項目名稱:promagent,代碼行數:18,代碼來源:BuiltInServer.java

示例3: getInstanceInfo

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getInstanceInfo() throws IOException,
        WebApplicationException,
		StreamsTrackerException{
	
	// At this time, if the auto-refresh is turned off, the call to getInstance() will cause the refresh() to occur.
    StreamsInstanceTracker jobTracker = StreamsInstanceTracker
            .getInstance();   
    
    LOGGER.debug("/prometheus endpoint handler: metricsAvailable={}, instanceAvailable={}",jobTracker.metricsAvailable(),jobTracker.getInstanceInfo().isInstanceAvailable());
    
    // Create streams_exporter_metrics_available and streams_exporter_instance_available
    
	StringWriter writer = new StringWriter();
	
	io.prometheus.client.exporter.common.TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());

    return Response.status(200).entity(writer.toString())
            .build();
}
 
開發者ID:IBMStreams,項目名稱:streamsx.jmxclients,代碼行數:22,代碼來源:PrometheusResource.java

示例4: prometheus

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
@Bean
PrometheusMeterRegistry prometheus(Clock clock) {
    PrometheusMeterRegistry r = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT, new CollectorRegistry(), clock);
    r.config().meterFilter(new MeterFilter() {
        @Override
        public MeterFilterReply accept(Meter.Id id) {
            for (Tag tag : id.getTags()) {
                if (tag.getKey().equals("uri") && (tag.getValue().contains("histogram") || tag.getValue().contains("percentiles"))) {
                    return MeterFilterReply.ACCEPT;
                }
            }
            return MeterFilterReply.DENY;
        }
    });
    return r;
}
 
開發者ID:micrometer-metrics,項目名稱:micrometer,代碼行數:17,代碼來源:MetricsFilterTest.java

示例5: PrometheusExporter

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
public PrometheusExporter(int port, String path) {
    
    QueuedThreadPool threadPool = new QueuedThreadPool(25);
    server = new Server(threadPool);

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    server.addConnector(connector);

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);

    CollectorRegistry collectorRegistry = new CollectorRegistry();
    
    collectorRegistry.register(new PrometheusExports(CassandraMetricsRegistry.Metrics));

    MetricsServlet metricsServlet = new MetricsServlet(collectorRegistry);

    context.addServlet(new ServletHolder(metricsServlet), "/" + path);
    try {
        server.start();
    } catch (Exception e) {
        System.err.println("cannot start metrics http server " + e.getMessage());
    }
}
 
開發者ID:nabto,項目名稱:cassandra-prometheus,代碼行數:27,代碼來源:PrometheusExporter.java

示例6: createAssertionCollector

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
protected void createAssertionCollector(){
	if (!collectAssertions){
		return;
	}
	
	String[] labelNames = new String[]{};
	
	if (SampleEvent.getVarCount() > 0) {
		labelNames = this.combineAssertionLabelsWithSampleVars();
	}else {
		labelNames = this.assertionConfig.getLabels();
	}
	
	if(this.getSaveConfig().getAssertionClass().equals(Summary.class))
		this.assertionsCollector = Summary.build().name("jmeter_assertions_total").help("Counter for assertions")
			.labelNames(labelNames).quantile(0.5, 0.1).quantile(0.99, 0.1)
			.create().register(CollectorRegistry.defaultRegistry);
	
	else if(this.getSaveConfig().getAssertionClass().equals(Counter.class))
		this.assertionsCollector = Counter.build().name("jmeter_assertions_total").help("Counter for assertions")
		.labelNames(labelNames).create().register(CollectorRegistry.defaultRegistry);
		
}
 
開發者ID:johrstrom,項目名稱:jmeter-prometheus-plugin,代碼行數:24,代碼來源:PrometheusListener.java

示例7: createSamplerCollector

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
protected void createSamplerCollector(){
	if (collectSamples) {
		String[] labelNames = new String[]{};
		
		if (SampleEvent.getVarCount() > 0) {
			labelNames = this.combineConfigLabelsWithSampleVars();
		}else {
			labelNames = this.samplerConfig.getLabels();
		}
		
		this.samplerCollector = Summary.build()
				.name("jmeter_samples_latency")
				.help("Summary for Sample Latency")
				.labelNames(labelNames)
				.quantile(0.5, 0.1)
				.quantile(0.99, 0.1)
				.create()
				.register(CollectorRegistry.defaultRegistry);
	}
}
 
開發者ID:johrstrom,項目名稱:jmeter-prometheus-plugin,代碼行數:21,代碼來源:PrometheusListener.java

示例8: run

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
  // Preparing Translation Service
  final TranslationService translationService = new TranslationService();
  // Preparing Greeting Service and inject Translation
  final GreetingResource greetingService = new GreetingResource(translationService);

  // Register Greeting Service
  environment.jersey().register(greetingService);

  // Add Metrics Instrumentation to count requests
  final CollectorRegistry collectorRegistry = new CollectorRegistry();
  collectorRegistry.register(new DropwizardExports(environment.metrics()));

  // Register Metrics Servlet
  environment.admin()
      .addServlet("metrics", new MetricsServlet(collectorRegistry))
      .addMapping("/metrics");
}
 
開發者ID:jeqo,項目名稱:talk-observing-distributed-systems,代碼行數:20,代碼來源:HelloWorldMonolithApp.java

示例9: run

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
public void run(Configuration configuration, Environment environment) {
  final CollectorRegistry collectorRegistry = new CollectorRegistry();
  collectorRegistry.register(new DropwizardExports(environment.metrics()));

  final PrometheusMetricsReporter reporter =
      PrometheusMetricsReporter.newMetricsReporter()
          .withCollectorRegistry(collectorRegistry)
          .withConstLabel("service", getName())
          .build();

  final Tracer tracer = getTracer();
  final Tracer metricsTracer = io.opentracing.contrib.metrics.Metrics.decorate(tracer, reporter);
  GlobalTracer.register(metricsTracer);

  final String jdbcUrl = "jdbc:tracing:postgresql://tweets-db/postgres";
  final String jdbcUsername = "postgres";
  final String jdbcPassword = "example";
  final TweetsRepository tweetsRepository = new JooqPostgresTweetsRepository(jdbcUrl, jdbcUsername, jdbcPassword);
  final TweetsService tweetsService = new TweetsService(tweetsRepository);
  final TweetsResource tweetsResource = new TweetsResource(tweetsService);

  environment.jersey().register(tweetsResource);

  final DynamicFeature tracing = new ServerTracingDynamicFeature.Builder(metricsTracer).build();
  environment.jersey().register(tracing);

  environment.admin()
      .addServlet("metrics", new MetricsServlet(collectorRegistry))
      .addMapping("/metrics");
}
 
開發者ID:jeqo,項目名稱:talk-observing-distributed-systems,代碼行數:31,代碼來源:TweetsServiceApplication.java

示例10: serverWithStatisticsCollection

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
/**
 * @param registry Prometheus CollectorRegistry to register the default exporters.
 * @param httpPort The port the Server runs on.
 * @return a Jetty Server with Prometheus' default exporters registered.
 */
public static Server serverWithStatisticsCollection(CollectorRegistry registry, int httpPort) {
    Server server = new Server(httpPort);

    new StandardExports().register(registry);
    new MemoryPoolsExports().register(registry);
    new GarbageCollectorExports().register(registry);
    new ThreadExports().register(registry);
    new ClassLoadingExports().register(registry);
    new VersionInfoExports().register(registry);

    HandlerCollection handlers = new HandlerCollection();
    StatisticsHandler statisticsHandler = new StatisticsHandler();
    statisticsHandler.setServer(server);
    handlers.addHandler(statisticsHandler);

    new JettyStatisticsCollector(statisticsHandler).register();
    server.setHandler(handlers);

    return server;
}
 
開發者ID:tjheslin1,項目名稱:Patterdale,代碼行數:26,代碼來源:RegisterExporters.java

示例11: createNifiMetrics

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
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_REGISTRY;
}
 
開發者ID:mkjoerg,項目名稱:nifi-prometheus-reporter,代碼行數:25,代碼來源:PrometheusMetricsFactory.java

示例12: testServletRequestMetrics

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
@Test
public void testServletRequestMetrics() throws Exception {

     // global query stats
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_query_seconds_bucket", new String[]{"status", "le"}, new String[]{TomcatJdbcInterceptor.SUCCESS_QUERY_STATUS, "0.01"}), is(notNullValue()));
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_query_seconds_bucket", new String[]{"status", "le"}, new String[]{TomcatJdbcInterceptor.SUCCESS_QUERY_STATUS, "+Inf"}), is(greaterThan(0.0)));
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_query_seconds_count", new String[]{"status"}, new String[]{TomcatJdbcInterceptor.SUCCESS_QUERY_STATUS}), is(greaterThan(0.0)));
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_query_seconds_bucket", new String[]{"status", "le"}, new String[]{TomcatJdbcInterceptor.FAILED_QUERY_STATUS, "0.01"}), is(notNullValue()));
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_query_seconds_bucket", new String[]{"status", "le"}, new String[]{TomcatJdbcInterceptor.FAILED_QUERY_STATUS, "+Inf"}), is(greaterThan(0.0)));
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_query_seconds_count", new String[]{"status"}, new String[]{TomcatJdbcInterceptor.FAILED_QUERY_STATUS}), is(greaterThan(0.0)));

    // slow query stats
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_slowquery_seconds_bucket", new String[]{"query", "le"}, new String[]{"select 1", "1.0"}), is(notNullValue()));
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_slowquery_seconds_bucket", new String[]{"query", "le"}, new String[]{"select 1", "+Inf"}), is(greaterThan(0.0)));
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_slowquery_seconds_count", new String[]{"query"}, new String[]{"select 1"}), is(greaterThan(0.0)));

    // failed query stats
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue("tomcat_jdbc_failedquery_total", new String[]{"query"}, new String[]{"select * from NON_EXISTING_TABLE"}), is(greaterThan(0.0)));

}
 
開發者ID:nlighten,項目名稱:tomcat_exporter,代碼行數:21,代碼來源:TomcatJdbcInterceptorTest.java

示例13: init

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
public static CollectorRegistry init(CollectorRegistry registry, Collection<HttpMetricsCollector> httpCollectors) {

        httpCollectors.forEach(it -> it.register(registry));

        //do not register the default metrics since we want full control here.
        new StandardExports().register(registry);
        new MemoryPoolsExports().register(registry);
        new ThreadExports().register(registry);

        new JvmGcMetrics().register(registry);
        Operation.getInstance().register(registry);
        Size.getInstance().register(registry);
        Status.getInstance().register(registry);

        // logback metrics
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        //cannot use instrumented appender here since it is not possible to send in the registry
        LogbackMetricsAppender appender = new LogbackMetricsAppender(registry);
        appender.setContext(lc);
        appender.start();
        Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        root.addAppender(appender);

        logger.debug("Registered standard, memory, thread, gc, httpcollectors and logback metrics");
        return registry;
    }
 
開發者ID:Skatteetaten,項目名稱:aurora-prometheus,代碼行數:27,代碼來源:MetricsConfig.java

示例14: MetricsPublisher

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
@Autowired
public MetricsPublisher(MetricsCollector metricsCollector) {
  //prometheus default port allocation is here : https://github.com/prometheus/prometheus/wiki/Default-port-allocations
  int publishPort = DynamicPropertyFactory.getInstance().getIntProperty(METRICS_PROMETHEUS_PORT, 9696).get();
  this.metricsCollector = metricsCollector;
  this.metricsCollector.register();
  try {
    this.httpServer = new HTTPServer(new InetSocketAddress(publishPort), CollectorRegistry.defaultRegistry, true);
    LOGGER.info("Prometheus httpServer listened {}.", publishPort);
  } catch (IOException e) {
    throw new ServiceCombException("create http publish server failed", e);
  }
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:14,代碼來源:MetricsPublisher.java

示例15: collectorRegistry

import io.prometheus.client.CollectorRegistry; //導入依賴的package包/類
@Bean
@ConditionalOnMissingBean
public CollectorRegistry collectorRegistry() {
    CollectorRegistry defaultRegistry = CollectorRegistry.defaultRegistry;
    defaultRegistry.clear();
    return defaultRegistry;
}
 
開發者ID:amvnetworks,項目名稱:amv-access-api-poc,代碼行數:8,代碼來源:PrometheusConfiguration.java


注:本文中的io.prometheus.client.CollectorRegistry類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。