diff --git a/CHANGELOG b/CHANGELOG index b5fcfb3..b3a65d5 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,20 +1,39 @@ -## 0.3.0 / 2019-03-24 +# Changelog -* [FEATURE] Add inflight requests metric per handler. +## [Unreleased] -## 0.2.0 / 2019-03-22 +### Breaking changes +* The Recorder methods now receive a context argument. -* [FEATURE] Add metrics of HTTP response size in bytes. -* [ENHANCEMENT] Make the label names of Prometheus recorder configurable. +### Added +* OpenCensus recorder implementation. -## 0.1.0 / 2019-03-18 +## [0.3.0] - 2019-03-24 -* [FEATURE] Add gorestful compatible middleware. -* [FEATURE] Add httprouter compatible middleware. -* [FEATURE] Add Negroni compatible middleware. -* [FEATURE] Add option to group by status codes. -* [FEATURE] Add predefined handler label. -* [FEATURE] Add URL infered handler label. -* [FEATURE] Add middleware. -* [FEATURE] Add HTTP latency requests. -* [FEATURE] Add Prometheus recorder. \ No newline at end of file +### Added +* Inflight requests metric per handler. + +## [0.2.0] - 2019-03-22 + +### Added +* Metrics of HTTP response size in bytes. +* Make the label names of Prometheus recorder configurable. + +## [0.1.0] - 2019-03-18 + +### Added +* Gorestful compatible middleware. +* Httprouter compatible middleware. +* Negroni compatible middleware. +* Option to group by status codes. +* Predefined handler label. +* URL infered handler label. +* Middleware. +* HTTP latency requests. +* Prometheus recorder. + + +[unreleased]: https://github.com/slok/go-http-metrics/compare/v0.3.0...HEAD +[0.3.0]: https://github.com/slok/go-http-metrics/compare/v0.2.0...v0.3.0 +[0.2.0]: https://github.com/slok/go-http-metrics/compare/v0.1.0...v0.2.0 +[0.1.0]: https://github.com/slok/go-http-metrics/releases/tag/v0.1.0 \ No newline at end of file diff --git a/Readme.md b/Readme.md index 1c95df4..14f23c2 100644 --- a/Readme.md +++ b/Readme.md @@ -39,6 +39,7 @@ The metrics obtained with this middleware are the [most important ones][red] for go-http-metrics is easy to extend to different metric backends by implementing `metrics.Recorder` interface. - [Prometheus][prometheus-recorder] +- [OpenCensus][opencensus-recorder] ## Framework compatibility middlewares @@ -203,3 +204,4 @@ BenchmarkMiddlewareHandler/benchmark_with_predefined_handler_ID-4 1000000 [httprouter-example]: examples/httprouter [gorestful-example]: examples/gorestful [prometheus-recorder]: metrics/prometheus +[opencensus-recorder]: metrics/opencensus diff --git a/examples/gin/main.go b/examples/gin/main.go new file mode 100644 index 0000000..fba73e9 --- /dev/null +++ b/examples/gin/main.go @@ -0,0 +1,59 @@ +package main + +import ( + "log" + "net/http" + "os" + "os/signal" + "syscall" + + "github.com/gin-gonic/gin" + "github.com/prometheus/client_golang/prometheus/promhttp" + prommiddleware "github.com/slok/go-prometheus-middleware" + promgin "github.com/slok/go-prometheus-middleware/gin" +) + +const ( + srvAddr = ":8080" + metricsAddr = ":8081" +) + +func main() { + // Create our middleware. + mdlw := prommiddleware.NewDefault() + + // Create our gin instance. + r := gin.New() + + // Add the middlewares to all gin routes. + r.Use( + promgin.Handler("", mdlw), + gin.Logger(), + ) + + // Add our handler + r.GET("/", func(c *gin.Context) { + c.String(http.StatusOK, "Hello world!") + }) + + // Serve our handler. + go func() { + log.Printf("server listening at %s", srvAddr) + if err := r.Run(srvAddr); err != nil { + log.Panicf("error while serving: %s", err) + } + }() + + // Serve our metrics. + go func() { + log.Printf("metrics listening at %s", metricsAddr) + if err := http.ListenAndServe(metricsAddr, promhttp.Handler()); err != nil { + log.Panicf("error while serving metrics: %s", err) + } + }() + + // Wait until some signal is captured. + sigC := make(chan os.Signal, 1) + signal.Notify(sigC, syscall.SIGTERM, syscall.SIGINT) + <-sigC +} diff --git a/examples/opencensus/main.go b/examples/opencensus/main.go new file mode 100644 index 0000000..68e2478 --- /dev/null +++ b/examples/opencensus/main.go @@ -0,0 +1,77 @@ +package main + +import ( + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + ocmmetrics "github.com/slok/go-http-metrics/metrics/opencensus" + "github.com/slok/go-http-metrics/middleware" + ocprometheus "go.opencensus.io/exporter/prometheus" + "go.opencensus.io/stats/view" +) + +const ( + srvAddr = ":8080" + metricsAddr = ":8081" +) + +// This example will show how you could use opencensus with go-http-middleware +// and serve the metrics in Prometheus format (through OpenCensus). +func main() { + // Create OpenCensus with Prometheus. + ocexporter, err := ocprometheus.NewExporter(ocprometheus.Options{}) + if err != nil { + log.Panicf("error creating OpenCensus exporter: %s", err) + } + view.RegisterExporter(ocexporter) + rec, err := ocmmetrics.NewRecorder(ocmmetrics.Config{}) + if err != nil { + log.Panicf("error creating OpenCensus metrics recorder: %s", err) + } + + // Create our middleware. + mdlw := middleware.New(middleware.Config{ + Recorder: rec, + }) + + // Create our server. + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + time.Sleep(200 * time.Millisecond) + w.WriteHeader(http.StatusOK) + }) + mux.HandleFunc("/test1", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) }) + mux.HandleFunc("/test1/test2", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusAccepted) }) + mux.HandleFunc("/test1/test4", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNonAuthoritativeInfo) }) + mux.HandleFunc("/test2", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }) + mux.HandleFunc("/test3", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusResetContent) }) + + // Wrap our main handler, we pass empty handler ID so the middleware inferes + // the handler label from the URL. + h := mdlw.Handler("", mux) + + // Serve our handler. + go func() { + log.Printf("server listening at %s", srvAddr) + if err := http.ListenAndServe(srvAddr, h); err != nil { + log.Panicf("error while serving: %s", err) + } + }() + + // Serve our metrics. + go func() { + log.Printf("metrics listening at %s", metricsAddr) + if err := http.ListenAndServe(metricsAddr, ocexporter); err != nil { + log.Panicf("error while serving metrics: %s", err) + } + }() + + // Wait until some signal is captured. + sigC := make(chan os.Signal, 1) + signal.Notify(sigC, syscall.SIGTERM, syscall.SIGINT) + <-sigC +} diff --git a/go.mod b/go.mod index d0e8c28..7cd467c 100644 --- a/go.mod +++ b/go.mod @@ -2,8 +2,16 @@ module github.com/slok/go-http-metrics require ( github.com/emicklei/go-restful v2.9.0+incompatible + github.com/gin-gonic/gin v1.3.0 + github.com/golang/mock v1.2.0 // indirect + github.com/json-iterator/go v1.1.6 // indirect github.com/julienschmidt/httprouter v1.2.0 - github.com/prometheus/client_golang v0.9.2 + github.com/kr/pretty v0.1.0 // indirect + github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829 + github.com/slok/go-prometheus-middleware v0.4.0 github.com/stretchr/testify v1.2.2 github.com/urfave/negroni v1.0.0 + go.opencensus.io v0.19.2 + gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect + gopkg.in/yaml.v2 v2.2.2 // indirect ) diff --git a/go.sum b/go.sum index 9b7881a..08d5096 100644 --- a/go.sum +++ b/go.sum @@ -1,40 +1,97 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +git.apache.org/thrift.git v0.12.0/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= +github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= +github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/emicklei/go-restful v2.8.0+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful v2.9.0+incompatible h1:YKhDcF/NL19iSAQcyCATL1MkFXCzxfdaTiuJKr18Ank= github.com/emicklei/go-restful v2.9.0+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.0.0-20170109093832-22d885f9ecc7 h1:AzN37oI0cOS+cougNAV9szl6CVoj2RYwzS3DpUQNtlY= github.com/gin-contrib/sse v0.0.0-20170109093832-22d885f9ecc7/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-gonic/gin v1.3.0 h1:kCmZyPklC0gVdL728E6Aj20uYBJV93nj/TkwBTKhFbs= github.com/gin-gonic/gin v1.3.0/go.mod h1:7cKuhb5qV2ggCFctp2fJQ+ErvciLZrIeoOSOm6mUr7Y= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/grpc-ecosystem/grpc-gateway v1.6.2/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.6 h1:MrUvLMLTMxbqFJ9kzlvat/rYZqZnW3u4wkLzWTaFwKs= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/julienschmidt/httprouter v0.0.0-20180715161854-348b672cd90d/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/julienschmidt/httprouter v1.2.0 h1:TDTW5Yz1mjftljbcKqRcrYhd4XeOoI98t+9HbQbYf7g= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/openzipkin/zipkin-go v0.1.3/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= +github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= +github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v0.9.0-pre1.0.20180914112405-b7b390014bf2/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.2 h1:awm861/B8OKDd2I/6o1dy3ra4BamzKhYOiGItCeZ740= -github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829 h1:D+CiwcpGTW6pL6bv6KI3KbyEyCKyS+1JWS2h8PNDnGA= +github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 h1:idejC8f05m9MGOsuEi1ATq9shN03HrxNkD/luQvxCv8= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f h1:BVwpUVJDADN2ufcGik7W992pyps0wZ888b/y9GXcLTU= +github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= -github.com/prometheus/common v0.0.0-20181126121408-4724e9255275 h1:PnBWHBf+6L0jOqq0gIVUe6Yk0/QMZ640k6NvkxcBf+8= -github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.2.0 h1:kUZDBDTdBVBYBj5Tmh2NZLlF60mfjA27rM34b+cVwNU= +github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a h1:9a8MnZMP0X2nLJdBg+pBmGgkJlSaKC2KaQmTCk1XDtE= -github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1 h1:/K3IL0Z1quvmJ7X0A1AwNEK7CRkVK3YwfOU/QAL4WGg= +github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/slok/go-prometheus-middleware v0.4.0 h1:cXCUg4w4wgcQLTTM/yShI+Tt3blu2C3aPf07TSsM9os= github.com/slok/go-prometheus-middleware v0.4.0/go.mod h1:dEbMQSF4RMuY7tG5XJVTxsHnqVs/AJqTJtpOFk7x/yo= github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= @@ -45,14 +102,78 @@ github.com/ugorji/go/codec v0.0.0-20180831062425-e253f1f20942 h1:CZORS/4d6i+5FKS github.com/ugorji/go/codec v0.0.0-20180831062425-e253f1f20942/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/urfave/negroni v1.0.0 h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc= github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4= +go.opencensus.io v0.19.1/go.mod h1:gug0GbSHa8Pafr0d2urOSgoXHZ6x/RUlaiT0d9pqb4A= +go.opencensus.io v0.19.2 h1:ZZpq6xI6kv/LuE/5s5UQvBU5vMjvRnPb8PvJrIntAnc= +go.opencensus.io v0.19.2/go.mod h1:NO/8qkisMZLZ1FCsKNqtJPwc8/TaclWyY0B6wcYNg9M= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20181217174547-8f45f776aaf1/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180911220305-26e67e76b6c3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 h1:bjcUS9ztw9kFmmIxJInhon/0Is3p+EHBKNgquIzo1OI= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181218192612-074acd46bca6/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181219222714-6e267b5cc78e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +google.golang.org/api v0.0.0-20181220000619-583d854617af/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/api v0.2.0/go.mod h1:IfRCZScioGtypHNTlz3gFk67J8uePVW7uDTBzXuIkhU= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20181219182458-5a97ab628bfb/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= +google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/go-playground/validator.v8 v8.18.2 h1:lFB4DoMU6B626w8ny76MV7VX6W2VHct2GVOI3xgiMrQ= gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20180920025451-e3ad64cb4ed3/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/internal/mocks/metrics/Recorder.go b/internal/mocks/metrics/Recorder.go index 03a5ee6..b6bbcdc 100644 --- a/internal/mocks/metrics/Recorder.go +++ b/internal/mocks/metrics/Recorder.go @@ -2,6 +2,8 @@ package metrics +import context "context" + import mock "github.com/stretchr/testify/mock" import time "time" @@ -10,17 +12,17 @@ type Recorder struct { mock.Mock } -// AddInflightRequests provides a mock function with given fields: id, quantity -func (_m *Recorder) AddInflightRequests(id string, quantity int) { - _m.Called(id, quantity) +// AddInflightRequests provides a mock function with given fields: ctx, id, quantity +func (_m *Recorder) AddInflightRequests(ctx context.Context, id string, quantity int) { + _m.Called(ctx, id, quantity) } -// ObserveHTTPRequestDuration provides a mock function with given fields: id, duration, method, code -func (_m *Recorder) ObserveHTTPRequestDuration(id string, duration time.Duration, method string, code string) { - _m.Called(id, duration, method, code) +// ObserveHTTPRequestDuration provides a mock function with given fields: ctx, id, duration, method, code +func (_m *Recorder) ObserveHTTPRequestDuration(ctx context.Context, id string, duration time.Duration, method string, code string) { + _m.Called(ctx, id, duration, method, code) } -// ObserveHTTPResponseSize provides a mock function with given fields: id, sizeBytes, method, code -func (_m *Recorder) ObserveHTTPResponseSize(id string, sizeBytes int64, method string, code string) { - _m.Called(id, sizeBytes, method, code) +// ObserveHTTPResponseSize provides a mock function with given fields: ctx, id, sizeBytes, method, code +func (_m *Recorder) ObserveHTTPResponseSize(ctx context.Context, id string, sizeBytes int64, method string, code string) { + _m.Called(ctx, id, sizeBytes, method, code) } diff --git a/metrics/metrics.go b/metrics/metrics.go index 9bd44de..9b2487d 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -1,6 +1,7 @@ package metrics import ( + "context" "time" ) @@ -9,12 +10,12 @@ import ( // middlewares. type Recorder interface { // ObserveHTTPRequestDuration measures the duration of an HTTP request. - ObserveHTTPRequestDuration(id string, duration time.Duration, method, code string) + ObserveHTTPRequestDuration(ctx context.Context, id string, duration time.Duration, method, code string) // ObserveHTTPResponseSize measures the size of an HTTP response in bytes. - ObserveHTTPResponseSize(id string, sizeBytes int64, method, code string) + ObserveHTTPResponseSize(ctx context.Context, id string, sizeBytes int64, method, code string) // AddInflightRequests increments and decrements the number of inflight request being // processed. - AddInflightRequests(id string, quantity int) + AddInflightRequests(ctx context.Context, id string, quantity int) } // Dummy is a dummy recorder. @@ -22,6 +23,8 @@ var Dummy = &dummy{} type dummy struct{} -func (dummy) ObserveHTTPRequestDuration(id string, duration time.Duration, method, code string) {} -func (dummy) ObserveHTTPResponseSize(id string, sizeBytes int64, method, code string) {} -func (dummy) AddInflightRequests(id string, quantity int) {} +func (dummy) ObserveHTTPRequestDuration(ctx context.Context, id string, duration time.Duration, method, code string) { +} +func (dummy) ObserveHTTPResponseSize(ctx context.Context, id string, sizeBytes int64, method, code string) { +} +func (dummy) AddInflightRequests(ctx context.Context, id string, quantity int) {} diff --git a/metrics/opencensus/opencensus.go b/metrics/opencensus/opencensus.go new file mode 100644 index 0000000..d7c1818 --- /dev/null +++ b/metrics/opencensus/opencensus.go @@ -0,0 +1,197 @@ +package opencensus + +import ( + "context" + "time" + + "go.opencensus.io/stats" + "go.opencensus.io/stats/view" + "go.opencensus.io/tag" + + "github.com/slok/go-http-metrics/metrics" +) + +var ( + durationBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10} + sizeBuckets = []float64{100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000} +) + +// Config has the dependencies and values of the recorder. +type Config struct { + // DurationBuckets are the buckets used for the HTTP request duration metrics, + // by default uses default buckets (from 5ms to 10s). + DurationBuckets []float64 + // SizeBuckets are the buckets for the HTTP response size metrics, + // by default uses a exponential buckets from 100B to 1GB. + SizeBuckets []float64 + // HandlerIDLabel is the name that will be set to the handler ID label, by default is `handler`. + HandlerIDLabel string + // StatusCodeLabel is the name that will be set to the status code label, by default is `code`. + StatusCodeLabel string + // MethodLabel is the name that will be set to the method label, by default is `method`. + MethodLabel string + // UnregisterViewsBeforeRegister will unregister the previous Recorder views before registering + // again. This is required on cases where multiple instances of recorder will be made due to how + // Opencensus is implemented (everything is at global state). Sadly this option is a kind of hack + // so we can test without exposing the views to the user. On regular usage this option is very + // rare to use it. + UnregisterViewsBeforeRegister bool +} + +func (c *Config) defaults() { + if len(c.DurationBuckets) == 0 { + c.DurationBuckets = durationBuckets + } + + if len(c.SizeBuckets) == 0 { + c.SizeBuckets = sizeBuckets + } + + if c.HandlerIDLabel == "" { + c.HandlerIDLabel = "handler" + } + + if c.StatusCodeLabel == "" { + c.StatusCodeLabel = "code" + } + + if c.MethodLabel == "" { + c.MethodLabel = "method" + } +} + +type recorder struct { + // Keys. + codeKey tag.Key + methodKey tag.Key + handlerKey tag.Key + + // Measures. + latencySecs *stats.Float64Measure + sizeBytes *stats.Int64Measure + inflightCount *stats.Int64Measure +} + +// NewRecorder returns a new Recorder that uses OpenCensus stats +// as the backend. +func NewRecorder(cfg Config) (metrics.Recorder, error) { + cfg.defaults() + + r := &recorder{} + + // Prepare metrics. + err := r.createKeys(cfg) + if err != nil { + return nil, err + } + r.createMeasurements() + err = r.registerViews(cfg) + if err != nil { + return nil, err + } + + return r, nil +} + +func (r *recorder) createKeys(cfg Config) error { + code, err := tag.NewKey(cfg.StatusCodeLabel) + if err != nil { + return err + } + r.codeKey = code + + method, err := tag.NewKey(cfg.MethodLabel) + if err != nil { + return err + } + r.methodKey = method + + handler, err := tag.NewKey(cfg.HandlerIDLabel) + if err != nil { + return err + } + r.handlerKey = handler + + return nil +} + +func (r *recorder) createMeasurements() { + r.latencySecs = stats.Float64( + "http_request_duration_seconds", + "The latency of the HTTP requests", + "s") + r.sizeBytes = stats.Int64( + "http_response_size_bytes", + "The size of the HTTP responses", + stats.UnitBytes) + r.inflightCount = stats.Int64( + "http_requests_inflight", + "The number of inflight requests being handled at the same time", + stats.UnitNone) +} + +func (r recorder) registerViews(cfg Config) error { + + // OpenCensus uses global states, sadly we can't have view insta + durationView := &view.View{ + Name: "http_request_duration_seconds", + Description: "The latency of the HTTP requests", + TagKeys: []tag.Key{r.handlerKey, r.methodKey, r.codeKey}, + Measure: r.latencySecs, + Aggregation: view.Distribution(cfg.DurationBuckets...), + } + sizeView := &view.View{ + Name: "http_response_size_bytes", + Description: "The size of the HTTP responses", + TagKeys: []tag.Key{r.handlerKey, r.methodKey, r.codeKey}, + Measure: r.sizeBytes, + Aggregation: view.Distribution(cfg.SizeBuckets...), + } + inflightView := &view.View{ + Name: "http_requests_inflight", + Description: "The number of inflight requests being handled at the same time", + TagKeys: []tag.Key{r.handlerKey}, + Measure: r.inflightCount, + Aggregation: view.Sum(), + } + + // Do we need to unregister the same views before registering. + if cfg.UnregisterViewsBeforeRegister { + view.Unregister(durationView, sizeView, inflightView) + } + + err := view.Register(durationView, sizeView, inflightView) + if err != nil { + return err + } + + return nil +} + +func (r recorder) ObserveHTTPRequestDuration(ctx context.Context, id string, duration time.Duration, method, code string) { + ctx, _ = tag.New(ctx, + tag.Upsert(r.handlerKey, id), + tag.Upsert(r.methodKey, method), + tag.Upsert(r.codeKey, code), + ) + + stats.Record(ctx, r.latencySecs.M(duration.Seconds())) +} + +func (r recorder) ObserveHTTPResponseSize(ctx context.Context, id string, sizeBytes int64, method, code string) { + ctx, _ = tag.New(ctx, + tag.Upsert(r.handlerKey, id), + tag.Upsert(r.methodKey, method), + tag.Upsert(r.codeKey, code), + ) + + stats.Record(ctx, r.sizeBytes.M(sizeBytes)) +} + +func (r recorder) AddInflightRequests(ctx context.Context, id string, quantity int) { + ctx, _ = tag.New(ctx, + tag.Upsert(r.handlerKey, id), + ) + + stats.Record(ctx, r.inflightCount.M(int64(quantity))) +} diff --git a/metrics/opencensus/opencensus_test.go b/metrics/opencensus/opencensus_test.go new file mode 100644 index 0000000..3440c95 --- /dev/null +++ b/metrics/opencensus/opencensus_test.go @@ -0,0 +1,202 @@ +package opencensus_test + +import ( + "context" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + ocprometheus "go.opencensus.io/exporter/prometheus" + "go.opencensus.io/stats/view" + + "github.com/slok/go-http-metrics/metrics" + ocmetrics "github.com/slok/go-http-metrics/metrics/opencensus" +) + +func TestOpenCensusRecorder(t *testing.T) { + tests := []struct { + name string + config ocmetrics.Config + recordMetrics func(r metrics.Recorder) + expMetrics []string + }{ + { + name: "Default configuration should measure with the default metric style.", + config: ocmetrics.Config{}, + recordMetrics: func(r metrics.Recorder) { + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 4*time.Second, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 175*time.Millisecond, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test2", 30*time.Millisecond, http.MethodGet, "201") + r.ObserveHTTPRequestDuration(context.TODO(), "test3", 700*time.Millisecond, http.MethodPost, "500") + r.ObserveHTTPResponseSize(context.TODO(), "test4", 529930, http.MethodPost, "500") + r.ObserveHTTPResponseSize(context.TODO(), "test4", 231, http.MethodPost, "500") + r.ObserveHTTPResponseSize(context.TODO(), "test4", 99999999, http.MethodPatch, "429") + r.AddInflightRequests(context.TODO(), "test1", 5) + r.AddInflightRequests(context.TODO(), "test1", -3) + r.AddInflightRequests(context.TODO(), "test2", 9) + }, + expMetrics: []string{ + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="0.005"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="0.01"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="0.025"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="0.05"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="0.1"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="0.25"} 1`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="0.5"} 1`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="1"} 1`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="2.5"} 1`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="5"} 2`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="10"} 2`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="+Inf"} 2`, + `http_request_duration_seconds_count{code="200",handler="test1",method="GET"} 2`, + + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="0.005"} 0`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="0.01"} 0`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="0.025"} 0`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="0.05"} 1`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="0.1"} 1`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="0.25"} 1`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="0.5"} 1`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="1"} 1`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="2.5"} 1`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="5"} 1`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="10"} 1`, + `http_request_duration_seconds_bucket{code="201",handler="test2",method="GET",le="+Inf"} 1`, + `http_request_duration_seconds_count{code="201",handler="test2",method="GET"} 1`, + + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="0.005"} 0`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="0.01"} 0`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="0.025"} 0`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="0.05"} 0`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="0.1"} 0`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="0.25"} 0`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="0.5"} 0`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="1"} 1`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="2.5"} 1`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="5"} 1`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="10"} 1`, + `http_request_duration_seconds_bucket{code="500",handler="test3",method="POST",le="+Inf"} 1`, + `http_request_duration_seconds_count{code="500",handler="test3",method="POST"} 1`, + + `http_response_size_bytes_bucket{code="429",handler="test4",method="PATCH",le="100"} 0`, + `http_response_size_bytes_bucket{code="429",handler="test4",method="PATCH",le="1000"} 0`, + `http_response_size_bytes_bucket{code="429",handler="test4",method="PATCH",le="10000"} 0`, + `http_response_size_bytes_bucket{code="429",handler="test4",method="PATCH",le="100000"} 0`, + `http_response_size_bytes_bucket{code="429",handler="test4",method="PATCH",le="1e+06"} 0`, + `http_response_size_bytes_bucket{code="429",handler="test4",method="PATCH",le="1e+07"} 0`, + `http_response_size_bytes_bucket{code="429",handler="test4",method="PATCH",le="1e+08"} 1`, + `http_response_size_bytes_bucket{code="429",handler="test4",method="PATCH",le="1e+09"} 1`, + `http_response_size_bytes_bucket{code="429",handler="test4",method="PATCH",le="+Inf"} 1`, + `http_response_size_bytes_count{code="429",handler="test4",method="PATCH"} 1`, + + `http_response_size_bytes_bucket{code="500",handler="test4",method="POST",le="100"} 0`, + `http_response_size_bytes_bucket{code="500",handler="test4",method="POST",le="1000"} 1`, + `http_response_size_bytes_bucket{code="500",handler="test4",method="POST",le="10000"} 1`, + `http_response_size_bytes_bucket{code="500",handler="test4",method="POST",le="100000"} 1`, + `http_response_size_bytes_bucket{code="500",handler="test4",method="POST",le="1e+06"} 2`, + `http_response_size_bytes_bucket{code="500",handler="test4",method="POST",le="1e+07"} 2`, + `http_response_size_bytes_bucket{code="500",handler="test4",method="POST",le="1e+08"} 2`, + `http_response_size_bytes_bucket{code="500",handler="test4",method="POST",le="1e+09"} 2`, + `http_response_size_bytes_bucket{code="500",handler="test4",method="POST",le="+Inf"} 2`, + `http_response_size_bytes_count{code="500",handler="test4",method="POST"} 2`, + + `http_requests_inflight{handler="test1"} 2`, + + `http_requests_inflight{handler="test2"} 9`, + }, + }, + { + name: "Using custom buckets in the configuration should measure with custom buckets.", + config: ocmetrics.Config{ + DurationBuckets: []float64{1, 2, 10, 20, 50, 200, 500, 1000, 2000, 5000, 10000}, + }, + recordMetrics: func(r metrics.Recorder) { + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 75*time.Minute, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 200*time.Hour, http.MethodGet, "200") + }, + expMetrics: []string{ + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="1"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="2"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="10"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="20"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="50"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="200"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="500"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="1000"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="2000"} 0`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="5000"} 1`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="10000"} 1`, + `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="+Inf"} 2`, + `http_request_duration_seconds_count{code="200",handler="test1",method="GET"} 2`, + }, + }, + { + name: "Using a custom labels in the configuration should measure with those labels.", + config: ocmetrics.Config{ + HandlerIDLabel: "route_id", + StatusCodeLabel: "status_code", + MethodLabel: "http_method", + }, + recordMetrics: func(r metrics.Recorder) { + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 4*time.Second, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 175*time.Millisecond, http.MethodGet, "200") + }, + expMetrics: []string{ + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="0.005"} 0`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="0.01"} 0`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="0.025"} 0`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="0.05"} 0`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="0.1"} 0`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="0.25"} 1`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="0.5"} 1`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="1"} 1`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="2.5"} 1`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="5"} 2`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="10"} 2`, + `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="+Inf"} 2`, + `http_request_duration_seconds_count{http_method="GET",route_id="test1",status_code="200"} 2`, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + assert := assert.New(t) + require := require.New(t) + + // Initialize opencensus. + ocexporter, err := ocprometheus.NewExporter(ocprometheus.Options{}) + require.NoError(err) + view.RegisterExporter(ocexporter) + + // Create our recorder. + test.config.UnregisterViewsBeforeRegister = true + mrecorder, err := ocmetrics.NewRecorder(test.config) + require.NoError(err) + test.recordMetrics(mrecorder) + + // Set reporting time and wait to compute metrics view. + view.SetReportingPeriod(1 * time.Millisecond) + time.Sleep(10 * time.Millisecond) + + // Get the metrics handler and serve. + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/metrics", nil) + ocexporter.ServeHTTP(rec, req) + + resp := rec.Result() + + // Check all metrics are present. + if assert.Equal(http.StatusOK, resp.StatusCode) { + body, _ := ioutil.ReadAll(resp.Body) + for _, expMetric := range test.expMetrics { + assert.Contains(string(body), expMetric, "metric not present on the result") + } + } + }) + } +} diff --git a/metrics/prometheus/prometheus.go b/metrics/prometheus/prometheus.go index f5fb243..e066e8b 100644 --- a/metrics/prometheus/prometheus.go +++ b/metrics/prometheus/prometheus.go @@ -1,6 +1,7 @@ package prometheus import ( + "context" "time" "github.com/prometheus/client_golang/prometheus" @@ -106,14 +107,14 @@ func (r recorder) registerMetrics() { ) } -func (r recorder) ObserveHTTPRequestDuration(id string, duration time.Duration, method, code string) { +func (r recorder) ObserveHTTPRequestDuration(_ context.Context, id string, duration time.Duration, method, code string) { r.httpRequestDurHistogram.WithLabelValues(id, method, code).Observe(duration.Seconds()) } -func (r recorder) ObserveHTTPResponseSize(id string, sizeBytes int64, method, code string) { +func (r recorder) ObserveHTTPResponseSize(_ context.Context, id string, sizeBytes int64, method, code string) { r.httpResponseSizeHistogram.WithLabelValues(id, method, code).Observe(float64(sizeBytes)) } -func (r recorder) AddInflightRequests(id string, quantity int) { +func (r recorder) AddInflightRequests(_ context.Context, id string, quantity int) { r.httpRequestsInflight.WithLabelValues(id).Add(float64(quantity)) } diff --git a/metrics/prometheus/prometheus_test.go b/metrics/prometheus/prometheus_test.go index d784cda..da87420 100644 --- a/metrics/prometheus/prometheus_test.go +++ b/metrics/prometheus/prometheus_test.go @@ -1,6 +1,7 @@ package prometheus_test import ( + "context" "io/ioutil" "net/http" "net/http/httptest" @@ -26,16 +27,16 @@ func TestPrometheusRecorder(t *testing.T) { name: "Default configuration should measure with the default metric style.", config: libprometheus.Config{}, recordMetrics: func(r metrics.Recorder) { - r.ObserveHTTPRequestDuration("test1", 5*time.Second, http.MethodGet, "200") - r.ObserveHTTPRequestDuration("test1", 175*time.Millisecond, http.MethodGet, "200") - r.ObserveHTTPRequestDuration("test2", 50*time.Millisecond, http.MethodGet, "201") - r.ObserveHTTPRequestDuration("test3", 700*time.Millisecond, http.MethodPost, "500") - r.ObserveHTTPResponseSize("test4", 529930, http.MethodPost, "500") - r.ObserveHTTPResponseSize("test4", 231, http.MethodPost, "500") - r.ObserveHTTPResponseSize("test4", 99999999, http.MethodPatch, "429") - r.AddInflightRequests("test1", 5) - r.AddInflightRequests("test1", -3) - r.AddInflightRequests("test2", 9) + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 5*time.Second, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 175*time.Millisecond, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test2", 50*time.Millisecond, http.MethodGet, "201") + r.ObserveHTTPRequestDuration(context.TODO(), "test3", 700*time.Millisecond, http.MethodPost, "500") + r.ObserveHTTPResponseSize(context.TODO(), "test4", 529930, http.MethodPost, "500") + r.ObserveHTTPResponseSize(context.TODO(), "test4", 231, http.MethodPost, "500") + r.ObserveHTTPResponseSize(context.TODO(), "test4", 99999999, http.MethodPatch, "429") + r.AddInflightRequests(context.TODO(), "test1", 5) + r.AddInflightRequests(context.TODO(), "test1", -3) + r.AddInflightRequests(context.TODO(), "test2", 9) }, expMetrics: []string{ `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="0.005"} 0`, @@ -113,8 +114,8 @@ func TestPrometheusRecorder(t *testing.T) { Prefix: "batman", }, recordMetrics: func(r metrics.Recorder) { - r.ObserveHTTPRequestDuration("test1", 5*time.Second, http.MethodGet, "200") - r.ObserveHTTPRequestDuration("test1", 175*time.Millisecond, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 5*time.Second, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 175*time.Millisecond, http.MethodGet, "200") }, expMetrics: []string{ `batman_http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="0.005"} 0`, @@ -138,8 +139,8 @@ func TestPrometheusRecorder(t *testing.T) { DurationBuckets: []float64{1, 2, 10, 20, 50, 200, 500, 1000, 2000, 5000, 10000}, }, recordMetrics: func(r metrics.Recorder) { - r.ObserveHTTPRequestDuration("test1", 75*time.Minute, http.MethodGet, "200") - r.ObserveHTTPRequestDuration("test1", 200*time.Hour, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 75*time.Minute, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 200*time.Hour, http.MethodGet, "200") }, expMetrics: []string{ `http_request_duration_seconds_bucket{code="200",handler="test1",method="GET",le="1"} 0`, @@ -165,8 +166,8 @@ func TestPrometheusRecorder(t *testing.T) { MethodLabel: "http_method", }, recordMetrics: func(r metrics.Recorder) { - r.ObserveHTTPRequestDuration("test1", 5*time.Second, http.MethodGet, "200") - r.ObserveHTTPRequestDuration("test1", 175*time.Millisecond, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 5*time.Second, http.MethodGet, "200") + r.ObserveHTTPRequestDuration(context.TODO(), "test1", 175*time.Millisecond, http.MethodGet, "200") }, expMetrics: []string{ `http_request_duration_seconds_bucket{http_method="GET",route_id="test1",status_code="200",le="0.005"} 0`, diff --git a/middleware/gorestful/gorestful_test.go b/middleware/gorestful/gorestful_test.go index 8a78d3f..a15da59 100644 --- a/middleware/gorestful/gorestful_test.go +++ b/middleware/gorestful/gorestful_test.go @@ -47,10 +47,10 @@ func TestMiddlewareIntegration(t *testing.T) { // Mocks. mr := &mmetrics.Recorder{} - mr.On("ObserveHTTPRequestDuration", test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() - mr.On("ObserveHTTPResponseSize", test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() - mr.On("AddInflightRequests", test.expHandlerID, 1).Once() - mr.On("AddInflightRequests", test.expHandlerID, -1).Once() + mr.On("ObserveHTTPRequestDuration", mock.Anything, test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() + mr.On("ObserveHTTPResponseSize", mock.Anything, test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() + mr.On("AddInflightRequests", mock.Anything, test.expHandlerID, 1).Once() + mr.On("AddInflightRequests", mock.Anything, test.expHandlerID, -1).Once() // Create our instance with the middleware. mdlw := middleware.New(middleware.Config{Recorder: mr}) diff --git a/middleware/httprouter/httprouter_test.go b/middleware/httprouter/httprouter_test.go index 65d6f94..7af5673 100644 --- a/middleware/httprouter/httprouter_test.go +++ b/middleware/httprouter/httprouter_test.go @@ -47,10 +47,10 @@ func TestMiddlewareIntegration(t *testing.T) { // Mocks. mr := &mmetrics.Recorder{} - mr.On("ObserveHTTPRequestDuration", test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() - mr.On("ObserveHTTPResponseSize", test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() - mr.On("AddInflightRequests", test.expHandlerID, 1).Once() - mr.On("AddInflightRequests", test.expHandlerID, -1).Once() + mr.On("ObserveHTTPRequestDuration", mock.Anything, test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() + mr.On("ObserveHTTPResponseSize", mock.Anything, test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() + mr.On("AddInflightRequests", mock.Anything, test.expHandlerID, 1).Once() + mr.On("AddInflightRequests", mock.Anything, test.expHandlerID, -1).Once() // Create our instance with the middleware. mdlw := middleware.New(middleware.Config{Recorder: mr}) diff --git a/middleware/middleware.go b/middleware/middleware.go index 93238e5..7df0289 100644 --- a/middleware/middleware.go +++ b/middleware/middleware.go @@ -86,8 +86,8 @@ func (m *middleware) Handler(handlerID string, h http.Handler) http.Handler { // Measure inflights if required. if !m.cfg.DisableMeasureInflight { - m.cfg.Recorder.AddInflightRequests(hid, 1) - defer m.cfg.Recorder.AddInflightRequests(hid, -1) + m.cfg.Recorder.AddInflightRequests(r.Context(), hid, 1) + defer m.cfg.Recorder.AddInflightRequests(r.Context(), hid, -1) } // Start the timer and when finishing measure the duration. @@ -105,11 +105,11 @@ func (m *middleware) Handler(handlerID string, h http.Handler) http.Handler { code = strconv.Itoa(wi.statusCode) } - m.cfg.Recorder.ObserveHTTPRequestDuration(hid, duration, r.Method, code) + m.cfg.Recorder.ObserveHTTPRequestDuration(r.Context(), hid, duration, r.Method, code) // Measure size of response if required. if !m.cfg.DisableMeasureSize { - m.cfg.Recorder.ObserveHTTPResponseSize(hid, int64(wi.bytesWritten), r.Method, code) + m.cfg.Recorder.ObserveHTTPResponseSize(r.Context(), hid, int64(wi.bytesWritten), r.Method, code) } }() diff --git a/middleware/middleware_test.go b/middleware/middleware_test.go index 56e2d99..4b551c0 100644 --- a/middleware/middleware_test.go +++ b/middleware/middleware_test.go @@ -67,10 +67,10 @@ func TestMiddlewareHandler(t *testing.T) { t.Run(test.name, func(t *testing.T) { // Mocks. mr := &mmetrics.Recorder{} - mr.On("ObserveHTTPRequestDuration", test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() - mr.On("ObserveHTTPResponseSize", test.expHandlerID, test.expSize, test.expMethod, test.expStatusCode).Once() - mr.On("AddInflightRequests", test.expHandlerID, 1).Once() - mr.On("AddInflightRequests", test.expHandlerID, -1).Once() + mr.On("ObserveHTTPRequestDuration", mock.Anything, test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() + mr.On("ObserveHTTPResponseSize", mock.Anything, test.expHandlerID, test.expSize, test.expMethod, test.expStatusCode).Once() + mr.On("AddInflightRequests", mock.Anything, test.expHandlerID, 1).Once() + mr.On("AddInflightRequests", mock.Anything, test.expHandlerID, -1).Once() // Make the request. test.config.Recorder = mr diff --git a/middleware/negroni/negroni_test.go b/middleware/negroni/negroni_test.go index 53a45db..156be61 100644 --- a/middleware/negroni/negroni_test.go +++ b/middleware/negroni/negroni_test.go @@ -47,10 +47,10 @@ func TestMiddlewareIntegration(t *testing.T) { // Mocks. mr := &mmetrics.Recorder{} - mr.On("ObserveHTTPRequestDuration", test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() - mr.On("ObserveHTTPResponseSize", test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() - mr.On("AddInflightRequests", test.expHandlerID, 1).Once() - mr.On("AddInflightRequests", test.expHandlerID, -1).Once() + mr.On("ObserveHTTPRequestDuration", mock.Anything, test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() + mr.On("ObserveHTTPResponseSize", mock.Anything, test.expHandlerID, mock.Anything, test.expMethod, test.expStatusCode).Once() + mr.On("AddInflightRequests", mock.Anything, test.expHandlerID, 1).Once() + mr.On("AddInflightRequests", mock.Anything, test.expHandlerID, -1).Once() // Create our negroni instance with the middleware. mdlw := middleware.New(middleware.Config{Recorder: mr})