1
0
mirror of https://github.com/labstack/echo.git synced 2025-07-15 01:34:53 +02:00

Logger middleware interface (#820)

* Modified logger format

Signed-off-by: Vishal Rana <vr@labstack.com>

* Logger middleware via struct

Signed-off-by: Vishal Rana <vr@labstack.com>

* Fixed time format

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2017-01-11 20:07:51 -08:00
committed by GitHub
parent a09afe2c97
commit ce6b1e20db
4 changed files with 144 additions and 100 deletions

View File

@ -1,18 +1,16 @@
package middleware
import (
"bytes"
"io"
"os"
"strconv"
"strings"
"sync"
"time"
"encoding/json"
"github.com/labstack/echo"
"github.com/labstack/gommon/color"
isatty "github.com/mattn/go-isatty"
"github.com/valyala/fasttemplate"
"github.com/labstack/echo/db"
)
type (
@ -21,8 +19,9 @@ type (
// Skipper defines a function to skip middleware.
Skipper Skipper
// Log format which can be constructed using the following tags:
// Availabe logger fields:
//
// - time_unix
// - time_rfc3339
// - id (Request ID - Not implemented)
// - remote_ip
@ -33,39 +32,51 @@ type (
// - referer
// - user_agent
// - status
// - latency (In microseconds)
// - latency (In nanosecond)
// - latency_human (Human readable)
// - bytes_in (Bytes received)
// - bytes_out (Bytes sent)
// - header:<name>
// - query:<name>
// - form:<name>
//
// Example "${remote_ip} ${status}"
//
// Optional. Default value DefaultLoggerConfig.Format.
Format string `json:"format"`
// Output is a writer where logs are written.
// Optional. Default value os.Stdout.
Output io.Writer
// Optional. Default value DefaultLoggerConfig.Fields.
Fields []string `json:"fields"`
template *fasttemplate.Template
color *color.Color
pool sync.Pool
// Output is where logs are written.
// Optional. Default value &Stream{os.Stdout}.
Output db.Logger
}
// Stream implements `db.Logger`.
Stream struct {
io.Writer
}
)
// LogRequest encodes `db.Request` into a stream.
func (s *Stream) Log(r *db.Request) error {
enc := json.NewEncoder(s)
return enc.Encode(r)
}
var (
// DefaultLoggerConfig is the default Logger middleware config.
DefaultLoggerConfig = LoggerConfig{
Skipper: defaultSkipper,
Format: `{"time":"${time_rfc3339}","remote_ip":"${remote_ip}","host":"${host}",` +
`"method":"${method}","uri":"${uri}","status":${status}, "latency":${latency},` +
`"latency_human":"${latency_human}","bytes_in":${bytes_in},` +
`"bytes_out":${bytes_out}}` + "\n",
Output: os.Stdout,
color: color.New(),
Fields: []string{
"time",
"remote_ip",
"host",
"method",
"uri",
"status",
"latency",
"latency_human",
"bytes_in",
"bytes_out",
},
Output: &Stream{os.Stdout},
}
)
@ -81,24 +92,13 @@ func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc {
if config.Skipper == nil {
config.Skipper = DefaultLoggerConfig.Skipper
}
if config.Format == "" {
config.Format = DefaultLoggerConfig.Format
if len(config.Fields) == 0 {
config.Fields = DefaultLoggerConfig.Fields
}
if config.Output == nil {
config.Output = DefaultLoggerConfig.Output
}
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()
}
config.pool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 256))
},
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
if config.Skipper(c) {
@ -112,74 +112,66 @@ func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc {
c.Error(err)
}
stop := time.Now()
buf := config.pool.Get().(*bytes.Buffer)
buf.Reset()
defer config.pool.Put(buf)
request := &db.Request{
Header: make(map[string]string),
Query: make(map[string]string),
Form: make(map[string]string),
}
_, err = config.template.ExecuteFunc(buf, func(w io.Writer, tag string) (int, error) {
switch tag {
case "time_rfc3339":
return w.Write([]byte(time.Now().Format(time.RFC3339)))
for _, f := range config.Fields {
switch f {
case "time":
request.Time = time.Now()
case "remote_ip":
ra := c.RealIP()
return w.Write([]byte(ra))
request.RemoteIP = c.RealIP()
case "host":
return w.Write([]byte(req.Host))
request.Host = req.Host
case "uri":
return w.Write([]byte(req.RequestURI))
request.URI = req.RequestURI
case "method":
return w.Write([]byte(req.Method))
request.Method = req.Method
case "path":
p := req.URL.Path
if p == "" {
p = "/"
}
return w.Write([]byte(p))
request.Path = p
case "referer":
return w.Write([]byte(req.Referer()))
request.Referer = req.Referer()
case "user_agent":
return w.Write([]byte(req.UserAgent()))
request.UserAgent = req.UserAgent()
case "status":
n := res.Status
s := config.color.Green(n)
switch {
case n >= 500:
s = config.color.Red(n)
case n >= 400:
s = config.color.Yellow(n)
case n >= 300:
s = config.color.Cyan(n)
}
return w.Write([]byte(s))
request.Status = res.Status
case "latency":
l := stop.Sub(start).Nanoseconds() / 1000
return w.Write([]byte(strconv.FormatInt(l, 10)))
request.Latency = stop.Sub(start)
case "latency_human":
return w.Write([]byte(stop.Sub(start).String()))
request.LatencyHuman = stop.Sub(start).String()
case "bytes_in":
b := req.Header.Get(echo.HeaderContentLength)
if b == "" {
b = "0"
cl := req.Header.Get(echo.HeaderContentLength)
if cl == "" {
cl = "0"
}
return w.Write([]byte(b))
l, _ := strconv.ParseInt(cl, 10, 64)
request.BytesIn = l
case "bytes_out":
return w.Write([]byte(strconv.FormatInt(res.Size, 10)))
request.BytesOut = res.Size
default:
switch {
case strings.HasPrefix(tag, "header:"):
return buf.Write([]byte(c.Request().Header.Get(tag[7:])))
case strings.HasPrefix(tag, "query:"):
return buf.Write([]byte(c.QueryParam(tag[6:])))
case strings.HasPrefix(tag, "form:"):
return buf.Write([]byte(c.FormValue(tag[5:])))
case strings.HasPrefix(f, "header:"):
k := f[7:]
request.Header[k] = c.Request().Header.Get(k)
case strings.HasPrefix(f, "query:"):
k := f[6:]
request.Query[k] = c.QueryParam(k)
case strings.HasPrefix(f, "form:"):
k := f[5:]
request.Form[k] = c.FormValue(k)
}
}
return 0, nil
})
if err == nil {
config.Output.Write(buf.Bytes())
}
return
// Write
return config.Output.Log(request)
}
}
}