forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
169 lines (158 loc) · 4.19 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package middleware
import (
"bytes"
"io"
"net"
"os"
"strconv"
"sync"
"time"
"github.com/labstack/echo"
"github.com/labstack/gommon/color"
isatty "github.com/mattn/go-isatty"
"github.com/valyala/fasttemplate"
)
type (
// LoggerConfig defines the config for logger middleware.
LoggerConfig struct {
// Log format which can be constructed using the following tags:
//
// - time_rfc3339
// - id (Request ID - Not implemented)
// - remote_ip
// - uri
// - host
// - method
// - path
// - referer
// - user_agent
// - status
// - latency (In microseconds)
// - latency_human (Human readable)
// - rx_bytes (Bytes received)
// - tx_bytes (Bytes sent)
//
// 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
template *fasttemplate.Template
color *color.Color
bufferPool sync.Pool
}
)
var (
// DefaultLoggerConfig is the default logger middleware config.
DefaultLoggerConfig = LoggerConfig{
Format: `{"time":"${time_rfc3339}","remote_ip":"${remote_ip}",` +
`"method":"${method}","uri":"${uri}","status":${status}, "latency":${latency},` +
`"latency_human":"${latency_human}","rx_bytes":${rx_bytes},` +
`"tx_bytes":${tx_bytes}}` + "\n",
color: color.New(),
Output: os.Stdout,
}
)
// Logger returns a middleware that logs HTTP requests.
func Logger() echo.MiddlewareFunc {
return LoggerWithConfig(DefaultLoggerConfig)
}
// LoggerWithConfig returns a logger middleware from config.
// See: `Logger()`.
func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc {
// Defaults
if config.Format == "" {
config.Format = DefaultLoggerConfig.Format
}
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.bufferPool = 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) {
req := c.Request()
res := c.Response()
start := time.Now()
if err = next(c); err != nil {
c.Error(err)
}
stop := time.Now()
buf := config.bufferPool.Get().(*bytes.Buffer)
buf.Reset()
defer config.bufferPool.Put(buf)
_, 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)))
case "remote_ip":
ra := req.RemoteAddress()
if ip := req.Header().Get(echo.HeaderXRealIP); ip != "" {
ra = ip
} else if ip = req.Header().Get(echo.HeaderXForwardedFor); ip != "" {
ra = ip
} else {
ra, _, _ = net.SplitHostPort(ra)
}
return w.Write([]byte(ra))
case "host":
return w.Write([]byte(req.Host()))
case "uri":
return w.Write([]byte(req.URI()))
case "method":
return w.Write([]byte(req.Method()))
case "path":
p := req.URL().Path()
if p == "" {
p = "/"
}
return w.Write([]byte(p))
case "referer":
return w.Write([]byte(req.Referer()))
case "user_agent":
return w.Write([]byte(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))
case "latency":
l := stop.Sub(start).Nanoseconds() / 1000
return w.Write([]byte(strconv.FormatInt(l, 10)))
case "latency_human":
return w.Write([]byte(stop.Sub(start).String()))
case "rx_bytes":
b := req.Header().Get(echo.HeaderContentLength)
if b == "" {
b = "0"
}
return w.Write([]byte(b))
case "tx_bytes":
return w.Write([]byte(strconv.FormatInt(res.Size(), 10)))
}
return 0, nil
})
if err == nil {
config.Output.Write(buf.Bytes())
}
return
}
}
}