-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
219 lines (202 loc) · 6.06 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
package log
import (
"context"
"fmt"
"log"
"sync"
"syscall"
"github.com/pkg/errors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/wfusion/gofusion/common/infra/watermill"
"github.com/wfusion/gofusion/common/utils"
"github.com/wfusion/gofusion/config"
"github.com/wfusion/gofusion/log/encoder"
fusCtx "github.com/wfusion/gofusion/context"
)
var (
globalLogger = defaultLogger(false)
rwlock = new(sync.RWMutex)
appInstances map[string]map[string]*logger
)
type logger struct {
name string
logger *zap.Logger
sugaredLogger *zap.SugaredLogger
}
type useOption struct {
appName string
}
func AppName(name string) utils.OptionFunc[useOption] {
return func(o *useOption) {
o.appName = name
}
}
func Use(name string, opts ...utils.OptionExtender) Loggable {
opt := utils.ApplyOptions[useOption](opts...)
rwlock.RLock()
defer rwlock.RUnlock()
instances, ok := appInstances[opt.appName]
if !ok {
globalLogger.Debug(context.Background(), "%v [Gofusion] %s instance not found for app: %s",
syscall.Getpid(), config.ComponentLog, opt.appName, Fields{"component": "log"})
return globalLogger
}
instance, ok := instances[name]
if !ok {
instance, ok = instances[config.DefaultInstanceKey]
if ok {
instance.Debug(context.Background(), "%v [Gofusion] %s instance not found for name: %s",
syscall.Getpid(), config.ComponentLog, name, Fields{"component": "log"})
return instance
}
globalLogger.Debug(context.Background(), "%v [Gofusion] %s instance not found for name: %s",
syscall.Getpid(), config.ComponentLog, name, Fields{"component": "log"})
return globalLogger
}
return instance
}
func defaultLogger(colorful bool) Loggable {
devCfg := zap.NewDevelopmentConfig()
devCfg.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
if colorful {
devCfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
devCfg.EncoderConfig.EncodeCaller = encoder.SkipCallerEncoder(encoder.SkipCallers, true)
zapLogger, _ := devCfg.Build(
zap.AddStacktrace(zap.PanicLevel),
zap.AddCaller(),
zap.Hooks(),
)
return &logger{
logger: zapLogger,
sugaredLogger: zapLogger.Sugar(),
}
}
func (l *logger) Debug(ctx context.Context, format string, args ...any) {
lg, msg, fields := l.sweeten(ctx, format, args...)
if logger, ok := lg.(*logger); ok {
logger.logger.Debug(msg, fields...)
} else {
lg.Debug(ctx, msg, args...)
}
}
func (l *logger) Info(ctx context.Context, format string, args ...any) {
lg, msg, fields := l.sweeten(ctx, format, args...)
if logger, ok := lg.(*logger); ok {
logger.logger.Info(msg, fields...)
} else {
lg.Info(ctx, msg, args...)
}
}
func (l *logger) Warn(ctx context.Context, format string, args ...any) {
lg, msg, fields := l.sweeten(ctx, format, args...)
if logger, ok := lg.(*logger); ok {
logger.logger.Warn(msg, fields...)
} else {
lg.Warn(ctx, msg, args...)
}
}
func (l *logger) Error(ctx context.Context, format string, args ...any) {
lg, msg, fields := l.sweeten(ctx, format, args...)
if logger, ok := lg.(*logger); ok {
logger.logger.Error(msg, fields...)
} else {
lg.Error(ctx, msg, args...)
}
}
func (l *logger) Panic(ctx context.Context, format string, args ...any) {
lg, msg, fields := l.sweeten(ctx, format, args...)
if logger, ok := lg.(*logger); ok {
logger.logger.Panic(msg, fields...)
} else {
lg.Panic(ctx, msg, args...)
}
}
func (l *logger) Fatal(ctx context.Context, format string, args ...any) {
lg, msg, fields := l.sweeten(ctx, format, args...)
if logger, ok := lg.(*logger); ok {
logger.logger.Fatal(msg, fields...)
} else {
lg.Fatal(ctx, msg, args...)
}
}
func (l *logger) Level(ctx context.Context) Level {
ctxLogger := GetCtxLogger(ctx, l)
lg, ok := ctxLogger.(*logger)
if !ok {
return InvalidLevel
}
switch lg.logger.Level() {
case zap.DebugLevel:
return DebugLevel
case zap.InfoLevel:
return InfoLevel
case zap.WarnLevel:
return WarnLevel
case zap.ErrorLevel:
return ErrorLevel
case zap.PanicLevel:
return PanicLevel
case zap.FatalLevel:
return FatalLevel
default:
return InfoLevel
}
}
func (l *logger) flush() {
ignore := func(err error) bool {
// ENOTTY:
// ignore sync /dev/stdout: inappropriate ioctl for device errors,
// which happens when redirect stderr to stdout
// EINVAL:
// ignore sync /dev/stdout: invalid argument
for _, target := range []error{syscall.EINVAL, syscall.ENOTTY} {
if errors.Is(err, target) {
return true
}
}
return false
}
pid := syscall.Getpid()
if _, err := utils.Catch(l.logger.Sync); err != nil && !ignore(err) {
log.Printf("%v [Gofusion] %s flush %s logger error: %s", pid, config.ComponentLog, l.name, err)
}
if _, err := utils.Catch(l.sugaredLogger.Sync); err != nil && !ignore(err) {
log.Printf("%v [Gofusion] %s flush %s sugared logger error: %s",
pid, config.ComponentLog, l.name, err)
}
}
func (l *logger) sweeten(ctx context.Context, format string, raw ...any) (
log Loggable, msg string, fields []zap.Field) {
args := make([]any, 0, len(raw))
fields = getContextZapFields(ctx)
for _, arg := range raw {
if f, ok := arg.(Fields); ok {
fields = append(fields, convertFieldsToZapFields(f)...)
continue
}
args = append(args, arg)
}
msg = fmt.Sprintf(format, args...)
if userID := fusCtx.GetUserID(ctx); utils.IsStrNotBlank(userID) {
fields = append(fields, zap.String("user_id", userID))
}
if traceID := fusCtx.GetTraceID(ctx); utils.IsStrNotBlank(traceID) {
fields = append(fields, zap.String("trace_id", traceID))
}
if taskID := fusCtx.GetCronTaskID(ctx); utils.IsStrNotBlank(taskID) {
fields = append(fields, zap.String("cron_task_id", taskID))
}
if taskName := fusCtx.GetCronTaskName(ctx); utils.IsStrNotBlank(taskName) {
fields = append(fields, zap.String("cron_task_name", taskName))
}
if id := utils.GetCtxAny[string](ctx, watermill.ContextKeyMessageUUID); utils.IsStrNotBlank(id) {
fields = append(fields, zap.String("message_uuid", id))
}
if id := utils.GetCtxAny[string](ctx, watermill.ContextKeyRawMessageID); utils.IsStrNotBlank(id) {
fields = append(fields, zap.String("message_raw_id", id))
}
log = GetCtxLogger(ctx, l)
return
}