...
1 package context
2
3 import (
4 "context"
5 "fmt"
6 "runtime"
7
8 "github.com/sirupsen/logrus"
9 )
10
11
12 type Logger interface {
13
14 Print(args ...interface{})
15 Printf(format string, args ...interface{})
16 Println(args ...interface{})
17
18 Fatal(args ...interface{})
19 Fatalf(format string, args ...interface{})
20 Fatalln(args ...interface{})
21
22 Panic(args ...interface{})
23 Panicf(format string, args ...interface{})
24 Panicln(args ...interface{})
25
26
27 Debug(args ...interface{})
28 Debugf(format string, args ...interface{})
29 Debugln(args ...interface{})
30
31 Error(args ...interface{})
32 Errorf(format string, args ...interface{})
33 Errorln(args ...interface{})
34
35 Info(args ...interface{})
36 Infof(format string, args ...interface{})
37 Infoln(args ...interface{})
38
39 Warn(args ...interface{})
40 Warnf(format string, args ...interface{})
41 Warnln(args ...interface{})
42
43 WithError(err error) *logrus.Entry
44 }
45
46 type loggerKey struct{}
47
48
49 func WithLogger(ctx context.Context, logger Logger) context.Context {
50 return context.WithValue(ctx, loggerKey{}, logger)
51 }
52
53
54
55
56 func GetLoggerWithField(ctx context.Context, key, value interface{}, keys ...interface{}) Logger {
57 return getLogrusLogger(ctx, keys...).WithField(fmt.Sprint(key), value)
58 }
59
60
61
62
63 func GetLoggerWithFields(ctx context.Context, fields map[interface{}]interface{}, keys ...interface{}) Logger {
64
65 lfields := make(logrus.Fields, len(fields))
66 for key, value := range fields {
67 lfields[fmt.Sprint(key)] = value
68 }
69
70 return getLogrusLogger(ctx, keys...).WithFields(lfields)
71 }
72
73
74
75
76
77
78
79 func GetLogger(ctx context.Context, keys ...interface{}) Logger {
80 return getLogrusLogger(ctx, keys...)
81 }
82
83
84
85
86
87 func getLogrusLogger(ctx context.Context, keys ...interface{}) *logrus.Entry {
88 var logger *logrus.Entry
89
90
91 loggerInterface := ctx.Value(loggerKey{})
92 if loggerInterface != nil {
93 if lgr, ok := loggerInterface.(*logrus.Entry); ok {
94 logger = lgr
95 }
96 }
97
98 if logger == nil {
99 fields := logrus.Fields{}
100
101
102 instanceID := ctx.Value("instance.id")
103 if instanceID != nil {
104 fields["instance.id"] = instanceID
105 }
106
107 fields["go.version"] = runtime.Version()
108
109 logger = logrus.StandardLogger().WithFields(fields)
110 }
111
112 fields := logrus.Fields{}
113 for _, key := range keys {
114 v := ctx.Value(key)
115 if v != nil {
116 fields[fmt.Sprint(key)] = v
117 }
118 }
119
120 return logger.WithFields(fields)
121 }
122
View as plain text