From 5997dc44d8ae6ec9b97db20e8610b2f48d352f79 Mon Sep 17 00:00:00 2001 From: stephen mcquay Date: Fri, 26 Jan 2018 18:05:28 -0800 Subject: [PATCH] track http status codes in metrics --- cmd/hwtd/main.go | 2 +- hooks.go | 9 ++++++++- metrics/metrics.go | 4 ++++ metrics/prom.go | 11 +++++++++++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/cmd/hwtd/main.go b/cmd/hwtd/main.go index 9b44a6d..e2775c2 100644 --- a/cmd/hwtd/main.go +++ b/cmd/hwtd/main.go @@ -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)) diff --git a/hooks.go b/hooks.go index 06ba8a0..af75cb9 100644 --- a/hooks.go +++ b/hooks.go @@ -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 diff --git a/metrics/metrics.go b/metrics/metrics.go index 6dae5da..16e2c10 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -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() +} diff --git a/metrics/prom.go b/metrics/prom.go index 3c4e2d2..984390e 100644 --- a/metrics/prom.go +++ b/metrics/prom.go @@ -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 }