track http status codes in metrics

This commit is contained in:
Stephen McQuay 2018-01-26 18:05:28 -08:00
parent cf10974419
commit 5997dc44d8
Signed by: sm
GPG Key ID: 4E4B72F479BA3CE5
4 changed files with 24 additions and 2 deletions

View File

@ -23,7 +23,7 @@ func main() {
}
s := &hwt.Server{hn}
hs := hwt.NewMetricsHooks(metrics.HTTPLatency)
hs := hwt.NewMetricsHooks(metrics.HTTPLatency, metrics.HTTPCode)
th := pb.NewHelloWorldServer(s, hs)
sm := http.NewServeMux()
sm.HandleFunc("/", hwt.Auth(th.ServeHTTP))

View File

@ -10,8 +10,9 @@ import (
var reqStartKey = new(int)
type Timer func(path string, dur time.Duration)
type Statuser func(path, status string)
func NewMetricsHooks(timer Timer) *twirp.ServerHooks {
func NewMetricsHooks(timer Timer, status Statuser) *twirp.ServerHooks {
hs := &twirp.ServerHooks{}
hs.RequestReceived = func(ctx context.Context) (context.Context, error) {
@ -31,6 +32,12 @@ func NewMetricsHooks(timer Timer) *twirp.ServerHooks {
}
dur := time.Now().Sub(start)
timer(name, dur)
sc, ok := twirp.StatusCode(ctx)
if !ok {
panic("missing code")
}
status(name, sc)
}
return hs

View File

@ -7,3 +7,7 @@ import (
func HTTPLatency(path string, dur time.Duration) {
httpReqLat.WithLabelValues(path).Observe(float64(dur) / float64(time.Millisecond))
}
func HTTPCode(path string, status string) {
httpStatus.WithLabelValues(path, status).Inc()
}

View File

@ -21,11 +21,22 @@ var (
},
[]string{"path"},
)
httpStatus = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hwt_http_requests_total",
Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
},
[]string{"path", "code"},
)
)
func RegisterPromMetrics() error {
if err := prometheus.Register(httpReqLat); err != nil {
return errors.Wrap(err, "registering http request latency")
}
if err := prometheus.Register(httpStatus); err != nil {
return errors.Wrap(err, "registering http request status")
}
return nil
}