mirror of
https://github.com/labstack/echo.git
synced 2025-01-26 03:20:08 +02:00
Some work on logger middleware
Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
parent
4a86175a32
commit
830b4eff3f
@ -4,24 +4,30 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo"
|
||||
"github.com/labstack/gommon/color"
|
||||
"github.com/mattn/go-isatty"
|
||||
"github.com/valyala/fasttemplate"
|
||||
)
|
||||
|
||||
type (
|
||||
LoggerConfig struct {
|
||||
Format string
|
||||
Output io.Writer
|
||||
template *fasttemplate.Template
|
||||
color *color.Color
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultLoggerConfig = LoggerConfig{
|
||||
Format: "time=${time_rfc3339}, remote_ip=${remote_ip}, method=${method}, path=${path}, status=${status}, response_time=${response_time}, size=${size}\n",
|
||||
color: color.New(),
|
||||
Output: os.Stdout,
|
||||
}
|
||||
)
|
||||
|
||||
@ -31,13 +37,16 @@ func Logger() echo.MiddlewareFunc {
|
||||
|
||||
func LoggerFromConfig(config LoggerConfig) echo.MiddlewareFunc {
|
||||
config.template = fasttemplate.New(config.Format, "${", "}")
|
||||
config.color = color.New()
|
||||
if w, ok := config.Output.(*os.File); ok && !isatty.IsTerminal(w.Fd()) {
|
||||
config.color.Disable()
|
||||
}
|
||||
|
||||
return func(next echo.Handler) echo.Handler {
|
||||
return echo.HandlerFunc(func(c echo.Context) (err error) {
|
||||
req := c.Request()
|
||||
res := c.Response()
|
||||
remoteAddr := req.RemoteAddress()
|
||||
output := c.Logger().Output()
|
||||
|
||||
if ip := req.Header().Get(echo.XRealIP); ip != "" {
|
||||
remoteAddr = ip
|
||||
@ -71,7 +80,7 @@ func LoggerFromConfig(config LoggerConfig) echo.MiddlewareFunc {
|
||||
status = color.Cyan(n)
|
||||
}
|
||||
|
||||
_, err = config.template.ExecuteFunc(output, func(w io.Writer, tag string) (int, error) {
|
||||
_, err = config.template.ExecuteFunc(config.Output, func(w io.Writer, tag string) (int, error) {
|
||||
switch tag {
|
||||
case "time_rfc3339":
|
||||
return w.Write([]byte(time.Now().Format(time.RFC3339)))
|
||||
|
@ -65,17 +65,17 @@ func TestLoggerIPAddress(t *testing.T) {
|
||||
// With X-Real-IP
|
||||
req.Header().Add(echo.XRealIP, ip)
|
||||
h.Handle(c)
|
||||
assert.Contains(t, buf.String(), ip)
|
||||
assert.Contains(t, ip, buf.String())
|
||||
|
||||
// With X-Forwarded-For
|
||||
buf.Reset()
|
||||
req.Header().Del(echo.XRealIP)
|
||||
req.Header().Add(echo.XForwardedFor, ip)
|
||||
h.Handle(c)
|
||||
assert.Contains(t, buf.String(), ip)
|
||||
assert.Contains(t, ip, buf.String())
|
||||
|
||||
// with req.RemoteAddr
|
||||
buf.Reset()
|
||||
h.Handle(c)
|
||||
assert.Contains(t, buf.String(), ip)
|
||||
assert.Contains(t, ip, buf.String())
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user