prysm-pulse/shared/prometheus/service.go
Leandro Lugaresi d061c784e0 Added Prometheus Client and p2p Metrics (#673)
* Added prometheus client and p2p metrics

* Avoid run the adapter if the metrics are disabled

* fix visibility issue

* Fix invalid p2p.Message sent to Adapters

The middlewares (adapters) must receive the complete message to avoid
problems and the main Handler must get the values from middlewares

Also, added tests and comments for metrics package

* Added logrus hook collector

This collector is used to collect counters of log messages.
The main purpose of these metric is to know how many warnings and errors
the system are getting.

* Add hook when register the prometheus service

* update bazel builds

* fix emit tests and remove unused imports

* gazelle --fix

* remove unused logger

* move prometheus package to shared directory

* better metric names and fix metric paths

* improve metric tests and start to use promauto

* added prometheus initial documentation

* fix tests

* fix type differences with go get and bazel

* Fix service test
2018-11-15 07:54:45 -05:00

49 lines
1.3 KiB
Go

package prometheus
import (
"context"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
)
var log = logrus.WithField("prefix", "prometheus")
// Service provides Prometheus metrics via the /metrics route. This route will
// show all the metrics registered with the Prometheus DefaultRegisterer.
type Service struct {
server *http.Server
}
// NewPrometheusService sets up a new instance for a given address host:port.
// An empty host will match with any IP so an address like ":2121" is perfectly acceptable.
func NewPrometheusService(addr string) *Service {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
return &Service{
server: &http.Server{Addr: addr, Handler: mux},
}
}
// Start the prometheus service.
func (s *Service) Start() {
log.WithField("endpoint", s.server.Addr).Info("Starting service")
go func() {
err := s.server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Errorf("Could not listen to host:port :%s: %v", s.server.Addr, err)
}
}()
}
// Stop the service gracefully.
func (s *Service) Stop() error {
log.Info("Stopping service")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return s.server.Shutdown(ctx)
}