-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogger.go
More file actions
65 lines (50 loc) · 1.05 KB
/
logger.go
File metadata and controls
65 lines (50 loc) · 1.05 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
package ctxlog
import (
"context"
"github.com/sirupsen/logrus"
)
type fieldsKey struct{}
type Fields map[string]any
type CtxLogger struct {
Fields Fields
Log *logrus.Logger
}
func New(options ...func(*CtxLogger)) *CtxLogger {
log := &CtxLogger{
Log: logrus.New(),
}
for _, o := range options {
o(log)
}
return log
}
func WithJSONFormat() func(*CtxLogger) {
return func(l *CtxLogger) {
l.Log.SetFormatter(&logrus.JSONFormatter{})
}
}
func getFields(ctx context.Context) Fields {
if val, ok := ctx.Value(fieldsKey{}).(Fields); ok {
return val
}
return Fields{}
}
func WithFields(ctx context.Context, newFields ...Fields) context.Context {
fields := Fields{}
for k, v := range getFields(ctx) {
fields[k] = v
}
for _, fieldMap := range newFields {
for k, v := range fieldMap {
fields[k] = v
}
}
return context.WithValue(ctx, fieldsKey{}, fields)
}
func convertFieldsToLogrusFields(fields Fields) logrus.Fields {
logrusFields := make(logrus.Fields)
for k, v := range fields {
logrusFields[k] = v
}
return logrusFields
}