-
Notifications
You must be signed in to change notification settings - Fork 5
/
logger.go
338 lines (319 loc) · 8.45 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// MIT License
// Copyright (c) 2020 Tree Xie
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package middleware
import (
"fmt"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"unsafe"
"github.com/vicanso/elton"
)
const (
host = "host"
method = "method"
path = "path"
proto = "proto"
query = "query"
remote = "remote"
realIP = "real-ip"
clientIP = "client-ip"
scheme = "scheme"
uri = "uri"
referer = "referer"
userAgent = "userAgent"
when = "when"
whenISO = "when-iso"
whenUTCISO = "when-utc-iso"
whenUnix = "when-unix"
whenISOMs = "when-iso-ms"
whenUTCISOMs = "when-utc-iso-ms"
size = "size"
sizeHuman = "size-human"
status = "status"
latency = "latency"
latencyMs = "latency-ms"
cookie = "cookie"
payloadSize = "payload-size"
payloadSizeHuman = "payload-size-human"
requestHeader = "requestHeader"
responseHeader = "responseHeader"
ctx = "context"
httpProto = "HTTP"
httpsProto = "HTTPS"
// get from env
env = "env"
kbytes = 1024
mbytes = 1024 * 1024
// LoggerCommon combined log format
LoggerCombined = `{remote} {when-iso} "{method} {uri} {proto}" {status} {size-human} "{referer}" "{userAgent}"`
// LoggerCommon common log format
LoggerCommon = `{remote} {when-iso} "{method} {uri} {proto}" {status} {size-human}`
// LoggerShort short log format
LoggerShort = `{remote} {method} {uri} {proto} {status} {size-human} - {latency-ms} ms`
// LoggerTiny tiny log format
LoggerTiny = `{method} {url} {status} {size-human} - {latency-ms} ms`
)
type (
// LoggerTag logger tag
LoggerTag struct {
category string
data string
}
// OnLog on log function
OnLog func(string, *elton.Context)
// LoggerConfig logger config
LoggerConfig struct {
// DefaultFill default fill for empty value
DefaultFill string
Format string
OnLog OnLog
Skipper elton.Skipper
}
)
// byteSliceToString converts a []byte to string without a heap allocation.
func byteSliceToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func cutLog(str string) string {
l := len(str)
if l == 0 {
return str
}
ch := str[l-1]
if ch == '0' || ch == '.' {
return cutLog(str[0 : l-1])
}
return str
}
// getHumanReadableSize get the size for human
func getHumanReadableSize(size int) string {
if size < kbytes {
return fmt.Sprintf("%dB", size)
}
fSize := float64(size)
if size < mbytes {
s := cutLog(fmt.Sprintf("%.2f", (fSize / kbytes)))
return s + "KB"
}
s := cutLog(fmt.Sprintf("%.2f", (fSize / mbytes)))
return s + "MB"
}
// getTimeConsuming 获取使用耗时(ms)
func getTimeConsuming(startedAt time.Time) int {
v := startedAt.UnixNano()
now := time.Now().UnixNano()
return int((now - v) / 1000000)
}
// parseLoggerTags 转换日志的输出格式
func parseLoggerTags(desc []byte) []*LoggerTag {
reg := regexp.MustCompile(`\{[\S]+?\}`)
index := 0
arr := make([]*LoggerTag, 0)
fillCategory := "fill"
for {
result := reg.FindIndex(desc[index:])
if result == nil {
break
}
start := index + result[0]
end := index + result[1]
if start != index {
arr = append(arr, &LoggerTag{
category: fillCategory,
data: byteSliceToString(desc[index:start]),
})
}
k := desc[start+1 : end-1]
switch k[0] {
case byte('~'):
arr = append(arr, &LoggerTag{
category: cookie,
data: byteSliceToString(k[1:]),
})
case byte('>'):
arr = append(arr, &LoggerTag{
category: requestHeader,
data: byteSliceToString(k[1:]),
})
case byte('<'):
arr = append(arr, &LoggerTag{
category: responseHeader,
data: byteSliceToString(k[1:]),
})
case byte(':'):
arr = append(arr, &LoggerTag{
category: ctx,
data: byteSliceToString(k[1:]),
})
case byte('$'):
arr = append(arr, &LoggerTag{
category: env,
data: os.Getenv(string(k[1:])),
})
default:
arr = append(arr, &LoggerTag{
category: byteSliceToString(k),
data: "",
})
}
index = result[1] + index
}
if index < len(desc) {
arr = append(arr, &LoggerTag{
category: fillCategory,
data: byteSliceToString(desc[index:]),
})
}
return arr
}
// formatLog 格式化访问日志信息
func formatLog(c *elton.Context, tags []*LoggerTag, startedAt time.Time, defaultFill string) string {
fn := func(tag *LoggerTag) string {
switch tag.category {
case host:
return c.Request.Host
case method:
return c.Request.Method
case path:
p := c.Request.URL.Path
if p == "" {
p = "/"
}
return p
case proto:
return c.Request.Proto
case query:
return c.Request.URL.RawQuery
case remote:
return c.Request.RemoteAddr
case realIP:
return c.RealIP()
case clientIP:
return c.ClientIP()
case scheme:
if c.Request.TLS != nil {
return httpsProto
}
return httpProto
case uri:
return c.Request.RequestURI
case cookie:
cookie, err := c.Cookie(tag.data)
if err != nil {
return ""
}
return cookie.Value
case requestHeader:
return c.Request.Header.Get(tag.data)
case responseHeader:
return c.GetHeader(tag.data)
case ctx:
return c.GetString(tag.data)
case referer:
return c.Request.Referer()
case userAgent:
return c.Request.UserAgent()
case when:
return time.Now().Format(time.RFC1123Z)
case whenISO:
return time.Now().Format(time.RFC3339)
case whenUTCISO:
return time.Now().UTC().Format("2006-01-02T15:04:05Z")
case whenISOMs:
return time.Now().Format("2006-01-02T15:04:05.999Z07:00")
case whenUTCISOMs:
return time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
case whenUnix:
return strconv.FormatInt(time.Now().Unix(), 10)
case status:
statusCode := c.StatusCode
if statusCode == 0 {
statusCode = http.StatusOK
}
return strconv.Itoa(statusCode)
case payloadSize:
return strconv.Itoa(len(c.RequestBody))
case payloadSizeHuman:
return getHumanReadableSize(len(c.RequestBody))
case size:
if c.IsReaderBody() {
return "-"
}
bodyBuf := c.BodyBuffer
if bodyBuf == nil {
return "0"
}
return strconv.Itoa(bodyBuf.Len())
case sizeHuman:
if c.IsReaderBody() {
return "-"
}
bodyBuf := c.BodyBuffer
if bodyBuf == nil {
return "0B"
}
return getHumanReadableSize(bodyBuf.Len())
case latency:
return time.Since(startedAt).String()
case latencyMs:
ms := getTimeConsuming(startedAt)
return strconv.Itoa(ms)
default:
return tag.data
}
}
arr := make([]string, 0, len(tags))
for _, tag := range tags {
v := fn(tag)
if v == "" {
v = defaultFill
}
arr = append(arr, v)
}
return strings.Join(arr, "")
}
// NewLogger returns a new logger middleware, it can log the field of query string, header, cookie and context.
// It will throw a panic if the Format is empty.
// It will throw a panic if the OnLog function is nil.
func NewLogger(config LoggerConfig) elton.Handler {
if config.Format == "" {
panic("logger require format")
}
if config.OnLog == nil {
panic("logger require on log function")
}
tags := parseLoggerTags([]byte(config.Format))
skipper := config.Skipper
if skipper == nil {
skipper = elton.DefaultSkipper
}
return func(c *elton.Context) error {
if skipper(c) {
return c.Next()
}
startedAt := time.Now()
err := c.Next()
str := formatLog(c, tags, startedAt, config.DefaultFill)
config.OnLog(str, c)
return err
}
}