agent.go 901 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package prometheus
  2. import (
  3. "fmt"
  4. "net/http"
  5. "sync"
  6. "github.com/prometheus/client_golang/prometheus/promhttp"
  7. "github.com/wuntsong-org/go-zero-plus/core/logx"
  8. "github.com/wuntsong-org/go-zero-plus/core/syncx"
  9. "github.com/wuntsong-org/go-zero-plus/core/threading"
  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. // Enable enables prometheus.
  20. func Enable() {
  21. enabled.Set(true)
  22. }
  23. // StartAgent starts a prometheus agent.
  24. func StartAgent(c Config) {
  25. if len(c.Host) == 0 {
  26. return
  27. }
  28. once.Do(func() {
  29. enabled.Set(true)
  30. threading.GoSafe(func() {
  31. http.Handle(c.Path, promhttp.Handler())
  32. addr := fmt.Sprintf("%s:%d", c.Host, c.Port)
  33. logx.Infof("Starting prometheus agent at %s", addr)
  34. if err := http.ListenAndServe(addr, nil); err != nil {
  35. logx.Error(err)
  36. }
  37. })
  38. })
  39. }