io.prometheus.client.hotspot.DefaultExports Java Examples

The following examples show how to use io.prometheus.client.hotspot.DefaultExports. 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: PrometheusService.java    From canal with Apache License 2.0 8 votes vote down vote up
@Override
public void initialize() {
    try {
        logger.info("Start prometheus HTTPServer on port {}.", port);
        //TODO 2.Https?
        server = new HTTPServer(port);
    } catch (IOException e) {
        logger.warn("Unable to start prometheus HTTPServer.", e);
        return;
    }
    try {
        // JVM exports
        DefaultExports.initialize();
        instanceExports.initialize();
        if (!clientProfiler.isStart()) {
            clientProfiler.start();
        }
        profiler().setInstanceProfiler(clientProfiler);
    } catch (Throwable t) {
        logger.warn("Unable to initialize server exports.", t);
    }

    running = true;
}
 
Example #2
Source File: TxleMetrics.java    From txle with Apache License 2.0 6 votes vote down vote up
public TxleMetrics(String promMetricsPort) {
    try {
        DefaultExports.initialize();
        // Default port logic: the default port 8099 has been configured in application.yaml, thus if it's not 8099, then indicate that someone edited it automatically.
        if (promMetricsPort != null && promMetricsPort.length() > 0) {
            int metricsPort = Integer.parseInt(promMetricsPort);
            if (metricsPort > 0) {
                // Initialize Prometheus's Metrics Server.
                // To establish the metrics server immediately without checking the port status.
                new HTTPServer(metricsPort);
                isEnableMonitorServer = true;
            }
        }
        this.register();
    } catch (IOException e) {
        log.error("Initialize txle metrics server exception, please check the port " + promMetricsPort + ". " + e);
    }

}
 
Example #3
Source File: PrometheusService.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize() {
    try {
        logger.info("Start prometheus HTTPServer on port {}.", port);
        //TODO 2.Https?
        server = new HTTPServer(port);
    } catch (IOException e) {
        logger.warn("Unable to start prometheus HTTPServer.", e);
        return;
    }
    try {
        // JVM exports
        DefaultExports.initialize();
        instanceExports.initialize();
        if (!clientProfiler.isStart()) {
            clientProfiler.start();
        }
        profiler().setInstanceProfiler(clientProfiler);
    } catch (Throwable t) {
        logger.warn("Unable to initialize server exports.", t);
    }

    running = true;
}
 
Example #4
Source File: JavaAgent.java    From jmx_exporter with Apache License 2.0 6 votes vote down vote up
public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception {
    // Bind to all interfaces by default (this includes IPv6).
    String host = "0.0.0.0";

    try {
        Config config = parseConfig(agentArgument, host);

        new BuildInfoCollector().register();
        new JmxCollector(new File(config.file)).register();
        DefaultExports.initialize();
        server = new HTTPServer(config.socket, CollectorRegistry.defaultRegistry, true);
    }
    catch (IllegalArgumentException e) {
        System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file> " + e.getMessage());
        System.exit(1);
    }
}
 
Example #5
Source File: OMetricsModule.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
	public void onInitialize(OrienteerWebApplication app, ODatabaseDocument db) {
		super.onInitialize(app, db);
		DefaultExports.initialize();
		OMetricsRequestCycleListener.install(app);
		OMetricSessionListener.install(app);
		new OMetricsOrientDB().register();
//		OPerformanceStatisticManager psm = OMetricsOrientDB.getPerformanceStatisticManager();
		//WorkAround to avoid NPEs in logs
		//TODO: Remove when https://github.com/orientechnologies/orientdb/issues/9169 will be fixed
//		psm.startThreadMonitoring();
//		psm.getSessionPerformanceStatistic().startWALFlushTimer();
//		psm.getSessionPerformanceStatistic().stopWALFlushTimer();
//		psm.stopThreadMonitoring();
		//End of block to delete after issue fixing
		
//		psm.startMonitoring();
		app.mountPackage(OMetricsModule.class.getPackage().getName());
	}
 
