2015-04-23 11:44:50 +03:00
|
|
|
package middleware
|
2015-04-20 23:24:57 -07:00
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
"github.com/labstack/gommon/color"
|
|
|
|
)
|
|
|
|
|
2015-05-15 12:29:14 -07:00
|
|
|
func Logger() echo.MiddlewareFunc {
|
|
|
|
return func(h echo.HandlerFunc) echo.HandlerFunc {
|
2015-05-20 14:38:51 -07:00
|
|
|
return func(c *echo.Context) error {
|
2015-05-15 12:29:14 -07:00
|
|
|
start := time.Now()
|
2015-05-20 14:38:51 -07:00
|
|
|
if err := h(c); err != nil {
|
|
|
|
c.Error(err)
|
2015-05-15 12:29:14 -07:00
|
|
|
}
|
2015-05-30 10:54:55 -07:00
|
|
|
stop := time.Now()
|
2015-05-22 04:40:01 -07:00
|
|
|
method := c.Request().Method
|
|
|
|
path := c.Request().URL.Path
|
2015-05-15 12:29:14 -07:00
|
|
|
if path == "" {
|
|
|
|
path = "/"
|
|
|
|
}
|
2015-05-22 04:40:01 -07:00
|
|
|
size := c.Response().Size()
|
2015-04-20 23:24:57 -07:00
|
|
|
|
2015-05-22 04:40:01 -07:00
|
|
|
n := c.Response().Status()
|
2015-05-15 12:29:14 -07:00
|
|
|
code := color.Green(n)
|
|
|
|
switch {
|
|
|
|
case n >= 500:
|
|
|
|
code = color.Red(n)
|
|
|
|
case n >= 400:
|
|
|
|
code = color.Yellow(n)
|
|
|
|
case n >= 300:
|
|
|
|
code = color.Cyan(n)
|
|
|
|
}
|
2015-04-20 23:24:57 -07:00
|
|
|
|
2015-05-30 10:54:55 -07:00
|
|
|
log.Printf("%s %s %s %s %d", method, path, code, stop.Sub(start), size)
|
2015-05-15 12:29:14 -07:00
|
|
|
return nil
|
|
|
|
}
|
2015-04-20 23:24:57 -07:00
|
|
|
}
|
|
|
|
}
|