exporter开发(下篇)


exporter开发(下篇)

准备工作已经在上篇讲过了,这里我们就直接开始撸代码

代码

目录结构:
.
├── collector
│   └── pid.go
└── main.go

main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

import (
"custom_exporters/demo_04/collector"
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)

func main() {
prometheus.MustRegister(collector.NewPidCollector())
http.Handle("/metrics", promhttp.Handler())
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Printf("Error occur when start server %v", err)
}
}

pid.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package collector

import (
"github.com/prometheus/client_golang/prometheus"
"github.com/shirou/gopsutil/host"
"os"
"sync"
)

type PidCollector struct {
pidDesc *prometheus.Desc //当前collector的pid
mutex sync.Mutex
}

func NewPidCollector()PidCollector {
return PidCollector{pidDesc: prometheus.NewDesc(
"cur_collector_pid",
"当前collector的pid",
[]string{"HOST_NAME"},
nil)}

}
// Describe implements the prometheus.Collector interface.
func (p PidCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- p.pidDesc
}

// Collect implements the prometheus.Collector interface.This method may be called concurrently and must therefore be
// implemented in a concurrency safe way
func (p PidCollector) Collect(ch chan<- prometheus.Metric) {
p.mutex.Lock()
defer p.mutex.Unlock()
host,_:= host.Info()
ch <- prometheus.MustNewConstMetric(
p.pidDesc,
prometheus.GaugeValue,
float64(os.Getpid()),
host.Hostname,
)
}

prometheus配置

1
2
3
4
5
6
7
8
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
- job_name: 'pid collector'
static_configs:
- targets:
- localhost:8080

效果

结尾

这只是一个简单的collector实践,如果有多个指标需要采集,我们就可以在 XXXCollector结构体里面定义多个Desc,具体指标值的获取,需要根据具体场景来实现。