common/metricsserver/metrics.go
2023-07-08 11:45:01 -07:00

69 lines
1.2 KiB
Go

package metricsserver
import (
"context"
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.ntppool.org/common/logger"
)
type Metrics struct {
r *prometheus.Registry
}
func New() *Metrics {
r := prometheus.NewRegistry()
m := &Metrics{
r: r,
}
return m
}
func (m *Metrics) Registry() prometheus.Registerer {
return m.r
}
func (m *Metrics) Handler() http.Handler {
log := logger.NewStdLog("prom http", false, nil)
return promhttp.HandlerFor(m.r, promhttp.HandlerOpts{
ErrorLog: log,
Registry: m.r,
EnableOpenMetrics: true,
})
}
func (m *Metrics) ListenAndServe(ctx context.Context, port int) {
log := logger.Setup()
srv := &http.Server{
Addr: ":" + strconv.Itoa(port),
ReadTimeout: 10 * time.Second,
WriteTimeout: 20 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: m.Handler(),
}
go func() {
err := srv.ListenAndServe()
if err != http.ErrServerClosed {
log.Warn("metrics server done listening", "err", err)
}
}()
<-ctx.Done()
if err := srv.Shutdown(ctx); err != nil {
log.Error("metrics server shutdown failed", "err", err)
}
}