-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
228 lines (187 loc) · 5.68 KB
/
logger.go
File metadata and controls
228 lines (187 loc) · 5.68 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
package logger
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"github.com/getsentry/sentry-go"
"github.com/vrischmann/envconfig"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
var global *zap.SugaredLogger
func init() {
SetLogger(New(zap.NewAtomicLevelAt(zap.InfoLevel), nil))
}
// SetLogger sets global used logger. This function is not thread-safe.
func SetLogger(l *zap.SugaredLogger) {
global = l
}
// New creates new *zap.SugaredLogger with standard EncoderConfig
func New(lvl zapcore.LevelEnabler, customFieldsKV []string, options ...zap.Option) *zap.SugaredLogger {
sink := zapcore.AddSync(os.Stdout)
options = append(options, zap.ErrorOutput(sink))
cfg := zapcore.EncoderConfig{
NameKey: "logger",
CallerKey: "caller",
StacktraceKey: "stacktrace",
MessageKey: "message",
LevelKey: "severity",
TimeKey: "timestamp",
LineEnding: zapcore.DefaultLineEnding,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
EncodeLevel: zapcore.LowercaseLevelEncoder,
}
encoder := zapcore.NewJSONEncoder(cfg)
return zap.New(zapcore.NewCore(encoder, sink, lvl), options...).With(customFields(customFieldsKV)...).Sugar()
}
func customFields(customFieldsKV []string) []zapcore.Field {
var fields []zapcore.Field
for i := 0; i < len(customFieldsKV); i += 2 {
fields = append(fields, zap.String(customFieldsKV[i], customFieldsKV[i+1]))
}
return fields
}
// Logger returns current global logger.
func Logger() *zap.SugaredLogger {
return global
}
func InitLogger(serviceName string, customFields ...string) error {
type Config struct {
Level string `envconfig:"default=info"`
}
var cfg struct {
Log *Config
}
if err := envconfig.InitWithPrefix(&cfg, serviceName); err != nil {
return fmt.Errorf("cannot get log config; err: %w", err)
}
lvl := zap.NewAtomicLevel()
err := lvl.UnmarshalText([]byte(cfg.Log.Level))
if err != nil {
return fmt.Errorf("failed to unmurshal log level: %s; err: %v", cfg.Log.Level, err)
}
SetLogger(New(lvl, customFields))
return nil
}
type contextKey struct{}
var loggerContextKey = contextKey{}
// ToContext returns new context with specified sugared logger inside.
func ToContext(ctx context.Context, l *zap.SugaredLogger) context.Context {
return context.WithValue(ctx, loggerContextKey, l)
}
// FromContext returns logger from context if set. Otherwise returns global `global` logger.
// In both cases returned logger is populated with `trace_id` & `span_id`.
func FromContext(ctx context.Context) *zap.SugaredLogger {
var (
logger *zap.SugaredLogger
ok bool
)
logger, ok = ctx.Value(loggerContextKey).(*zap.SugaredLogger)
if !ok {
logger = global
}
s, ok := tracer.SpanFromContext(ctx)
if ok && s.Context().TraceID() > 0 {
logger = withTraceID(logger, s.Context().TraceID(), s.Context().SpanID())
}
reqID := ctx.Value(requestIDKey{})
if reqIDValue, ok := reqID.(string); ok {
logger = withRequestID(logger, reqIDValue)
}
return logger
}
func withTraceID(l *zap.SugaredLogger, traceID, spanID uint64) *zap.SugaredLogger {
return l.With(
zap.Uint64("dd.trace_id", traceID),
zap.Uint64("dd.span_id", spanID),
)
}
func withRequestID(l *zap.SugaredLogger, requestID string) *zap.SugaredLogger {
return l.With(
zap.String("request_id", requestID),
)
}
func Debug(ctx context.Context, args ...interface{}) {
FromContext(ctx).Debug(args...)
}
func Debugf(ctx context.Context, format string, args ...interface{}) {
FromContext(ctx).Debugf(format, args...)
}
func Info(ctx context.Context, args ...interface{}) {
FromContext(ctx).Info(args...)
}
func Infof(ctx context.Context, format string, args ...interface{}) {
FromContext(ctx).Infof(format, args...)
}
func Warn(ctx context.Context, args ...interface{}) {
FromContext(ctx).Warn(args...)
}
func Warnf(ctx context.Context, format string, args ...interface{}) {
FromContext(ctx).Warnf(format, args...)
}
func Error(ctx context.Context, args ...interface{}) {
sendToSentry("", args...)
markTracing(ctx, "", args...)
FromContext(ctx).Error(args...)
}
func Errorf(ctx context.Context, format string, args ...interface{}) {
sendToSentry(format, args...)
markTracing(ctx, format, args...)
FromContext(ctx).Errorf(format, args...)
}
func Fatal(ctx context.Context, args ...interface{}) {
sendToSentry("", args...)
markTracing(ctx, "", args...)
FromContext(ctx).Fatal(args...)
}
func Fatalf(ctx context.Context, format string, args ...interface{}) {
sendToSentry(format, args...)
markTracing(ctx, format, args...)
FromContext(ctx).Fatalf(format, args...)
}
func prepareErrFormat(format string, args ...interface{}) string {
if format != "" || len(args) == 0 {
return format
}
return strings.Repeat("%+v ", len(args))
}
func sendToSentry(format string, args ...interface{}) {
format = prepareErrFormat(format, args)
if format != "" {
sentry.CaptureException(fmt.Errorf(format, args...))
}
}
func markTracing(ctx context.Context, format string, args ...interface{}) {
span, ok := tracer.SpanFromContext(ctx)
if !ok {
return
}
format = prepareErrFormat(format, args)
if format != "" {
span.SetTag("error", fmt.Errorf(format, args...))
}
}
type requestIDKey struct{}
func ReqWithLoggerContext(r *http.Request) *http.Request {
reqID := r.Header.Get("X-Request-Id")
if reqID != "" {
return r.WithContext(context.WithValue(r.Context(), requestIDKey{}, reqID))
}
return r
}
func AddHeadersFromContext(headers http.Header, ctx context.Context) {
reqIDCtx := ctx.Value(requestIDKey{})
if reqIDCtx == nil {
return
}
reqID, ok := reqIDCtx.(string)
if !ok {
return
}
headers.Set("X-Request-Id", reqID)
}