-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
146 lines (132 loc) · 3.78 KB
/
log.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
package ecolog
import (
"bytes"
"fmt"
"io"
"strings"
"sync"
"time"
"github.com/labstack/echo/v4"
"github.com/valyala/fasttemplate"
)
// Almost codes are copied from official logging middleware.
// See also: https://github.com/labstack/echo/blob/abecadc/middleware/logger.go
type AppLoggerConfig struct {
// Tags to construct the logger format.
// - time_rfc3339
// - time_rfc3339_nano
// - time_custom
// - level
// - prefix
// - long_file
// - short_file
// - line
// - id (Request ID)
// - remote_ip
// - host
// - method
// - uri
// - path
// - protocol
// - route
// - referer
// - user_agent
// - header:<NAME>
// - query:<NAME>
// - form:<NAME>
//
// Example "${remote_ip} ${status}"
//
// Optional. Default value DefaultLoggerConfig.Format.
Format string `yaml:"format"`
// Optional. Default value DefaultLoggerConfig.CustomTimeFormat.
CustomTimeFormat string `yaml:"custom_time_format"`
pool *sync.Pool
template *fasttemplate.Template
}
var (
// DefaultLoggerConfig is the default Logger middleware config.
DefaultLoggerConfig = AppLoggerConfig{
Format: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}",` +
`"host":"${host}","method":"${method}","uri":"${uri}","user_agent":"${user_agent}"}`,
CustomTimeFormat: "2006-01-02 15:04:05.00000",
}
)
// Logger returns a middleware that outputs application logs with request info.
func AppLogger() echo.MiddlewareFunc {
return AppLoggerWithConfig(DefaultLoggerConfig)
}
// AppLoggerWithConfig returns a AppLogger middleware with config.
// See: `AppLogger()`.
func AppLoggerWithConfig(config AppLoggerConfig) echo.MiddlewareFunc {
if config.Format == "" {
config.Format = DefaultLoggerConfig.Format
}
config.template = fasttemplate.New(config.Format, "${", "}")
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) {
req := c.Request()
res := c.Response()
buf := config.pool.Get().(*bytes.Buffer)
buf.Reset()
defer config.pool.Put(buf)
if _, err = config.template.ExecuteFunc(buf, func(w io.Writer, tag string) (int, error) {
switch tag {
case "time_custom":
return buf.WriteString(time.Now().Format(config.CustomTimeFormat))
case "id":
return buf.WriteString(res.Header().Get(echo.HeaderXRequestID))
case "remote_ip":
return buf.WriteString(c.RealIP())
case "host":
return buf.WriteString(req.Host)
case "uri":
return buf.WriteString(req.RequestURI)
case "method":
return buf.WriteString(req.Method)
case "path":
p := req.URL.Path
if p == "" {
p = "/"
}
return buf.WriteString(p)
case "route":
return buf.WriteString(c.Path())
case "protocol":
return buf.WriteString(req.Proto)
case "referer":
return buf.WriteString(req.Referer())
case "user_agent":
return buf.WriteString(req.UserAgent())
default:
switch {
case strings.HasPrefix(tag, "context:"):
return buf.WriteString(fmt.Sprintf("%s", c.Get(tag[8:])))
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(tag, "cookie:"):
cookie, err := c.Cookie(tag[7:])
if err == nil {
return buf.Write([]byte(cookie.Value))
}
}
// Undo unsupported tags because they are handled by gommon.
return buf.WriteString(fmt.Sprintf("${%s}", tag))
}
}); err != nil {
return
}
c.Logger().SetHeader(string(buf.Bytes()))
return next(c)
}
}
}