-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
83 lines (69 loc) · 1.8 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
// Package log provides context-aware and structured logging capabilities.
package log
import (
"context"
"net/http"
"github.com/google/uuid"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
)
type Logger interface {
With(ctx context.Context, args ...interface{}) Logger
Debug(args ...interface{})
Info(args ...interface{})
Error(args ...interface{})
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Errorf(format string, args ...interface{})
}
type logger struct {
*zap.SugaredLogger
}
type contextKey int
const (
requestIDKey contextKey = iota
correlationIDKey
)
func New() Logger {
l, _ := zap.NewProduction()
return NewWithZap(l)
}
func NewWithZap(l *zap.Logger) Logger {
return &logger{l.Sugar()}
}
func NewForTest() (Logger, *observer.ObservedLogs) {
core, recorded := observer.New(zapcore.InfoLevel)
return NewWithZap(zap.New(core)), recorded
}
func (l *logger) With(ctx context.Context, args ...interface{}) Logger {
if ctx != nil {
if id, ok := ctx.Value(requestIDKey).(string); ok {
args = append(args, zap.String("request_id", id))
}
if id, ok := ctx.Value(correlationIDKey).(string); ok {
args = append(args, zap.String("correlation_id", id))
}
}
if len(args) > 0 {
return &logger{l.SugaredLogger.With(args...)}
}
return l
}
func WithRequest(ctx context.Context, req *http.Request) context.Context {
id := getRequestID(req)
if id == "" {
id = uuid.New().String()
}
ctx = context.WithValue(ctx, requestIDKey, id)
if id := getCorrelationID(req); id != "" {
ctx = context.WithValue(ctx, correlationIDKey, id)
}
return ctx
}
func getCorrelationID(req *http.Request) string {
return req.Header.Get("X-Correlation-ID")
}
func getRequestID(req *http.Request) string {
return req.Header.Get("X-Request-ID")
}