Example #6
Source File: PrometheusMetrics.java    From Lavalink with MIT License 6 votes vote down vote up
public PrometheusMetrics() {

        InstrumentedAppender prometheusAppender = new InstrumentedAppender();
        //log metrics
        final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
        final ch.qos.logback.classic.Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);
        prometheusAppender.setContext(root.getLoggerContext());
        prometheusAppender.start();
        root.addAppender(prometheusAppender);

        //jvm (hotspot) metrics
        DefaultExports.initialize();

        //gc pause buckets
        final GcNotificationListener gcNotificationListener = new GcNotificationListener();
        for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
            if (gcBean instanceof NotificationEmitter) {
                ((NotificationEmitter) gcBean).addNotificationListener(gcNotificationListener, null, gcBean);
            }
        }

        log.info("Prometheus metrics set up");
    }
 
Example #7
Source File: PerformanceCounterService.java    From bboxdb with Apache License 2.0 6 votes vote down vote up
@Override
public void init() throws InterruptedException, BBoxDBException {
	final BBoxDBConfiguration bboxDBConfiguration = BBoxDBConfigurationManager.getConfiguration();
	
	final int port = bboxDBConfiguration.getPerformanceCounterPort();
	
	// Service is disabled
	if(port == -1) {
		logger.info("Performance counter service is disabled");
		return;
	}
	
	logger.info("Starting performance counter service on port: {}", port);
	
  		// Expose JVM stats
	DefaultExports.initialize();
	
	try {
		server = new HTTPServer(port);
	} catch (IOException e) {
		logger.error("Got an exception during starting up performance counter HTTP sever", e);
	}
}
 
Example #8
Source File: ZooKeeperStarter.java    From pulsar with Apache License 2.0 6 votes vote down vote up
protected static void start(String[] args, String defaultStatsPort) throws Exception {
    // Register basic JVM metrics
    DefaultExports.initialize();

    // Start Jetty to serve stats
    int port = Integer.parseInt(System.getProperties().getProperty("stats_server_port", defaultStatsPort));

    log.info("Starting ZK stats HTTP server at port {}", port);
    InetSocketAddress httpEndpoint = InetSocketAddress.createUnresolved("0.0.0.0", port);

    Server server = new Server(httpEndpoint);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    try {
        server.start();
    } catch (Exception e) {
        log.error("Failed to start HTTP server at port {}. Use \"-Dstats_server_port=1234\" to change port number",
                port, e);
        throw e;
    }

    // Start the regular ZooKeeper server
    QuorumPeerMain.main(args);
}
 
Example #9
Source File: JavaDropwizard.java    From java_examples with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
    // Increment the counter.
    counter.inc();

    // Hook the Dropwizard registry into the Prometheus registry
    // via the DropwizardExports collector.
    CollectorRegistry.defaultRegistry.register(new DropwizardExports(metrics));


    // Expose Prometheus metrics.
    Server server = new Server(1234);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    // Add metrics about CPU, JVM memory etc.
    DefaultExports.initialize();
    // Start the webserver.
    server.start();
    server.join();
}
 
Example #10
Source File: JavaSimple.java    From java_examples with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
    Server server = new Server(1234);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    // Expose our example servlet.
    context.addServlet(new ServletHolder(new ExampleServlet()), "/");
    // Expose Promtheus metrics.
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    // Add metrics about CPU, JVM memory etc.
    DefaultExports.initialize();


    // Start the webserver.
    server.start();
    server.join();
}
 
Example #11
Source File: TomcatMetricsServlet.java    From tomcat_exporter with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletConfig config) {
    if (!initialized()) {
        DefaultExports.initialize();
        new TomcatGenericExports(false).register();
        if (TomcatJdbcPoolExports.isTomcatJdbcUsed()) {
            new TomcatJdbcPoolExports().register();
        } else {
            new TomcatDbcp2PoolExports().register();
        }
    }
}
 
Example #12
Source File: MonitoringModule.java    From curiostack with MIT License 5 votes vote down vote up
@Provides
@Singleton
static CollectorRegistry collectorRegistry() {
  CollectorRegistry registry = CollectorRegistry.defaultRegistry;
  DefaultExports.initialize();
  configureLogMetrics();
  return registry;
}
 
