-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
314 lines (262 loc) · 8.65 KB
/
logger.go
File metadata and controls
314 lines (262 loc) · 8.65 KB
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
package dglogger
import (
"fmt"
"io"
"os"
"runtime"
"strings"
"github.com/darwinOrg/go-common/constants"
dgctx "github.com/darwinOrg/go-common/context"
dgsys "github.com/darwinOrg/go-common/sys"
"github.com/darwinOrg/go-common/utils"
"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
// PanicLevel level, highest level of severity. Logs and then calls panic with the
// message passed to Debug, Info, ...
PanicLevel = "panic"
// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
// logging level is set to Panic.
FatalLevel = "fatal"
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
// Commonly used for hooks to send errors to an error tracking service.
ErrorLevel = "error"
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel = "warn"
// InfoLevel level. General operational entries about what's going on inside the
// application.
InfoLevel = "info"
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel = "debug"
)
const (
DefaultTimestampFormat = "2006-01-02 15:04:05.999999"
DefaultFilename = "app.log" // 日志文件路径
DefaultMaxSize = 100 // 每个日志文件的最大尺寸(MB)
DefaultMaxBackups = 10 // 保留旧日志文件的最大数量
DefaultMaxAge = 30 // 保留旧日志文件的最大天数
DefaultCompress = true // 是否压缩/归档旧的日志文件
extraFieldsKey = "extraLogFields"
)
func init() {
zap.StackSkip("stacktrace", 2)
}
type DgLogger struct {
log *zap.Logger
}
func DefaultDgLogger() *DgLogger {
return NewDgLogger(getDefaultLogLevel(), DefaultTimestampFormat, os.Stdout)
}
func DefaultRotatedLogger() *DgLogger {
return NewDgLogger(getDefaultLogLevel(), DefaultTimestampFormat, buildDefaultRotatedLogWriter())
}
func DefaultMultiWriterLogger() *DgLogger {
return NewDgLogger(getDefaultLogLevel(), DefaultTimestampFormat, io.MultiWriter(os.Stdout, buildDefaultRotatedLogWriter()))
}
func NewDgLogger(level string, timestampFormat string, out io.Writer) *DgLogger {
// 创建 zap 配置
config := zap.NewProductionEncoderConfig()
config.EncodeTime = zapcore.TimeEncoderOfLayout(timestampFormat)
config.EncodeLevel = zapcore.CapitalLevelEncoder
// 创建 encoder
encoder := zapcore.NewConsoleEncoder(config)
// 创建 core
core := zapcore.NewCore(
encoder,
zapcore.AddSync(out),
parseLevel(level),
)
// 创建 logger, 只在错误级别及以上记录堆栈
logger := zap.New(core, zap.AddStacktrace(zapcore.ErrorLevel), zap.AddCaller(), zap.AddCallerSkip(2))
return &DgLogger{log: logger}
}
func getDefaultLogLevel() string {
logLevel := os.Getenv("LOG_LEVEL")
if logLevel != "" {
return logLevel
}
return utils.IfReturn(dgsys.IsProd(), InfoLevel, DebugLevel)
}
func buildDefaultRotatedLogWriter() io.Writer {
return &lumberjack.Logger{
Filename: DefaultFilename,
MaxSize: DefaultMaxSize,
MaxBackups: DefaultMaxBackups,
MaxAge: DefaultMaxAge,
Compress: DefaultCompress,
}
}
func (dl *DgLogger) Debugf(ctx *dgctx.DgContext, format string, args ...any) {
if dl.log.Core().Enabled(zap.DebugLevel) {
dl.withFields(ctx, nil, false).Debug(fmt.Sprintf(format, args...))
}
}
func (dl *DgLogger) Infof(ctx *dgctx.DgContext, format string, args ...any) {
if dl.log.Core().Enabled(zap.InfoLevel) {
dl.withFields(ctx, nil, false).Info(fmt.Sprintf(format, args...))
}
}
func (dl *DgLogger) Warnf(ctx *dgctx.DgContext, format string, args ...any) {
if dl.log.Core().Enabled(zap.WarnLevel) {
dl.withFields(ctx, nil, false).Warn(fmt.Sprintf(format, args...))
}
}
func (dl *DgLogger) Errorf(ctx *dgctx.DgContext, format string, args ...any) {
if dl.log.Core().Enabled(zap.ErrorLevel) {
dl.withFields(ctx, nil, true).Error(fmt.Sprintf(format, args...))
}
}
func (dl *DgLogger) Fatalf(ctx *dgctx.DgContext, format string, args ...any) {
dl.withFields(ctx, nil, true).Fatal(fmt.Sprintf(format, args...))
}
func (dl *DgLogger) Panicf(ctx *dgctx.DgContext, format string, args ...any) {
dl.withFields(ctx, nil, true).Panic(fmt.Sprintf(format, args...))
}
func (dl *DgLogger) Debug(ctx *dgctx.DgContext, args ...any) {
if dl.log.Core().Enabled(zap.DebugLevel) {
dl.withFields(ctx, nil, false).Debug(fmt.Sprint(args...))
}
}
func (dl *DgLogger) Info(ctx *dgctx.DgContext, args ...any) {
if dl.log.Core().Enabled(zap.InfoLevel) {
dl.withFields(ctx, nil, false).Info(fmt.Sprint(args...))
}
}
func (dl *DgLogger) Warn(ctx *dgctx.DgContext, args ...any) {
if dl.log.Core().Enabled(zap.WarnLevel) {
dl.withFields(ctx, nil, false).Warn(fmt.Sprint(args...))
}
}
func (dl *DgLogger) Error(ctx *dgctx.DgContext, args ...any) {
if dl.log.Core().Enabled(zap.ErrorLevel) {
dl.withFields(ctx, nil, true).Error(fmt.Sprint(args...))
}
}
func (dl *DgLogger) Fatal(ctx *dgctx.DgContext, args ...any) {
dl.withFields(ctx, nil, true).Fatal(fmt.Sprint(args...))
}
func (dl *DgLogger) Panic(ctx *dgctx.DgContext, args ...any) {
dl.withFields(ctx, nil, true).Panic(fmt.Sprint(args...))
}
func (dl *DgLogger) Debugln(ctx *dgctx.DgContext, args ...any) {
if dl.log.Core().Enabled(zap.DebugLevel) {
dl.withFields(ctx, nil, false).Debug(fmt.Sprintln(args...))
}
}
func (dl *DgLogger) Infoln(ctx *dgctx.DgContext, args ...any) {
if dl.log.Core().Enabled(zap.InfoLevel) {
dl.withFields(ctx, nil, false).Info(fmt.Sprintln(args...))
}
}
func (dl *DgLogger) Warnln(ctx *dgctx.DgContext, args ...any) {
if dl.log.Core().Enabled(zap.WarnLevel) {
dl.withFields(ctx, nil, false).Warn(fmt.Sprintln(args...))
}
}
func (dl *DgLogger) Errorln(ctx *dgctx.DgContext, args ...any) {
if dl.log.Core().Enabled(zap.ErrorLevel) {
dl.withFields(ctx, nil, true).Error(fmt.Sprintln(args...))
}
}
func (dl *DgLogger) Fatalln(ctx *dgctx.DgContext, args ...any) {
dl.withFields(ctx, nil, true).Fatal(fmt.Sprintln(args...))
}
func (dl *DgLogger) Panicln(ctx *dgctx.DgContext, args ...any) {
dl.withFields(ctx, nil, true).Panic(fmt.Sprintln(args...))
}
func (dl *DgLogger) Debugw(ctx *dgctx.DgContext, content string, fields map[string]any) {
if dl.log.Core().Enabled(zap.DebugLevel) {
dl.withFields(ctx, fields, false).Debug(content)
}
}
func (dl *DgLogger) Infow(ctx *dgctx.DgContext, content string, fields map[string]any) {
if dl.log.Core().Enabled(zap.InfoLevel) {
dl.withFields(ctx, fields, false).Info(content)
}
}
func (dl *DgLogger) Warnw(ctx *dgctx.DgContext, content string, fields map[string]any) {
if dl.log.Core().Enabled(zap.WarnLevel) {
dl.withFields(ctx, fields, false).Warn(content)
}
}
func (dl *DgLogger) Errorw(ctx *dgctx.DgContext, content string, fields map[string]any) {
if dl.log.Core().Enabled(zap.ErrorLevel) {
dl.withFields(ctx, fields, true).Error(content)
}
}
func (dl *DgLogger) Fatalw(ctx *dgctx.DgContext, content string, fields map[string]any) {
dl.withFields(ctx, fields, true).Fatal(content)
}
func (dl *DgLogger) Panicw(ctx *dgctx.DgContext, content string, fields map[string]any) {
dl.withFields(ctx, fields, true).Panic(content)
}
func SetExtraFields(ctx *dgctx.DgContext, fields map[string]any) {
ctx.SetExtraKeyValue(extraFieldsKey, fields)
}
func (dl *DgLogger) withFields(ctx *dgctx.DgContext, fields map[string]any, printFileLine bool) *zap.Logger {
allFields := []zap.Field{
zap.String(constants.TraceId, ctx.TraceId),
}
if ctx.SpanId != "" {
allFields = append(allFields, zap.String(constants.SpanId, ctx.SpanId))
}
if ctx.UserId > 0 {
allFields = append(allFields, zap.Int64(constants.UID, ctx.UserId))
}
if len(fields) > 0 {
for k, v := range fields {
allFields = append(allFields, zap.Any(k, v))
}
}
extraFields := ctx.GetExtraValue(extraFieldsKey)
if extraFields != nil {
fds := extraFields.(map[string]any)
if len(fds) > 0 {
for k, v := range fds {
allFields = append(allFields, zap.Any(k, v))
}
}
}
if printFileLine {
// 动态查找真正的调用者
var file string
var line int
var found bool
// 从第3层开始向上查找,直到找到非logger包中的调用者
for i := 3; i <= 10; i++ {
_, f, l, ok := runtime.Caller(i)
if ok && !strings.Contains(f, "go-logger/logger.go") {
file, line = f, l
found = true
break
}
}
if found {
allFields = append(allFields,
zap.String("file", file),
zap.Int("line", line),
)
}
}
return dl.log.With(allFields...)
}
func parseLevel(level string) zapcore.Level {
switch level {
case PanicLevel:
return zap.PanicLevel
case FatalLevel:
return zap.FatalLevel
case ErrorLevel:
return zap.ErrorLevel
case WarnLevel:
return zap.WarnLevel
case InfoLevel:
return zap.InfoLevel
case DebugLevel:
return zap.DebugLevel
default:
return zap.DebugLevel
}
}