forked from ruiaylin/pgparser
/
trace.go
312 lines (281 loc) · 10.2 KB
/
trace.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
// Copyright 2016 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package log
import (
"context"
"strconv"
"strings"
"github.com/ruiaylin/pgparser/utils/syncutil"
"github.com/ruiaylin/pgparser/utils/tracing"
"github.com/cockroachdb/logtags"
"github.com/cockroachdb/redact"
opentracing "github.com/opentracing/opentracing-go"
otlog "github.com/opentracing/opentracing-go/log"
"golang.org/x/net/trace"
)
// ctxEventLogKey is an empty type for the handle associated with the
// ctxEventLog value (see context.Value).
type ctxEventLogKey struct{}
// ctxEventLog is used for contexts to keep track of an EventLog.
type ctxEventLog struct {
syncutil.Mutex
eventLog trace.EventLog
}
func (el *ctxEventLog) finish() {
el.Lock()
if el.eventLog != nil {
el.eventLog.Finish()
el.eventLog = nil
}
el.Unlock()
}
func embedCtxEventLog(ctx context.Context, el *ctxEventLog) context.Context {
return context.WithValue(ctx, ctxEventLogKey{}, el)
}
// withEventLogInternal embeds a trace.EventLog in the context, causing future
// logging and event calls to go to the EventLog. The current context must not
// have an existing open span.
func withEventLogInternal(ctx context.Context, eventLog trace.EventLog) context.Context {
if opentracing.SpanFromContext(ctx) != nil {
panic("event log under span")
}
return embedCtxEventLog(ctx, &ctxEventLog{eventLog: eventLog})
}
// WithEventLog creates and embeds a trace.EventLog in the context, causing
// future logging and event calls to go to the EventLog. The current context
// must not have an existing open span.
func WithEventLog(ctx context.Context, family, title string) context.Context {
return withEventLogInternal(ctx, trace.NewEventLog(family, title))
}
var _ = WithEventLog
// WithNoEventLog creates a context which no longer has an embedded event log.
func WithNoEventLog(ctx context.Context) context.Context {
return withEventLogInternal(ctx, nil)
}
func eventLogFromCtx(ctx context.Context) *ctxEventLog {
if val := ctx.Value(ctxEventLogKey{}); val != nil {
return val.(*ctxEventLog)
}
return nil
}
// FinishEventLog closes the event log in the context (see WithEventLog).
// Concurrent and subsequent calls to record events are allowed.
func FinishEventLog(ctx context.Context) {
if el := eventLogFromCtx(ctx); el != nil {
el.finish()
}
}
// getSpanOrEventLog returns the current Span. If there is no Span, it returns
// the current ctxEventLog. If neither (or the Span is "black hole"), returns
// false.
func getSpanOrEventLog(ctx context.Context) (opentracing.Span, *ctxEventLog, bool) {
if sp := opentracing.SpanFromContext(ctx); sp != nil {
if tracing.IsBlackHoleSpan(sp) {
return nil, nil, false
}
return sp, nil, true
}
if el := eventLogFromCtx(ctx); el != nil {
return nil, el, true
}
return nil, nil, false
}
// eventInternal is the common code for logging an event. If no args are given,
// the format is treated as a pre-formatted string.
//
// Note that when called from a logging function, this is taking the log
// message as input after introduction of redaction markers. This
// means the message may or may not contain markers already depending
// of the configuration of --redactable-logs.
//
// TODO(knz): change the interface to take a log.Entry
// as input instead.
func eventInternal(sp opentracing.Span, el *ctxEventLog, isErr bool, entry Entry) {
var msg string
if len(entry.Tags) == 0 && len(entry.File) == 0 && !entry.Redactable {
// Shortcut.
msg = entry.Message
} else {
var buf strings.Builder
if len(entry.File) != 0 {
buf.WriteString(entry.File)
buf.WriteByte(':')
// TODO(knz): The "canonical" way to represent a file/line prefix
// is: <file>:<line>: msg
// with a colon between the line number and the message.
// However, some location filter deep inside SQL doesn't
// understand a colon after the line number.
buf.WriteString(strconv.FormatInt(entry.Line, 10))
buf.WriteByte(' ')
}
if len(entry.Tags) > 0 {
buf.WriteByte('[')
buf.WriteString(entry.Tags)
buf.WriteString("] ")
}
buf.WriteString(entry.Message)
msg = buf.String()
if entry.Redactable {
// This is true when eventInternal is called from addStructured(),
// ie. a regular log call. In this case, the tags and message may contain
// redaction markers. We remove them here.
msg = redact.RedactableString(msg).StripMarkers()
}
}
if sp != nil {
// TODO(radu): pass tags directly to sp.LogKV when LightStep supports
// that.
sp.LogFields(otlog.String(tracing.LogMessageField, msg))
// if isErr {
// // TODO(radu): figure out a way to signal that this is an error. We
// // could use a different "error" key (provided it shows up in
// // LightStep). Things like NetTraceIntegrator would need to be modified
// // to understand the difference. We could also set a special Tag or
// // Baggage on the span. See #8827 for more discussion.
// }
} else {
el.Lock()
if el.eventLog != nil {
if isErr {
el.eventLog.Errorf("%s", msg)
} else {
el.eventLog.Printf("%s", msg)
}
}
el.Unlock()
}
}
// formatTags appends the tags to a strings.Builder. If there are no tags,
// returns false.
func formatTags(ctx context.Context, brackets bool, buf *strings.Builder) bool {
tags := logtags.FromContext(ctx)
if tags == nil {
return false
}
if brackets {
buf.WriteByte('[')
}
tags.FormatToString(buf)
if brackets {
buf.WriteString("] ")
}
return true
}
// Event looks for an opentracing.Trace in the context and logs the given
// message to it. If no Trace is found, it looks for an EventLog in the context
// and logs the message to it. If neither is found, does nothing.
func Event(ctx context.Context, msg string) {
sp, el, ok := getSpanOrEventLog(ctx)
if !ok {
// Nothing to log. Skip the work.
return
}
// Format the tracing event and add it to the trace.
entry := MakeEntry(ctx,
Severity_INFO, /* unused for trace events */
nil, /* logCounter, unused for trace events */
1, /* depth */
// redactable is false because we want to flatten the data in traces
// -- we don't have infrastructure yet for trace redaction.
false, /* redactable */
"")
entry.Message = msg
eventInternal(sp, el, false /* isErr */, entry)
}
// Eventf looks for an opentracing.Trace in the context and formats and logs
// the given message to it. If no Trace is found, it looks for an EventLog in
// the context and logs the message to it. If neither is found, does nothing.
func Eventf(ctx context.Context, format string, args ...interface{}) {
sp, el, ok := getSpanOrEventLog(ctx)
if !ok {
// Nothing to log. Skip the work.
return
}
// Format the tracing event and add it to the trace.
entry := MakeEntry(ctx,
Severity_INFO, /* unused for trace events */
nil, /* logCounter, unused for trace events */
1, /* depth */
// redactable is false because we want to flatten the data in traces
// -- we don't have infrastructure yet for trace redaction.
false, /* redactable */
format, args...)
eventInternal(sp, el, false /* isErr */, entry)
}
func vEventf(
ctx context.Context, isErr bool, depth int, level Level, format string, args ...interface{},
) {
if VDepth(level, 1+depth) {
// Log the message (which also logs an event).
sev := Severity_INFO
if isErr {
sev = Severity_ERROR
}
logDepth(ctx, 1+depth, sev, format, args)
} else {
sp, el, ok := getSpanOrEventLog(ctx)
if !ok {
// Nothing to log. Skip the work.
return
}
entry := MakeEntry(ctx,
Severity_INFO, /* unused for trace events */
nil, /* logCounter, unused for trace events */
depth+1,
// redactable is false because we want to flatten the data in traces
// -- we don't have infrastructure yet for trace redaction.
false, /* redactable */
format, args...)
eventInternal(sp, el, isErr, entry)
}
}
// VEvent either logs a message to the log files (which also outputs to the
// active trace or event log) or to the trace/event log alone, depending on
// whether the specified verbosity level is active.
func VEvent(ctx context.Context, level Level, msg string) {
vEventf(ctx, false /* isErr */, 1, level, msg)
}
// VEventf either logs a message to the log files (which also outputs to the
// active trace or event log) or to the trace/event log alone, depending on
// whether the specified verbosity level is active.
func VEventf(ctx context.Context, level Level, format string, args ...interface{}) {
vEventf(ctx, false /* isErr */, 1, level, format, args...)
}
// VEventfDepth performs the same as VEventf but checks the verbosity level
// at the given depth in the call stack.
func VEventfDepth(ctx context.Context, depth int, level Level, format string, args ...interface{}) {
vEventf(ctx, false /* isErr */, 1+depth, level, format, args...)
}
// VErrEvent either logs an error message to the log files (which also outputs
// to the active trace or event log) or to the trace/event log alone, depending
// on whether the specified verbosity level is active.
func VErrEvent(ctx context.Context, level Level, msg string) {
vEventf(ctx, true /* isErr */, 1, level, msg)
}
// VErrEventf either logs an error message to the log files (which also outputs
// to the active trace or event log) or to the trace/event log alone, depending
// on whether the specified verbosity level is active.
func VErrEventf(ctx context.Context, level Level, format string, args ...interface{}) {
vEventf(ctx, true /* isErr */, 1, level, format, args...)
}
// VErrEventfDepth performs the same as VErrEventf but checks the verbosity
// level at the given depth in the call stack.
func VErrEventfDepth(
ctx context.Context, depth int, level Level, format string, args ...interface{},
) {
vEventf(ctx, true /* isErr */, 1+depth, level, format, args...)
}
var _ = VErrEventfDepth // silence unused warning
// HasSpanOrEvent returns true if the context has a span or event that should
// be logged to.
func HasSpanOrEvent(ctx context.Context) bool {
_, _, ok := getSpanOrEventLog(ctx)
return ok
}