github.com/lingyao2333/mo-zero@v1.4.1/core/prometheus/agent.go (about) 1 package prometheus 2 3 import ( 4 "fmt" 5 "net/http" 6 "sync" 7 8 "github.com/lingyao2333/mo-zero/core/logx" 9 "github.com/lingyao2333/mo-zero/core/syncx" 10 "github.com/lingyao2333/mo-zero/core/threading" 11 "github.com/prometheus/client_golang/prometheus/promhttp" 12 ) 13 14 var ( 15 once sync.Once 16 enabled syncx.AtomicBool 17 ) 18 19 // Enabled returns if prometheus is enabled. 20 func Enabled() bool { 21 return enabled.True() 22 } 23 24 // StartAgent starts a prometheus agent. 25 func StartAgent(c Config) { 26 if len(c.Host) == 0 { 27 return 28 } 29 30 once.Do(func() { 31 enabled.Set(true) 32 threading.GoSafe(func() { 33 http.Handle(c.Path, promhttp.Handler()) 34 addr := fmt.Sprintf("%s:%d", c.Host, c.Port) 35 logx.Infof("Starting prometheus agent at %s", addr) 36 if err := http.ListenAndServe(addr, nil); err != nil { 37 logx.Error(err) 38 } 39 }) 40 }) 41 }