-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
290 lines (239 loc) · 6.55 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
package log
import (
stdlog "log"
"os"
"time"
"github.com/TheZeroSlave/zapsentry"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
globalLogger Logger
globalSugaredLogger SugaredLogger
globalLoggerLevel zap.AtomicLevel
)
var (
DebugLevel = zapcore.DebugLevel
InfoLevel = zapcore.InfoLevel
WarnLevel = zapcore.WarnLevel
ErrorLevel = zapcore.ErrorLevel
PanicLevel = zapcore.PanicLevel
FatalLevel = zapcore.FatalLevel
)
var levelMapping = map[string]Level{
DebugLevel.String(): DebugLevel,
InfoLevel.String(): InfoLevel,
WarnLevel.String(): WarnLevel,
ErrorLevel.String(): ErrorLevel,
PanicLevel.String(): PanicLevel,
FatalLevel.String(): FatalLevel,
}
type (
// Field is an alias of zap.Field. Aliasing this type dramatically
// improves the navigability of this package's API documentation.
Field = zap.Field
Level = zapcore.Level
)
type SugaredLogger interface {
Named(name string) SugaredLogger
With(args ...interface{}) SugaredLogger
Debug(args ...interface{})
Info(args ...interface{})
Warn(args ...interface{})
Error(args ...interface{})
Panic(args ...interface{})
Fatal(args ...interface{})
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Panicf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
Sync()
}
// Logger defines methods of writing log
type Logger interface {
Named(s string) Logger
With(fields ...Field) Logger
Debug(msg string, fields ...Field)
Info(msg string, fields ...Field)
Warn(msg string, fields ...Field)
Error(msg string, fields ...Field)
Clone() Logger
Level() string
IsDebug() bool
Sync()
SugaredLogger() SugaredLogger
CoreLogger() *zap.Logger
}
type logger struct {
level string
logger *zap.Logger
sugaredLogger *zap.SugaredLogger
}
type sugaredLogger struct {
sugaredLogger *zap.SugaredLogger
}
type Config struct {
Level string
// Encoding sets the logger's encoding. Valid values are "json" and
// "console", as well as any third-party encodings registered via
// RegisterEncoder.
Encoding string
// DisableCaller configures the Logger to annotate each message with the filename
// and line number of zap's caller, or not
DisableCaller bool
// OutputPaths is a list of URLs or file paths to write logging output to.
// See Open for details.
OutputPaths []string
// ErrorOutputPaths is a list of URLs to write internal logger errors to.
// The default is standard error.
//
// Note that this setting only affects internal errors; for sample code that
// sends error-level logs to a different location from info- and debug-level
// logs, see the package-level AdvancedConfiguration example.
ErrorOutputPaths []string
}
func New(cfgs ...*Config) (Logger, zap.AtomicLevel) {
var cfg *Config
if len(cfgs) > 0 {
cfg = cfgs[0]
}
l := &logger{
level: getLevel(cfg),
}
// get encoding
encoding := "json"
if cfg != nil && cfg.Encoding != "" {
encoding = cfg.Encoding
}
atomicLevel := zap.NewAtomicLevelAt(parseLevel(l.level))
// get output paths
outputPaths, errorOutputPaths := getOutputPaths(cfg)
// get config
config := getConfig(atomicLevel, encoding, outputPaths, errorOutputPaths)
var err error
if cfg != nil && cfg.DisableCaller {
l.logger, err = config.Build(zap.WithCaller(false))
} else {
l.logger, err = config.Build(zap.AddCallerSkip(2))
}
if err != nil {
panic(err)
}
l.sugaredLogger = l.logger.Sugar()
// add sentry hook
addSentryHook(l.logger)
return l, atomicLevel
}
func getConfig(atomicLevel zap.AtomicLevel, encoding string, outputPaths, errorOutputPaths []string) zap.Config {
encoder := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "name",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
encodeTimeLayout(t, "2006-01-02 15:04:05.000", enc)
},
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
if encoding == "console" {
encoder.EncodeLevel = zapcore.CapitalLevelEncoder
}
return zap.Config{
Level: atomicLevel,
Development: false,
Sampling: &zap.SamplingConfig{
Initial: 100,
Thereafter: 100,
},
Encoding: encoding,
EncoderConfig: encoder,
OutputPaths: outputPaths,
ErrorOutputPaths: errorOutputPaths,
}
}
func getLevel(cfg *Config) string {
level := InfoLevel.String()
if cfg != nil && cfg.Level != "" && cfg.Level != level {
level = cfg.Level
}
if lvl := os.Getenv("LOG_LEVEL"); lvl != "" && lvl != level {
level = lvl
}
return level
}
func parseLevel(level string) Level {
lvl, ok := levelMapping[level]
if ok {
return lvl
}
// default level: info
return InfoLevel
}
func getOutputPaths(cfg *Config) (outputPaths, errorOutputPaths []string) {
if cfg == nil {
return []string{"stdout"}, []string{"stderr"}
}
outputPaths = cfg.OutputPaths
errorOutputPaths = cfg.ErrorOutputPaths
if len(cfg.OutputPaths) == 0 {
outputPaths = []string{"stdout"}
} else if len(cfg.OutputPaths) > 1 {
for _, p := range outputPaths {
if p == "stdout" || p == "stderr" {
continue
}
// try to create the file if not exists
_ = createFileIfNotExists(p)
}
}
if len(cfg.ErrorOutputPaths) == 0 {
errorOutputPaths = []string{"stderr"}
} else if len(cfg.ErrorOutputPaths) > 1 {
for _, p := range errorOutputPaths {
if p == "stdout" || p == "stderr" {
continue
}
// try to create the file if not exists
_ = createFileIfNotExists(p)
}
}
return
}
func encodeTimeLayout(t time.Time, layout string, enc zapcore.PrimitiveArrayEncoder) {
type appendTimeEncoder interface {
AppendTimeLayout(time.Time, string)
}
if enc, ok := enc.(appendTimeEncoder); ok {
enc.AppendTimeLayout(t, layout)
return
}
enc.AppendString(t.Format(layout))
}
func addSentryHook(l *zap.Logger) *zap.Logger {
dsn := os.Getenv("SENTRY_DSN")
if dsn == "" {
return l
}
cfg := zapsentry.Configuration{
Level: ErrorLevel,
}
core, err := zapsentry.NewCore(cfg, zapsentry.NewSentryClientFromDSN(dsn))
if err != nil {
stdlog.Printf("WARN - failed to new sentry client: %v\n", err)
return l
}
stdlog.Printf("Attach logger to sentry: %s\n", dsn)
return zapsentry.AttachCoreToLogger(core, l)
}
func init() {
globalLogger, globalLoggerLevel = New()
globalSugaredLogger = globalLogger.SugaredLogger()
zap.ReplaceGlobals(globalLogger.CoreLogger())
}