2015-04-23 10:44:50 +02:00
|
|
|
package middleware
|
2015-04-21 08:24:57 +02:00
|
|
|
|
|
|
|
import (
|
2015-09-18 01:17:54 +02:00
|
|
|
"net"
|
2015-04-21 08:24:57 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/labstack/gommon/color"
|
2016-03-11 12:06:06 +02:00
|
|
|
echo "gopkg.in/labstack/echo.v1"
|
2015-04-21 08:24:57 +02:00
|
|
|
)
|
|
|
|
|
2016-01-30 20:05:17 +02:00
|
|
|
const (
|
|
|
|
format = "%s %s %s %s %s %d"
|
|
|
|
)
|
2016-01-29 14:06:20 +02:00
|
|
|
|
|
|
|
// Logger returns a Middleware that logs requests.
|
2015-05-15 21:29:14 +02:00
|
|
|
func Logger() echo.MiddlewareFunc {
|
|
|
|
return func(h echo.HandlerFunc) echo.HandlerFunc {
|
2015-05-20 23:38:51 +02:00
|
|
|
return func(c *echo.Context) error {
|
2015-09-18 01:17:54 +02:00
|
|
|
req := c.Request()
|
|
|
|
res := c.Response()
|
2015-12-01 21:22:45 +02:00
|
|
|
logger := c.Echo().Logger()
|
2015-09-18 01:17:54 +02:00
|
|
|
|
2015-10-22 00:11:01 +02:00
|
|
|
remoteAddr := req.RemoteAddr
|
2015-09-18 01:17:54 +02: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 22:39:51 +02:00
|
|
|
} else {
|
|
|
|
remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
|
2015-09-18 01:17:54 +02:00
|
|
|
}
|
|
|
|
|
2015-05-15 21:29:14 +02:00
|
|
|
start := time.Now()
|
2015-05-20 23:38:51 +02:00
|
|
|
if err := h(c); err != nil {
|
|
|
|
c.Error(err)
|
2015-05-15 21:29:14 +02:00
|
|
|
}
|
2015-05-30 19:54:55 +02:00
|
|
|
stop := time.Now()
|
2015-09-18 01:17:54 +02:00
|
|
|
method := req.Method
|
|
|
|
path := req.URL.Path
|
2015-05-15 21:29:14 +02:00
|
|
|
if path == "" {
|
|
|
|
path = "/"
|
|
|
|
}
|
2015-09-18 01:17:54 +02:00
|
|
|
size := res.Size()
|
2015-04-21 08:24:57 +02:00
|
|
|
|
2015-09-18 01:17:54 +02:00
|
|
|
n := res.Status()
|
2015-05-15 21:29:14 +02: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-21 08:24:57 +02:00
|
|
|
|
2016-03-06 19:10:42 +02:00
|
|
|
logger.Printf(format, remoteAddr, method, path, code, stop.Sub(start), size)
|
2015-05-15 21:29:14 +02:00
|
|
|
return nil
|
|
|
|
}
|
2015-04-21 08:24:57 +02:00
|
|
|
}
|
|
|
|
}
|