/
logger.go
512 lines (423 loc) · 12.1 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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
package logging
import (
"context"
"fmt"
"net/http"
"net/http/httptrace"
"strings"
"time"
"github.com/hashicorp/go-hclog"
"github.com/nicholasjackson/fake-service/tracing"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/opentracing/opentracing-go/log"
"google.golang.org/grpc/metadata"
)
type Logger struct {
metrics Metrics
log hclog.Logger
getSpanDetails tracing.SpanDetailsFunc
}
func NewLogger(m Metrics, l hclog.Logger, sdf tracing.SpanDetailsFunc) *Logger {
return &Logger{
metrics: m,
log: l,
getSpanDetails: sdf,
}
}
// LogProcess is returned from a logging function
type LogProcess struct {
finished func(err error, meta map[string]string)
err error
metadata map[string]string
Span opentracing.Span
}
// SetError for the current operation
func (l *LogProcess) SetError(err error) {
l.err = err
}
// SetMetadata for the process
func (l *LogProcess) SetMetadata(key, value string) {
if l.metadata == nil {
l.metadata = map[string]string{}
}
l.metadata[key] = value
}
// Finished operation
func (l *LogProcess) Finished() {
l.finished(l.err, l.metadata)
}
func (l *Logger) Log() hclog.Logger {
return l.log
}
// LogServiceStarted logs information when the service starts
func (l *Logger) ServiceStarted(name, upstreamURIs string, upstreamWorkers int, listenAddress string) {
l.log.Info(
"Started service",
"name", name,
"upstreamURIs", upstreamURIs,
"upstreamWorkers", fmt.Sprint(upstreamWorkers),
"listenAddress", listenAddress,
)
l.metrics.Increment("service.started", nil)
}
// HandleHTTPRequest creates the request span and timing metrics for the handler
func (l *Logger) HandleHTTPRequest(r *http.Request) *LogProcess {
// create the start time
st := time.Now()
// attempt to create a span using a parent span defined in http headers
var serverSpan opentracing.Span
wireContext, err := opentracing.GlobalTracer().Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.Header),
)
if err != nil {
// if there is no span in the headers an error will be raised, log
// this error
l.log.Debug("Error obtaining context, creating new span", "error", err)
}
// Create the span referring to the RPC client if available.
// If wireContext == nil, a root span will be created.
serverSpan = opentracing.StartSpan(
"handle_request",
ext.RPCServerOption(wireContext))
serverSpan.LogFields(log.String("service.type", "http"))
l.log.Info("Handle inbound request",
l.logFieldsWithSpanID(
serverSpan.Context(),
"request", formatRequest(r),
)...,
)
// return an object which can be used to set metadata onto the trace and
// complete
return &LogProcess{
finished: func(err error, meta map[string]string) {
te := time.Now()
// if there was an error add this to the trace
// and log
if err != nil {
serverSpan.SetTag("error", true)
serverSpan.LogFields(log.Error(err))
l.log.Error(
"Error handling request",
l.logFieldsWithSpanID(
serverSpan.Context(),
"error", err,
)...,
)
}
// add metadata to the trace and stats
for k, v := range meta {
serverSpan.SetTag(k, v)
}
dur := te.Sub(st)
l.log.Info(
"Finished handling request",
l.logFieldsWithSpanID(
serverSpan.Context(),
"duration", dur,
)...,
)
serverSpan.Finish()
l.metrics.Timing("handle.request.http", dur, getTags(err, meta))
},
Span: serverSpan,
}
}
func (l *Logger) HandleGRCPRequest(ctx context.Context) *LogProcess {
st := time.Now()
// we need to convert the metadata to a httpRequest to extract the span
md, _ := metadata.FromIncomingContext(ctx)
r := grpcMetaDataToHTTPRequest(md)
var serverSpan opentracing.Span
wireContext, err := opentracing.GlobalTracer().Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.Header),
)
if err != nil {
// Optionally record something about err here
l.log.Debug("Error obtaining context, creating new span", "error", err)
}
// Create the span referring to the RPC client if available.
// If wireContext == nil, a root span will be created.
serverSpan = opentracing.StartSpan(
"handle_request",
ext.RPCServerOption(wireContext))
serverSpan.LogFields(log.String("service.type", "grpc"))
l.log.Info(
"Handling request gRPC request",
l.logFieldsWithSpanID(
serverSpan.Context(),
"context", printContext(ctx),
)...,
)
return &LogProcess{
finished: func(err error, meta map[string]string) {
te := time.Now()
// if there was an error add this to the trace
// and log
if err != nil {
serverSpan.SetTag("error", true)
serverSpan.LogFields(log.Error(err))
l.log.Error(
"Error handling request",
l.logFieldsWithSpanID(
serverSpan.Context(),
"error", err,
)...,
)
}
// add metadata to the trace and stats
for k, v := range meta {
serverSpan.SetTag(k, v)
}
dur := te.Sub(st)
l.log.Info(
"Finished handling request",
l.logFieldsWithSpanID(
serverSpan.Context(),
"duration", dur,
)...,
)
serverSpan.Finish()
l.metrics.Timing("handle.request.grpc", dur, getTags(err, meta))
},
Span: serverSpan,
}
}
// Logs data about service duration simulation
func (l *Logger) SleepService(parentSpan opentracing.Span, d time.Duration) *LogProcess {
sp := parentSpan.Tracer().StartSpan(
"service_delay",
opentracing.ChildOf(parentSpan.Context()),
)
sp.LogFields(log.String("randomized_duration", d.String()))
l.log.Info(
"Sleeping for",
l.logFieldsWithSpanID(
parentSpan.Context(),
"duration", d.String(),
)...,
)
return &LogProcess{
finished: func(err error, meta map[string]string) {
sp.Finish()
},
Span: sp,
}
}
// Logs data regarding upstream http requests
func (l *Logger) CallHTTPUpstream(parentRequest *http.Request, upstreamRequest *http.Request, ctx opentracing.SpanContext) *LogProcess {
st := time.Now()
clientSpan := opentracing.StartSpan(
"call_upstream",
opentracing.ChildOf(ctx),
)
clientSpan.LogFields(log.String("upstream.type", "http"))
ext.SpanKindRPCClient.Set(clientSpan)
ext.HTTPUrl.Set(clientSpan, upstreamRequest.URL.String())
ext.HTTPMethod.Set(clientSpan, upstreamRequest.Method)
// Transmit the span's TraceContext as HTTP headers on our
// outbound request.
opentracing.GlobalTracer().Inject(
clientSpan.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(upstreamRequest.Header))
// add tracing to the http request to log connection instantiation, etc
trace := &httptrace.ClientTrace{
GotConn: func(connInfo httptrace.GotConnInfo) {
l.log.Debug("Got connection for upstream request", "idle", connInfo.WasIdle, "reused", connInfo.Reused)
if !connInfo.WasIdle {
l.metrics.Increment("upstream.request.http.connection.created", nil)
} else {
l.metrics.Increment("upstream.request.http.connection.reused", nil)
}
},
PutIdleConn: func(err error) {
l.log.Debug("Returned connection to pool", "error", err)
},
}
*upstreamRequest = *upstreamRequest.WithContext(httptrace.WithClientTrace(upstreamRequest.Context(), trace))
l.log.Info(
"Calling upstream service",
l.logFieldsWithSpanID(
ctx,
"uri", upstreamRequest.URL.String(),
"type", "HTTP",
"request", formatRequest(upstreamRequest),
)...,
)
return &LogProcess{
finished: func(err error, meta map[string]string) {
te := time.Now()
// if there was an error add this to the trace
// and log
if err != nil {
clientSpan.SetTag("error", true)
clientSpan.LogFields(log.Error(err))
l.log.Error(
"Error processing upstream request",
l.logFieldsWithSpanID(
clientSpan.Context(),
"error", err,
)...,
)
}
// add metadata to the trace and stats
for k, v := range meta {
clientSpan.SetTag(k, v)
}
l.metrics.Timing("upstream.request.http", te.Sub(st), getTags(err, meta))
clientSpan.Finish()
},
}
}
// Logs data regarding upstream grpc requests
// returns a context containing span context for tracing
func (l *Logger) CallGRCPUpstream(uri string, ctx opentracing.SpanContext) (*LogProcess, context.Context) {
st := time.Now()
clientSpan := opentracing.StartSpan(
"call_upstream",
opentracing.ChildOf(ctx),
)
ext.SpanKindRPCClient.Set(clientSpan)
// add the upstream type
clientSpan.LogFields(log.String("upstream.type", "grpc"))
req := &http.Request{Header: http.Header{}}
opentracing.GlobalTracer().Inject(
clientSpan.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(req.Header))
// create the grpc metadata and inject the client span
md := httpRequestToGrpcMetadata(req)
outCtx := metadata.NewOutgoingContext(context.Background(), md)
l.log.Info(
"Calling upstream service",
l.logFieldsWithSpanID(
clientSpan.Context(),
"uri", uri,
"type", "gRPC",
)...,
)
return &LogProcess{
finished: func(err error, meta map[string]string) {
te := time.Now()
// if there was an error add this to the trace
// and log
if err != nil {
clientSpan.LogFields(log.Error(err))
clientSpan.SetTag("error", true)
l.log.Error(
"Error processing upstream request",
l.logFieldsWithSpanID(
clientSpan.Context(),
"error", err,
)...,
)
}
// add metadata to the trace and stats
for k, v := range meta {
clientSpan.SetTag(k, v)
}
l.metrics.Timing("upstream.request.grpc", te.Sub(st), getTags(err, meta))
clientSpan.Finish()
},
}, outCtx
}
func (l *Logger) CallHealthHTTP() *LogProcess {
st := time.Now()
l.log.Info("Handling health request")
return &LogProcess{
finished: func(err error, meta map[string]string) {
te := time.Now()
l.metrics.Timing("handle.health.http", te.Sub(st), getTags(err, meta))
},
}
}
func (l *Logger) CallReadyHTTP() *LogProcess {
st := time.Now()
l.log.Info("Handling ready request")
return &LogProcess{
finished: func(err error, meta map[string]string) {
te := time.Now()
l.metrics.Timing("handle.ready.http", te.Sub(st), getTags(err, meta))
},
}
}
// formatRequest generates ascii representation of a request
func formatRequest(r *http.Request) string {
// Create return string
var request []string
// Add the request string
url := fmt.Sprintf("%v %v %v", r.Method, r.URL, r.Proto)
request = append(request, url)
// Add the host
request = append(request, fmt.Sprintf("Host: %v", r.Host))
// Loop through headers
for name, headers := range r.Header {
name = strings.ToLower(name)
for _, h := range headers {
request = append(request, fmt.Sprintf("%v: %v", name, h))
}
}
// If this is a POST, add post data
if r.Method == "POST" {
r.ParseForm()
request = append(request, "\n")
request = append(request, r.Form.Encode())
}
// Return the request as a string
return strings.Join(request, "\n")
}
// the following two functions are a hack to get round that
// opentracing zipkin can not deal with grpc metadata for
// Inject and extract
func grpcMetaDataToHTTPRequest(md metadata.MD) *http.Request {
h := http.Header{}
for k, v := range md {
for _, vv := range v {
h.Add(k, vv)
}
}
return &http.Request{Header: h}
}
func httpRequestToGrpcMetadata(r *http.Request) metadata.MD {
md := metadata.MD{}
for k, v := range r.Header {
md.Set(k, v...)
}
return md
}
// debug function to print gRPC request metadata
func printContext(ctx context.Context) string {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return "No metadata in context"
}
ret := ""
for k, v := range md {
ret += fmt.Sprintf("key: %s value: %s\n", k, v)
}
return ret
}
// utility function to add the span and trace id to the log record
func (l *Logger) logFieldsWithSpanID(ctx opentracing.SpanContext, fields ...interface{}) []interface{} {
if l.getSpanDetails != nil {
sd := l.getSpanDetails(ctx)
fields = append(fields, "span_id")
fields = append(fields, sd.SpanID)
fields = append(fields, "trace_id")
fields = append(fields, sd.TraceID)
}
return fields
}
func getTags(err error, meta map[string]string) []string {
tags := []string{}
for k, v := range meta {
tags = append(tags, fmt.Sprintf("%s:%s", k, v))
}
if err != nil {
tags = append(tags, "error:true")
}
return tags
}