Example #13
Source File: PrometheusHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    SimpleTimer respTimer = new SimpleTimer();

    exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
        Map<String, Object> auditInfo = exchange1.getAttachment(AttachmentConstants.AUDIT_INFO);
        if(auditInfo != null) {
            Map<String, String> tags = new HashMap<>();
            tags.put("endpoint", (String)auditInfo.get(Constants.ENDPOINT_STRING));
            tags.put("clientId", auditInfo.get(Constants.CLIENT_ID_STRING) != null ? (String)auditInfo.get(Constants.CLIENT_ID_STRING) : "unknown");

            List<String> labels = new ArrayList<>(tags.keySet());
            List<String> labelValues = new ArrayList<>(tags.values());

            summary(RESPONSE_TIME_SECOND, labels).labels(labelValues.stream().toArray(String[]::new)).observe(respTimer.elapsedSeconds());

            incCounterForStatusCode(exchange1.getStatusCode(), labels, labelValues);
            if (config.enableHotspot) {
                logger.info("Prometheus hotspot monitor enabled.");
                DefaultExports.initialize();
            }
        }
        nextListener.proceed();
    });

    Handler.next(exchange, next);
}
 
Example #14
Source File: PrometheusAutoConfiguration.java    From shipping with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "prometheusMetricsServletRegistrationBean")
ServletRegistrationBean prometheusMetricsServletRegistrationBean(@Value("${prometheus.metrics" +
        ".path:/metrics}") String metricsPath) {
    DefaultExports.initialize();
    return new ServletRegistrationBean(new MetricsServlet(), metricsPath);
}
 
Example #15
Source File: PrometheusServer.java    From cineast with MIT License 5 votes vote down vote up
public static synchronized void initialize() {
  if (initalized) {
    LOGGER.info("Prometheus already initalized");
    return;
  }
  if (!Config.sharedConfig().getMonitoring().enablePrometheus) {
    LOGGER.info("Prometheus monitoring not enabled");
    return;
  }
  DefaultExports.initialize();
  Integer port = Config.sharedConfig().getMonitoring().prometheusPort;
  LOGGER.info("Initalizing Prometheus endpoint at port {}", port);
  server = Optional.of(new Server(port));
  ServletContextHandler context = new ServletContextHandler();
  context.setContextPath("/");
  server.get().setHandler(context);
  context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
  PrometheusExtractionTaskMonitor.init();
  ImportTaskMonitor.init();
  DatabaseHealthMonitor.init();
  RetrievalTaskMonitor.init();
  try {
    server.get().start();
  } catch (Exception e) {
    e.printStackTrace();
  }
  initalized = true;
}
 
Example #16
Source File: JavaGraphiteBridge.java    From java_examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Add metrics about CPU, JVM memory etc.
    DefaultExports.initialize();

    Graphite g = new Graphite("localhost", 2003);
    // Send to graphite every 60s.
    Thread thread = g.start(CollectorRegistry.defaultRegistry, 60);
    thread.join();  // Waits forever.
}
 
Example #17
Source File: JavaExample.java    From java_examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  DefaultExports.initialize();
  HTTPServer server = new HTTPServer(8000);
  while (true) {
    myFunction();
    Thread.sleep(1000);
  }
}
 
Example #18
Source File: PrometheusAutoConfiguration.java    From orders with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "prometheusMetricsServletRegistrationBean")
ServletRegistrationBean prometheusMetricsServletRegistrationBean(@Value("${prometheus.metrics" +
        ".path:/metrics}") String metricsPath) {
    DefaultExports.initialize();
    return new ServletRegistrationBean(new MetricsServlet(), metricsPath);
}
 
Example #19
Source File: PrometheusTelemetryProvider.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
    this.registerServiceImplementation(MetricsCreator.class, new PrometheusMetricsCreator());
    this.registerServiceImplementation(MetricsCollector.class, new MetricsCollectorNoop());
    try {
        new HTTPServer(config.getHost(), config.getPort());
    } catch (IOException e) {
        throw new ModuleStartException(e.getMessage(), e);
    }

    DefaultExports.initialize();
}
 
