Prometheus實踐 - 集成exporter/項目埋點

       目前prometheus採集數據通常有兩種方式,一種是採用第三方已經開發完成的各種集成exporter,去獲取相關的指標(Metric)數據;一種是採用項目埋點的方式去自定義指標,而後經過prometheus去採集。大體狀況以下:node

  • 第三方exporter

                好比用node_exporter監控採集服務器CPU、內存、磁盤、I/O等信息,做爲機器數據的通用採集,用mysqld_exporter監控數據庫訪問量、壓力性能等指標,用memcached_exporter監控收集數據緩存系統的數據指標,用JMX_exporter採集Java虛擬機的數據信息等。mysql

  • 自定義Metric指標

                 在PHP項目/Java項目/Ngnix項目等中加入prometheus的自定義Metric指標的註冊,採集等埋點工做,而後經過prometheus指定對應的拉取規則去採集。通常的對於Java程序中經常使用到的埋點方法有兩種,一爲結合切面(Aspect)/攔截器(Interceptor)技術實現對通用接口的數據採集,一爲在特定業務接口中寫入自定義Metric的註冊-採集代碼,單獨爲該業務統計採集指標數據。linux

       下面就以linux系統環境(CentOS)中,node_exporter和Spring-boot埋點爲例,大體介紹下這兩種數據採集的使用方法,以及一些注意點:git

  1. node_exporter監控linux系統
  • 命令行安裝node_exporter
//從github獲取安裝包
$ wget https://github.com/prometheus/node_exporter/releases/download/v0.14.0/node_exporter-0.14.0.linux-amd64.tar.gz
//解壓
$ tar -zxvf node_exporter-0.14.0.linux-amd64.tar.gz
//移動到指定目錄
$ mv node_exporter-0.14.0.linux-amd64 /usr/local/prometheus/node_exporter
  • 建立Systemd服務
$ vim /etc/systemd/system/node_exporter.service

[Unit]
Description=node_exporter
After=network.target
[Service]
Type=simple
User=root
ExecStart=/usr/local/prometheus/node_exporter/node_exporter
Restart=on-failure
[Install]
WantedBy=multi-user.target
  • 啓動/驗證 node_exporter
//啓動命令:
$ systemctl start node_exporter
//查詢服務狀態命令:
$ systemctl status node_exporter
● node_exporter.service - node_exporter
   Loaded: loaded (/etc/systemd/system/node_exporter.service; disabled; vendor preset: enabled)
   Active: active (running) since Mon 2017-05-22 12:13:43 CST; 6s ago
 Main PID: 11776 (node_exporter)
    Tasks: 4
   Memory: 1.5M
      CPU: 24ms
   CGroup: /system.slice/node_exporter.service
           └─11776 /usr/local/prometheus/node_exporter/node_exporter

        若狀態Active爲active(running)則證實啓動正常,若狀態爲inactive (dead)則說明服務未正常啓動。github

  • 修改prometheus主程序配置文件,默認配置文件爲prometheus.yml,需在scrape_configs中新增抓取對象‘linux’及對應的ip地址端口。
    scrape_configs:
    
      - job_name: 'prometheus'
        static_configs:
          - targets: ['localhost:9090']
    
      - job_name: 'linux'
        static_configs:
          - targets: ['localhost:9100']

    在完成上述操做後,重啓prometheus服務,能夠看到一些採集到的數據曲線,以下:spring

          當前主機CPU負載狀況曲線:sql

            

        注意點:node_exporter做爲由第三方開發完成的exporter,在採集linux系統數據方面使用起來比較便利,但也存在代碼開發不完善,與業務不匹配,指標採集數據冗餘的缺點,這個能夠經過對開源的exporter進行二次開發,對應的exporter配置修改相關配置,或者利用PromQL語句去剔除無用數據等方法去完善。數據庫

     2. Spring-boot埋點 - 自定義數據指標Metricvim

        prometheus提供的官方或第三方exporters,能夠知足大部分prometheus用戶對於基礎業務的監控需求,其它狀況下,咱們還須要在應用中擴展Prometheus支持。即須要在監控對象程序中埋點抓取對應的監控指標數據,而目前常見的攔截器埋點方法以下所示:緩存

  • 增長配置項:

       (1)在pom.xml中加入依賴配置

<!-- Exposition spring_boot -->
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_spring_boot</artifactId>
    <version>0.1.0</version>
</dependency>
<!-- Hotspot JVM metrics -->
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_hotspot</artifactId>
    <version>0.1.0</version>
</dependency>
<!-- Exposition servlet -->
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_servlet</artifactId>
    <version>0.1.0</version>
</dependency>

        (2)在boot啓動主程序類加註解配置:

            

        (3)新增MonitoringConfig類用於prometheus服務接口的註冊:

@Configuration
class MonitoringConfig {
    @Bean
    SpringBootMetricsCollector springBootMetricsCollector(Collection<PublicMetrics> publicMetrics) {

        SpringBootMetricsCollector springBootMetricsCollector = new 
             SpringBootMetricsCollector(publicMetrics);
        springBootMetricsCollector.register();
        return springBootMetricsCollector;
    }

    @Bean
    ServletRegistrationBean servletRegistrationBean() {
        DefaultExports.initialize();
        return new ServletRegistrationBean(new MetricsServlet(), "/prometheus");
    }
}
  •  增長攔截器,定義註冊Metric,採集數據

    新增RequestCounterInterceptor類用於計數:

public class RequestCounterInterceptor extends HandlerInterceptorAdapter {

    // @formatter:off
    // Note (1)
    private static final Counter requestTotal = Counter.build()
         .name("cgt_requests_total")
         .labelNames("method", "handler", "status")
         .help("Http Request Total").register();
    // @formatter:on

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)
                                                                                                    
    throws Exception {
         // Update counters
         String handlerLabel = handler.toString();
         // get short form of handler method name
         if (handler instanceof HandlerMethod) {
              Method method = ((HandlerMethod) handler).getMethod();
              handlerLabel = method.getDeclaringClass().getSimpleName() + "." + method.getName();
         }
         // Note (2)
         requestTotal.labels(request.getMethod(), handlerLabel, 
               Integer.toString(response.getStatus())).inc();
    }
}
  • 攔截器註冊
@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter {
    /**
     * 註冊 攔截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestCounterInterceptor());
    }
}
  • 修改prometheus主程序配置文件prometheus.yml,增長新的抓取目標,好比:

                                

        在完成上述修改後,啓動boot程序和prometheus程序,能夠看到在訪問boot程序接口時,統計到的訪問接口請求數目的變化:

            

        注意點:利用攔截器自定義Metric採集數據,通常是應用級別的監控採用的方法,同時能夠在程序內增長方法級別的Metric定義埋點,去採集特定指標的指標數據。

        另,對於boot程序,想要prometheus正常監控,須要再配置文件中加入必定配置容許程序暴露數據指標Metric和去除重複的Metric,以下:

//容許暴露metric給prometheus
management:
  security:
    enabled: false

//去掉spring自帶的重複metric
spring:
    metrics:
     servo:
       enabled: false

        以上即爲prometheus獲取監控數據經常使用方法,後續若遇到新的知識點,也將持續更新。感謝閱讀。

相關文章
相關標籤/搜索