agent.go 800 B

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