001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.support.metric.reporter.prometheus;
017
018import com.codahale.metrics.MetricRegistry;
019import io.jboot.Jboot;
020import io.jboot.exception.JbootIllegalConfigException;
021import io.jboot.support.metric.JbootMetricReporter;
022import io.prometheus.client.exporter.HTTPServer;
023
024import java.io.IOException;
025
026/**
027 * @author Michael Yang 杨福海 (fuhai999@gmail.com)
028 * @version V1.0
029 * @url https://github.com/prometheus/client_java
030 */
031public class PrometheusReporter implements JbootMetricReporter {
032
033    private HTTPServer httpServer;
034
035    public PrometheusReporter() {
036        PrometheusReporterConfig config = Jboot.config(PrometheusReporterConfig.class);
037        try {
038            httpServer = new HTTPServer(config.getHost(), config.getPort());
039            String printMsg = "Prometheus Reporter Server started -> http://" + config.getHost() + ":" + config.getPort();
040            System.out.println(printMsg);
041        } catch (IOException e) {
042            throw new JbootIllegalConfigException("Prometheus config is error, please check your jboot.properties. ", e);
043        }
044
045//        if (httpServer != null) {
046//            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
047//                if (httpServer != null) {
048//                    try {
049//                        httpServer.stop();
050//                    } catch (Exception ex) {
051//                    }
052//                }
053//            }, "prometheus-httpserver-hook"));
054//        }
055    }
056
057    @Override
058    public void report(MetricRegistry metricRegistry) {
059//        new DropwizardExports(metricRegistry).register();
060
061        // 使用 PrometheusExports 主要是可以添加 application 和 instance 的参数
062        // 例如 jvm_memory_total_used{application="jboot",instance="192.168.3.24:8818",} 1.521354E8
063        new PrometheusExports(metricRegistry).register();
064    }
065}