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/echo"
|
|
|
|
"github.com/labstack/gommon/color"
|
|
|
|
)
|
|
|
|
|
2016-02-18 07:01:47 +02:00
|
|
|
type (
|
2016-03-14 22:55:38 +02:00
|
|
|
LoggerConfig struct {
|
2015-04-21 08:24:57 +02:00
|
|
|
}
|
2016-02-18 07:01:47 +02:00
|
|
|
)
|
|
|
|
|
2016-03-14 22:55:38 +02:00
|
|
|
var (
|
|
|
|
DefaultLoggerConfig = LoggerConfig{}
|
|
|
|
)
|
|
|
|
|
|
|
|
func Logger() echo.MiddlewareFunc {
|
|
|
|
return LoggerFromConfig(DefaultLoggerConfig)
|
|
|
|
}
|
|
|
|
|
|
|
|
func LoggerFromConfig(config LoggerConfig) echo.MiddlewareFunc {
|
2016-02-19 08:50:40 +02:00
|
|
|
return func(next echo.Handler) echo.Handler {
|
2016-02-18 07:49:31 +02:00
|
|
|
return echo.HandlerFunc(func(c echo.Context) error {
|
|
|
|
req := c.Request()
|
|
|
|
res := c.Response()
|
|
|
|
logger := c.Logger()
|
|
|
|
|
|
|
|
remoteAddr := req.RemoteAddress()
|
|
|
|
if ip := req.Header().Get(echo.XRealIP); ip != "" {
|
|
|
|
remoteAddr = ip
|
|
|
|
} else if ip = req.Header().Get(echo.XForwardedFor); ip != "" {
|
|
|
|
remoteAddr = ip
|
|
|
|
} else {
|
|
|
|
remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
|
|
|
|
}
|
|
|
|
|
|
|
|
start := time.Now()
|
2016-02-19 08:50:40 +02:00
|
|
|
if err := next.Handle(c); err != nil {
|
2016-02-18 07:49:31 +02:00
|
|
|
c.Error(err)
|
|
|
|
}
|
|
|
|
stop := time.Now()
|
|
|
|
method := req.Method()
|
|
|
|
path := req.URL().Path()
|
|
|
|
if path == "" {
|
|
|
|
path = "/"
|
|
|
|
}
|
|
|
|
size := res.Size()
|
|
|
|
|
|
|
|
n := res.Status()
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2016-03-06 19:52:32 +02:00
|
|
|
logger.Printf("%s %s %s %s %s %d", remoteAddr, method, path, code, stop.Sub(start), size)
|
2016-02-18 07:49:31 +02:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|
2015-04-21 08:24:57 +02:00
|
|
|
}
|