2015-03-01 09:45:13 -08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
2015-03-27 14:21:30 -07:00
|
|
|
"github.com/labstack/echo"
|
2015-03-12 15:46:02 -07:00
|
|
|
"github.com/labstack/gommon/color"
|
2015-03-31 12:35:53 +09:00
|
|
|
"github.com/mattn/go-colorable"
|
2015-03-01 09:45:13 -08:00
|
|
|
)
|
|
|
|
|
2015-03-27 14:21:30 -07:00
|
|
|
func Logger(h echo.HandlerFunc) echo.HandlerFunc {
|
2015-03-31 12:35:53 +09:00
|
|
|
log.SetOutput(colorable.NewColorableStdout())
|
2015-03-27 14:21:30 -07:00
|
|
|
return echo.HandlerFunc(func(c *echo.Context) {
|
2015-03-01 09:45:13 -08:00
|
|
|
start := time.Now()
|
2015-03-25 08:50:24 -07:00
|
|
|
h(c)
|
2015-03-01 09:45:13 -08:00
|
|
|
end := time.Now()
|
2015-03-12 20:50:33 -07:00
|
|
|
col := color.Green
|
2015-03-01 09:45:13 -08:00
|
|
|
m := c.Request.Method
|
|
|
|
p := c.Request.URL.Path
|
|
|
|
s := c.Response.Status()
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case s >= 500:
|
2015-03-12 20:50:33 -07:00
|
|
|
col = color.Red
|
2015-03-01 09:45:13 -08:00
|
|
|
case s >= 400:
|
2015-03-12 20:50:33 -07:00
|
|
|
col = color.Yellow
|
2015-03-01 09:45:13 -08:00
|
|
|
case s >= 300:
|
2015-03-12 20:50:33 -07:00
|
|
|
col = color.Cyan
|
2015-03-01 09:45:13 -08:00
|
|
|
}
|
|
|
|
|
2015-03-12 20:50:33 -07:00
|
|
|
log.Printf("%s %s %s %s", m, p, col(s), end.Sub(start))
|
2015-03-25 08:50:24 -07:00
|
|
|
})
|
2015-03-01 09:45:13 -08:00
|
|
|
}
|