2015-04-23 10:44:50 +02:00
|
|
|
package middleware
|
2015-04-21 08:24:57 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
2015-09-18 01:17:54 +02:00
|
|
|
"net"
|
2015-04-21 08:24:57 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
"github.com/labstack/gommon/color"
|
|
|
|
)
|
|
|
|
|
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-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
|
|
|
|
2015-09-18 01:17:54 +02:00
|
|
|
log.Printf("%s %s %s %s %s %d", 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
|
|
|
}
|
|
|
|
}
|