Example #20
Source File: PromMetricsExporter.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
    JsonObject conf = config().getJsonObject("prometheus_exporter", new JsonObject());
    int httpPort = conf.getInteger("port", 9100);
    String path = conf.getString("path", "/metrics");

    DefaultExports.initialize();

    Router router = Router.router(vertx);
    router.route(path).handler(new MetricsHandler());
    vertx.createHttpServer().requestHandler(router::handle).listen(httpPort);
}
 
Example #21
Source File: PromregatorApplication.java    From promregator with Apache License 2.0 5 votes vote down vote up
@Bean
public CollectorRegistry collectorRegistry() {
	CollectorRegistry cr = CollectorRegistry.defaultRegistry;
	
	DefaultExports.initialize();
	
	return cr;
}
 
Example #22
Source File: PrometheusExporter.java    From tunnel with Apache License 2.0 5 votes vote down vote up
@Override
public void startup() {
    PrometheusStatsCollector.createAndRegister();
    DefaultExports.initialize();
    try {
        this.server = new HTTPServer(this.exporterConfig.getExportPort());
    } catch (Exception e) {
        //
    }
}
 
Example #23
Source File: HealthCheckExporter.java    From hellokoding-courses with MIT License 5 votes vote down vote up
public void export() throws Exception {
    CollectorRegistry.defaultRegistry.register(this.healthChecksCollector);

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

    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    DefaultExports.initialize();

    server.start();
    server.join();
}
 
Example #24
Source File: PrometheusMetricsTrackerManager.java    From soul with Apache License 2.0 5 votes vote down vote up
private void register(final String jmxConfig) {
    if (!registered.compareAndSet(false, true)) {
        return;
    }
    new BuildInfoCollector().register();
    try {
        new JmxCollector(jmxConfig).register();
        DefaultExports.initialize();
    } catch (MalformedObjectNameException e) {
        log.error("init jxm collector error", e);
    }
}
 
Example #25
Source File: PrometheusExporter.java    From tunnel with Apache License 2.0 5 votes vote down vote up
@Override
public void startup() {
    PrometheusStatsCollector.createAndRegister();
    DefaultExports.initialize();
    try {
        this.server = new HTTPServer(this.exporterConfig.getExportPort());
    } catch (Exception e) {
        //
    }
}
 
Example #26
Source File: PrometheusUtils.java    From andesite-node with MIT License 5 votes vote down vote up
static void setup() {
    var prometheusAppender = new InstrumentedAppender();
    
    var factory = (LoggerContext) LoggerFactory.getILoggerFactory();
    var root = factory.getLogger(Logger.ROOT_LOGGER_NAME);
    prometheusAppender.setContext(root.getLoggerContext());
    prometheusAppender.start();
    root.addAppender(prometheusAppender);
    
    
    DefaultExports.initialize();
}
 
Example #27
Source File: PrometheusBuilder.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Inject
public PrometheusBuilder(
    ErrorReporter errorReporterRef
)
{
    errorReporter = errorReporterRef;
    DefaultExports.initialize();
}
 
Example #28
Source File: Metrics.java    From FlareBot with MIT License 5 votes vote down vote up
public Metrics() {
    DefaultExports.initialize();

    new BotCollector(new BotMetrics()).register();

    try {
        server = new HTTPServer(9191);
        logger.info("Setup HTTPServer for Metrics");
    } catch (IOException e) {
        throw new IllegalStateException("Failed to set up HTTPServer for Metrics", e);
    }
}
 
Example #29
Source File: PrometheusExporter.java    From prom-bitbucket-exporter with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public PrometheusExporter(
        MetricCollector metricCollector,
        SecureTokenManager secureTokenManager) {
    this.metricCollector = metricCollector;
    this.secureTokenManager = secureTokenManager;
    DefaultExports.initialize();
}
 
Example #30
Source File: MetricsInitializer.java    From docker-javaee with Apache License 2.0 4 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
  DefaultExports.initialize();
}