-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathctxlog.go
204 lines (171 loc) · 5.86 KB
/
ctxlog.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
package ctxlog
import (
"context"
"fmt"
"net/http"
"github.com/beatlabs/patron/log"
"github.com/google/uuid"
)
// List of header values that should be forwarded during login
const (
AmazonTraceHeader = "X-Amzn-Trace-Id"
ForwardForHeader = "X-Forwarded-For"
RequestIDHeader = "X-REQUEST-ID"
UserAgentHeader = "User-Agent"
)
// Constants for context data.
const (
RequestID = "request_id"
AmazonTraceID = "amazon_trace_id"
IPForwardedFor = "ip_forwarded_for"
UserAgent = "user_agent"
)
// CtxKey json key on which the context data is logged.
const CtxKey = "ctx"
// CtxLogger is a logger implementation that delegates logging fully to Patron and always adds some logging context to a message.
type CtxLogger struct {
logger log.Logger
contextData map[string]interface{}
}
// AddLoggerForRequest adds a ctx logger to the context of an HTTP request
func AddLoggerForRequest(req *http.Request) context.Context {
ctx := req.Context()
logger := log.FromContext(ctx)
if _, ok := logger.(*CtxLogger); ok {
return ctx
}
ctxLogger := &CtxLogger{
logger: logger,
contextData: map[string]interface{}{
RequestID: getRequestID(req),
AmazonTraceID: req.Header.Get(AmazonTraceHeader),
IPForwardedFor: req.Header.Get(ForwardForHeader),
UserAgent: req.Header.Get(UserAgentHeader),
},
}
return log.WithContext(ctx, ctxLogger)
}
func getRequestID(req *http.Request) string {
reqIDFromHeader := req.Header.Get(RequestIDHeader)
if reqIDFromHeader == "" {
return uuid.New().String()
}
return reqIDFromHeader
}
// FromContext associates logger with a context and returns both the context and the logger.
// If logger in this context has been already created, returns that one, otherwise creates a new one and associates it with a context.
// When created, a logger gets a unique request UUID.
func FromContext(ctx context.Context) *CtxLogger {
logger := log.FromContext(ctx)
if ctxLogger, ok := logger.(*CtxLogger); ok {
return ctxLogger
}
ctxLogger := &CtxLogger{
logger: logger,
contextData: map[string]interface{}{RequestID: uuid.New().String()},
}
return ctxLogger
}
// RequestID returns a current request ID.
func (l *CtxLogger) RequestID() string {
reqID, ok := l.contextData[RequestID].(string)
if !ok {
requestID := uuid.New().String()
l.contextData[RequestID] = requestID
return requestID
}
return reqID
}
// Str returns a logger with a key-value added to log context.
func (l *CtxLogger) Str(key, value string) *CtxLogger {
l.contextData[key] = value
return l
}
// Int returns a logger with a key-value added to log context.
func (l *CtxLogger) Int(key string, value int) *CtxLogger {
l.contextData[key] = fmt.Sprintf("%d", value)
return l
}
// SubCtx appends a list of fields to the context data.
func (l *CtxLogger) SubCtx(fields map[string]interface{}) *CtxLogger {
for k, v := range fields {
l.contextData[k] = v
}
return l
}
// Sub returns a sub logger with new fields attached.
func (l *CtxLogger) Sub(fields map[string]interface{}) log.Logger {
return &CtxLogger{
logger: l.logger.Sub(fields),
contextData: l.contextData,
}
}
// Level returns the current loglevel.
func (l *CtxLogger) Level() log.Level {
return l.logger.Level()
}
// Fatal adds log context data to the log message.
func (l *CtxLogger) Fatal(i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Fatal(fmt.Sprint(i...))
}
// Fatalf adds log context data to the log message.
func (l *CtxLogger) Fatalf(s string, i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Fatal(fmt.Sprintf(s, i...))
}
// Panic adds log context data to the log message.
func (l *CtxLogger) Panic(i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Panic(fmt.Sprint(i...))
}
// Panicf adds log context data to the log message.
func (l *CtxLogger) Panicf(s string, i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Panic(fmt.Sprintf(s, i...))
}
// Error adds log context data to the log message.
func (l *CtxLogger) Error(i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Error(fmt.Sprint(i...))
}
// Errorf adds log context data to the log message.
func (l *CtxLogger) Errorf(s string, i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Error(fmt.Sprintf(s, i...))
}
// Warn adds log context data to the log message.
func (l *CtxLogger) Warn(i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Warn(fmt.Sprint(i...))
}
// Warnf adds log context data to the log message.
func (l *CtxLogger) Warnf(s string, i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Warn(fmt.Sprintf(s, i...))
}
// Info adds log context data to the log message.
func (l *CtxLogger) Info(i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Info(fmt.Sprint(i...))
}
// Infof adds log context data to the log message.
func (l *CtxLogger) Infof(s string, i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Info(fmt.Sprintf(s, i...))
}
// Debug adds log context data to the log message.
func (l *CtxLogger) Debug(i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Debug(fmt.Sprint(i...))
}
// Debugf adds log context data to the log message.
func (l *CtxLogger) Debugf(s string, i ...interface{}) {
l.logger.Sub(map[string]interface{}{CtxKey: l.contextData}).Debug(fmt.Sprintf(s, i...))
}
// Logf logs at the provided level, adding log context data to the logs message.
func (l *CtxLogger) Logf(loglevel log.Level, s string, i ...interface{}) {
switch loglevel {
case log.DebugLevel:
l.Debugf(s, i...)
case log.InfoLevel:
l.Infof(s, i...)
case log.WarnLevel:
l.Warnf(s, i...)
case log.ErrorLevel:
l.Errorf(s, i...)
case log.FatalLevel:
l.Fatalf(s, i...)
case log.PanicLevel:
l.Panicf(s, i...)
}
}