agent.go 620 B

12345678910111213141516171819202122232425262728293031
  1. package prometheus
  2. import (
  3. "fmt"
  4. "net/http"
  5. "sync"
  6. "github.com/prometheus/client_golang/prometheus/promhttp"
  7. "github.com/tal-tech/go-zero/core/logx"
  8. "github.com/tal-tech/go-zero/core/threading"
  9. )
  10. var once sync.Once
  11. // StartAgent starts a prometheus agent.
  12. func StartAgent(c Config) {
  13. once.Do(func() {
  14. if len(c.Host) == 0 {
  15. return
  16. }
  17. threading.GoSafe(func() {
  18. http.Handle(c.Path, promhttp.Handler())
  19. addr := fmt.Sprintf("%s:%d", c.Host, c.Port)
  20. logx.Infof("Starting prometheus agent at %s", addr)
  21. if err := http.ListenAndServe(addr, nil); err != nil {
  22. logx.Error(err)
  23. }
  24. })
  25. })
  26. }