-
Notifications
You must be signed in to change notification settings - Fork 75
/
zap.go
201 lines (180 loc) · 5.88 KB
/
zap.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
// Package ginzap provides log handling using zap package.
// Code structure based on ginrus package.
package ginzap
import (
"net"
"net/http"
"net/http/httputil"
"os"
"regexp"
"runtime/debug"
"strings"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Fn is a function to get zap fields from gin.Context
type Fn func(c *gin.Context) []zapcore.Field
// Skipper is a function to skip logs based on provided Context
type Skipper func(c *gin.Context) bool
// ZapLogger is the minimal logger interface compatible with zap.Logger
type ZapLogger interface {
Info(msg string, fields ...zap.Field)
Error(msg string, fields ...zap.Field)
}
// Config is config setting for Ginzap
type Config struct {
TimeFormat string
UTC bool
SkipPaths []string
SkipPathRegexps []*regexp.Regexp
Context Fn
DefaultLevel zapcore.Level
// skip is a Skipper that indicates which logs should not be written.
// Optional.
Skipper Skipper
}
// Ginzap returns a gin.HandlerFunc (middleware) that logs requests using uber-go/zap.
//
// Requests with errors are logged using zap.Error().
// Requests without errors are logged using zap.Info().
//
// It receives:
// 1. A time package format string (e.g. time.RFC3339).
// 2. A boolean stating whether to use UTC time zone or local.
func Ginzap(logger ZapLogger, timeFormat string, utc bool) gin.HandlerFunc {
return GinzapWithConfig(logger, &Config{TimeFormat: timeFormat, UTC: utc, DefaultLevel: zapcore.InfoLevel})
}
// GinzapWithConfig returns a gin.HandlerFunc (middleware) that logs requests using uber-go/zap.
//
// Requests with errors are logged using zap.Error().
// Requests without errors are logged using zap.Info().
//
// It receives a Config struct and a ZapLogger.
// The Config struct allows you to configure the logging format, the time format, and the UTC time zone.
// The ZapLogger is the minimal logger interface compatible with zap.Logger.
func GinzapWithConfig(logger ZapLogger, conf *Config) gin.HandlerFunc {
skipPaths := make(map[string]bool, len(conf.SkipPaths))
for _, path := range conf.SkipPaths {
skipPaths[path] = true
}
return func(c *gin.Context) {
start := time.Now()
// some evil middlewares modify this values
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
c.Next()
track := true
if _, ok := skipPaths[path]; ok || (conf.Skipper != nil && conf.Skipper(c)) {
track = false
}
if track && len(conf.SkipPathRegexps) > 0 {
for _, reg := range conf.SkipPathRegexps {
if !reg.MatchString(path) {
continue
}
track = false
break
}
}
if track {
end := time.Now()
latency := end.Sub(start)
if conf.UTC {
end = end.UTC()
}
fields := []zapcore.Field{
zap.Int("status", c.Writer.Status()),
zap.String("method", c.Request.Method),
zap.String("path", path),
zap.String("query", query),
zap.String("ip", c.ClientIP()),
zap.String("user-agent", c.Request.UserAgent()),
zap.Duration("latency", latency),
}
if conf.TimeFormat != "" {
fields = append(fields, zap.String("time", end.Format(conf.TimeFormat)))
}
if conf.Context != nil {
fields = append(fields, conf.Context(c)...)
}
if len(c.Errors) > 0 {
// Append error field if this is an erroneous request.
for _, e := range c.Errors.Errors() {
logger.Error(e, fields...)
}
} else {
if zl, ok := logger.(*zap.Logger); ok {
zl.Log(conf.DefaultLevel, path, fields...)
} else if conf.DefaultLevel == zapcore.InfoLevel {
logger.Info(path, fields...)
} else {
logger.Error(path, fields...)
}
}
}
}
}
func defaultHandleRecovery(c *gin.Context, err interface{}) {
c.AbortWithStatus(http.StatusInternalServerError)
}
// RecoveryWithZap returns a gin.HandlerFunc (middleware)
// that recovers from any panics and logs requests using uber-go/zap.
// All errors are logged using zap.Error().
// stack means whether output the stack info.
// The stack info is easy to find where the error occurs but the stack info is too large.
func RecoveryWithZap(logger ZapLogger, stack bool) gin.HandlerFunc {
return CustomRecoveryWithZap(logger, stack, defaultHandleRecovery)
}
// CustomRecoveryWithZap returns a gin.HandlerFunc (middleware) with a custom recovery handler
// that recovers from any panics and logs requests using uber-go/zap.
// All errors are logged using zap.Error().
// stack means whether output the stack info.
// The stack info is easy to find where the error occurs but the stack info is too large.
func CustomRecoveryWithZap(logger ZapLogger, stack bool, recovery gin.RecoveryFunc) gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
// Check for a broken connection, as it is not really a
// condition that warrants a panic stack trace.
var brokenPipe bool
if ne, ok := err.(*net.OpError); ok {
if se, ok := ne.Err.(*os.SyscallError); ok {
if strings.Contains(strings.ToLower(se.Error()), "broken pipe") ||
strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
brokenPipe = true
}
}
}
httpRequest, _ := httputil.DumpRequest(c.Request, false)
if brokenPipe {
logger.Error(c.Request.URL.Path,
zap.Any("error", err),
zap.String("request", string(httpRequest)),
)
// If the connection is dead, we can't write a status to it.
c.Error(err.(error)) //nolint: errcheck
c.Abort()
return
}
if stack {
logger.Error("[Recovery from panic]",
zap.Time("time", time.Now()),
zap.Any("error", err),
zap.String("request", string(httpRequest)),
zap.String("stack", string(debug.Stack())),
)
} else {
logger.Error("[Recovery from panic]",
zap.Time("time", time.Now()),
zap.Any("error", err),
zap.String("request", string(httpRequest)),
)
}
recovery(c, err)
}
}()
c.Next()
}
}