/
gcp.go
296 lines (249 loc) · 7.6 KB
/
gcp.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package logger
import (
"context"
"fmt"
"net/http"
"slices"
"sync"
"time"
"cloud.google.com/go/logging"
"contrib.go.opencensus.io/exporter/stackdriver/propagation"
"go.opentelemetry.io/otel/trace"
)
const gcpMessageKey = "message"
// GoogleCloudExporter implements exporting to Google Cloud Logging
type GoogleCloudExporter struct {
projectID string
client *logging.Client
opts []logging.LoggerOption
logAll bool
}
// NewGoogleCloudExporter returns a configured GoogleCloudExporter
func NewGoogleCloudExporter(client *logging.Client, projectID string, opts ...logging.LoggerOption) *GoogleCloudExporter {
return &GoogleCloudExporter{
projectID: projectID,
client: client,
opts: opts,
logAll: true,
}
}
// LogAll controls if this logger will log all requests, or only requests that contain
// logs written to the request Logger (default: true)
func (e *GoogleCloudExporter) LogAll(v bool) *GoogleCloudExporter {
e.logAll = v
return e
}
// Middleware returns a middleware that exports logs to Google Cloud Logging
func (e *GoogleCloudExporter) Middleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return &gcpHandler{
next: next,
parentLogger: e.client.Logger("request_parent_log", e.opts...),
childLogger: e.client.Logger("request_child_log", e.opts...),
projectID: e.projectID,
logAll: e.logAll,
}
}
}
type gcpHandler struct {
next http.Handler
parentLogger logger
childLogger logger
projectID string
logAll bool
}
func (g *gcpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
begin := time.Now()
traceID := gcpTraceIDFromRequest(r, g.projectID, generateID)
l := newGCPLogger(g.childLogger, traceID)
r = r.WithContext(newContext(r.Context(), l))
sw := newResponseRecorder(w)
g.next.ServeHTTP(sw, r)
l.mu.Lock()
logCount := l.logCount
maxSeverity := l.maxSeverity
attributes := make(map[string]any)
for k, v := range l.reqAttributes {
attributes[k] = v
}
l.mu.Unlock()
if !g.logAll && logCount == 0 {
return
}
// status code should also set the minimum maxSeverity to Error
if sw.Status() > 499 && maxSeverity < logging.Error {
maxSeverity = logging.Error
}
sc := trace.SpanFromContext(r.Context()).SpanContext()
attributes[gcpMessageKey] = parentLogEntry
g.parentLogger.Log(logging.Entry{
Timestamp: begin,
Severity: maxSeverity,
Trace: traceID,
SpanID: sc.SpanID().String(),
TraceSampled: sc.IsSampled(),
Payload: attributes,
HTTPRequest: &logging.HTTPRequest{
Request: r,
RequestSize: requestSize(r.Header.Get("Content-Length")),
Latency: time.Since(begin),
Status: sw.Status(),
ResponseSize: sw.Length(),
RemoteIP: r.Header.Get("X-Forwarded-For"),
},
})
}
// gcpTraceIDFromRequest formats a trace_id value for GCP Stackdriver
func gcpTraceIDFromRequest(r *http.Request, projectID string, idgen func() string) string {
var traceID string
if sc := trace.SpanFromContext(r.Context()).SpanContext(); sc.IsValid() {
traceID = sc.TraceID().String()
} else {
if sc1, ok := new(propagation.HTTPFormat).SpanContextFromRequest(r); ok {
traceID = sc1.TraceID.String()
} else {
traceID = idgen()
}
}
return fmt.Sprintf("projects/%s/traces/%s", projectID, traceID)
}
// logger interface exists for testability
type logger interface {
Log(e logging.Entry)
}
type gcpLogger struct {
root *gcpLogger
logger logger
traceID string
rsvdKeys []string
attributes map[string]any // attributes for child (trace) logs
mu sync.Mutex
maxSeverity logging.Severity
logCount int
reqAttributes map[string]any // attributes for the parent request log
}
func newGCPLogger(lg logger, traceID string) *gcpLogger {
l := &gcpLogger{
logger: lg,
traceID: traceID,
rsvdKeys: []string{gcpMessageKey},
reqAttributes: make(map[string]any),
attributes: make(map[string]any),
}
l.root = l // root is self
return l
}
// newChild returns a new child gcpLogger
func (l *gcpLogger) newChild() *gcpLogger {
return &gcpLogger{
root: l.root,
logger: l.logger,
traceID: l.traceID,
rsvdKeys: l.rsvdKeys,
attributes: make(map[string]any),
reqAttributes: nil, // reqAttributes is only used in the root logger, never the child.
}
}
// Debug logs a debug message.
func (l *gcpLogger) Debug(ctx context.Context, v any) {
l.log(ctx, logging.Debug, v)
}
// Debugf logs a debug message with format.
func (l *gcpLogger) Debugf(ctx context.Context, format string, v ...any) {
l.log(ctx, logging.Debug, fmt.Sprintf(format, v...))
}
// Info logs a info message.
func (l *gcpLogger) Info(ctx context.Context, v any) {
l.log(ctx, logging.Info, v)
}
// Infof logs a info message with format.
func (l *gcpLogger) Infof(ctx context.Context, format string, v ...any) {
l.log(ctx, logging.Info, fmt.Sprintf(format, v...))
}
// Warn logs a warning message.
func (l *gcpLogger) Warn(ctx context.Context, v any) {
l.log(ctx, logging.Warning, v)
}
// Warnf logs a warning message with format.
func (l *gcpLogger) Warnf(ctx context.Context, format string, v ...any) {
l.log(ctx, logging.Warning, fmt.Sprintf(format, v...))
}
// Error logs an error message.
func (l *gcpLogger) Error(ctx context.Context, v any) {
l.log(ctx, logging.Error, v)
}
// Errorf logs an error message with format.
func (l *gcpLogger) Errorf(ctx context.Context, format string, v ...any) {
l.log(ctx, logging.Error, fmt.Sprintf(format, v...))
}
// AddRequestAttribute adds an attribute (key, value) for the parent request log
// If the key matches a reserved key, it will be prefixed with "custom_"
// If the key already exists, its value is overwritten
func (l *gcpLogger) AddRequestAttribute(key string, value any) {
if slices.Contains(l.rsvdKeys, key) {
key = customPrefix + key
}
l.root.mu.Lock()
defer l.root.mu.Unlock()
l.root.reqAttributes[key] = value
}
// WithAttributes returns an attributer that can be used to add child (trace) log attributes
func (l *gcpLogger) WithAttributes() attributer {
attrs := make(map[string]any)
for k, v := range l.attributes {
attrs[k] = v
}
return &gcpAttributer{logger: l, attributes: attrs}
}
// TraceID returns the trace ID of the request logs
func (l *gcpLogger) TraceID() string {
return l.traceID
}
func (l *gcpLogger) log(ctx context.Context, severity logging.Severity, msg any) {
l.root.mu.Lock()
if l.root.maxSeverity < severity {
l.root.maxSeverity = severity
}
l.root.logCount++
l.root.mu.Unlock()
if err, ok := msg.(error); ok {
msg = err.Error()
}
span := trace.SpanFromContext(ctx)
attrs := make(map[string]any)
for k, v := range l.attributes {
attrs[k] = v
}
attrs[gcpMessageKey] = msg
l.logger.Log(
logging.Entry{
Payload: attrs,
Severity: severity,
Trace: l.traceID,
SpanID: span.SpanContext().SpanID().String(),
TraceSampled: span.SpanContext().IsSampled(),
},
)
}
var _ attributer = (*gcpAttributer)(nil)
type gcpAttributer struct {
logger *gcpLogger
attributes map[string]any
}
// AddAttribute adds an attribute (key, value) for the child (trace) log
// If the key matches a reserved key, it will be prefixed with "custom_"
// If the key already exists, its value is overwritten
func (a *gcpAttributer) AddAttribute(key string, value any) {
if slices.Contains(a.logger.rsvdKeys, key) {
key = customPrefix + key
}
a.attributes[key] = value
}
// Logger returns a ctxLogger with the child (trace) attributes embedded
func (a *gcpAttributer) Logger() ctxLogger {
l := a.logger.newChild()
for k, v := range a.attributes {
l.attributes[k] = v
}
return l
}