2015-04-23 11:44:50 +03:00
|
|
|
package middleware
|
2015-04-20 23:24:57 -07:00
|
|
|
|
|
|
|
import (
|
2015-09-17 19:17:54 -04:00
|
|
|
"net"
|
2015-04-20 23:24:57 -07:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
"github.com/labstack/gommon/color"
|
|
|
|
)
|
|
|
|
|
2016-01-30 10:05:17 -08:00
|
|
|
const (
|
|
|
|
format = "%s %s %s %s %s %d"
|
|
|
|
)
|
2016-01-29 04:06:20 -08:00
|
|
|
|
|
|
|
// Logger returns a Middleware that logs requests.
|
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-09-17 19:17:54 -04:00
|
|
|
req := c.Request()
|
|
|
|
res := c.Response()
|
2015-12-01 11:22:45 -08:00
|
|
|
logger := c.Echo().Logger()
|
2015-09-17 19:17:54 -04:00
|
|
|
|
2015-10-21 15:11:01 -07:00
|
|
|
remoteAddr := req.RemoteAddr
|
2015-09-17 19:17:54 -04:00
|
|
|
if ip := req.Header.Get(echo.XRealIP); ip != "" {
|
|
|
|
remoteAddr = ip
|
|
|
|
} else if ip = req.Header.Get(echo.XForwardedFor); ip != "" {
|
|
|
|
remoteAddr = ip
|
2015-10-21 16:39:51 -04:00
|
|
|
} else {
|
|
|
|
remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
|
2015-09-17 19:17:54 -04:00
|
|
|
}
|
|
|
|
|
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-09-17 19:17:54 -04:00
|
|
|
method := req.Method
|
|
|
|
path := req.URL.Path
|
2015-05-15 12:29:14 -07:00
|
|
|
if path == "" {
|
|
|
|
path = "/"
|
|
|
|
}
|
2015-09-17 19:17:54 -04:00
|
|
|
size := res.Size()
|
2015-04-20 23:24:57 -07:00
|
|
|
|
2015-09-17 19:17:54 -04:00
|
|
|
n := res.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
|
|
|
|
2016-01-30 10:05:17 -08:00
|
|
|
logger.Infof(format, remoteAddr, 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
|
|
|
}
|
|
|
|
}
|