2020-07-26 17:09:05 +08:00
|
|
|
package prometheus
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
|
|
"github.com/zeromicro/go-zero/core/syncx"
|
|
|
|
"github.com/zeromicro/go-zero/core/threading"
|
2020-07-26 17:09:05 +08:00
|
|
|
)
|
|
|
|
|
2021-04-30 15:09:49 +08:00
|
|
|
var (
|
|
|
|
once sync.Once
|
|
|
|
enabled syncx.AtomicBool
|
|
|
|
)
|
|
|
|
|
|
|
|
// Enabled returns if prometheus is enabled.
|
|
|
|
func Enabled() bool {
|
|
|
|
return enabled.True()
|
|
|
|
}
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2021-02-22 14:55:04 +08:00
|
|
|
// StartAgent starts a prometheus agent.
|
2020-07-26 17:09:05 +08:00
|
|
|
func StartAgent(c Config) {
|
2021-10-31 18:54:13 +08:00
|
|
|
if len(c.Host) == 0 {
|
|
|
|
return
|
|
|
|
}
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2021-10-31 18:54:13 +08:00
|
|
|
once.Do(func() {
|
2021-04-30 15:09:49 +08:00
|
|
|
enabled.Set(true)
|
2020-07-26 17:09:05 +08:00
|
|
|
threading.GoSafe(func() {
|
|
|
|
http.Handle(c.Path, promhttp.Handler())
|
|
|
|
addr := fmt.Sprintf("%s:%d", c.Host, c.Port)
|
|
|
|
logx.Infof("Starting prometheus agent at %s", addr)
|
|
|
|
if err := http.ListenAndServe(addr, nil); err != nil {
|
|
|
|
logx.Error(err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|