12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- package prometheus
- import (
- "fmt"
- "net/http"
- "sync"
- "github.com/prometheus/client_golang/prometheus/promhttp"
- "github.com/wuntsong-org/go-zero-plus/core/logx"
- "github.com/wuntsong-org/go-zero-plus/core/syncx"
- "github.com/wuntsong-org/go-zero-plus/core/threading"
- )
- var (
- once sync.Once
- enabled syncx.AtomicBool
- )
- // Enabled returns if prometheus is enabled.
- func Enabled() bool {
- return enabled.True()
- }
- // Enable enables prometheus.
- func Enable() {
- enabled.Set(true)
- }
- // StartAgent starts a prometheus agent.
- func StartAgent(c Config) {
- if len(c.Host) == 0 {
- return
- }
- once.Do(func() {
- enabled.Set(true)
- 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)
- }
- })
- })
- }
|