@@ -22,6 +22,7 @@ package prometheus
22
22
23
23
import (
24
24
"bytes"
25
+ "errors"
25
26
"net/http"
26
27
"os"
27
28
"strconv"
@@ -364,7 +365,7 @@ func (p *Prometheus) Use(e *echo.Echo) {
364
365
365
366
// HandlerFunc defines handler function for middleware
366
367
func (p * Prometheus ) HandlerFunc (next echo.HandlerFunc ) echo.HandlerFunc {
367
- return func (c echo.Context ) ( err error ) {
368
+ return func (c echo.Context ) error {
368
369
if c .Path () == p .MetricsPath {
369
370
return next (c )
370
371
}
@@ -375,18 +376,22 @@ func (p *Prometheus) HandlerFunc(next echo.HandlerFunc) echo.HandlerFunc {
375
376
start := time .Now ()
376
377
reqSz := computeApproximateRequestSize (c .Request ())
377
378
378
- if err = next (c ); err != nil {
379
- c .Error (err )
380
- }
379
+ err := next (c )
381
380
382
- status := strconv .Itoa (c .Response ().Status )
383
- url := p .RequestCounterURLLabelMappingFunc (c )
381
+ status := c .Response ().Status
382
+ if err != nil {
383
+ var httpError * echo.HTTPError
384
+ if errors .As (err , & httpError ) {
385
+ status = httpError .Code
386
+ }
387
+ if status == 0 || status == http .StatusOK {
388
+ status = http .StatusInternalServerError
389
+ }
390
+ }
384
391
385
392
elapsed := float64 (time .Since (start )) / float64 (time .Second )
386
- resSz := float64 (c .Response ().Size )
387
-
388
- p .reqDur .WithLabelValues (status , c .Request ().Method , url ).Observe (elapsed )
389
393
394
+ url := p .RequestCounterURLLabelMappingFunc (c )
390
395
if len (p .URLLabelFromContext ) > 0 {
391
396
u := c .Get (p .URLLabelFromContext )
392
397
if u == nil {
@@ -395,11 +400,15 @@ func (p *Prometheus) HandlerFunc(next echo.HandlerFunc) echo.HandlerFunc {
395
400
url = u .(string )
396
401
}
397
402
398
- p .reqCnt .WithLabelValues (status , c .Request ().Method , p .RequestCounterHostLabelMappingFunc (c ), url ).Inc ()
399
- p .reqSz .WithLabelValues (status , c .Request ().Method , url ).Observe (float64 (reqSz ))
400
- p .resSz .WithLabelValues (status , c .Request ().Method , url ).Observe (resSz )
403
+ statusStr := strconv .Itoa (status )
404
+ p .reqDur .WithLabelValues (statusStr , c .Request ().Method , url ).Observe (elapsed )
405
+ p .reqCnt .WithLabelValues (statusStr , c .Request ().Method , p .RequestCounterHostLabelMappingFunc (c ), url ).Inc ()
406
+ p .reqSz .WithLabelValues (statusStr , c .Request ().Method , url ).Observe (float64 (reqSz ))
407
+
408
+ resSz := float64 (c .Response ().Size )
409
+ p .resSz .WithLabelValues (statusStr , c .Request ().Method , url ).Observe (resSz )
401
410
402
- return
411
+ return err
403
412
}
404
413
}
405
414
0 commit comments