forked from GoogleCloudPlatform/functions-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.go
More file actions
206 lines (181 loc) · 4.89 KB
/
logging.go
File metadata and controls
206 lines (181 loc) · 4.89 KB
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
package funcframework
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"regexp"
"sync"
"time"
)
var (
loggingIDsContextKey contextKey = "loggingIDs"
validXCloudTraceContext = regexp.MustCompile(
// Matches on "TRACE_ID"
`([a-f\d]+)?` +
// Matches on "/SPAN_ID"
`(?:/([a-f\d]+))?` +
// Matches on ";0=TRACE_TRUE"
`(?:;o=(\d))?`)
)
type loggingIDs struct {
trace string
spanID string
executionID string
}
type contextKey string
func addLoggingIDsToRequest(r *http.Request) *http.Request {
executionID := r.Header.Get("Function-Execution-Id")
if executionID == "" {
timestamp := time.Now().UnixNano()
random := rand.Int63()
executionID = fmt.Sprintf("%06x%06x", timestamp, random)
}
traceID, spanID, _ := deconstructXCloudTraceContext(r.Header.Get("X-Cloud-Trace-Context"))
if executionID == "" && traceID == "" && spanID == "" {
return r
}
r = r.WithContext(contextWithLoggingIDs(r.Context(), &loggingIDs{
trace: traceID,
spanID: spanID,
executionID: executionID,
}))
return r
}
func contextWithLoggingIDs(ctx context.Context, loggingIDs *loggingIDs) context.Context {
return context.WithValue(ctx, loggingIDsContextKey, loggingIDs)
}
func loggingIDsFromContext(ctx context.Context) *loggingIDs {
val := ctx.Value(loggingIDsContextKey)
if val == nil {
return nil
}
return val.(*loggingIDs)
}
func TraceIDFromContext(ctx context.Context) string {
ids := loggingIDsFromContext(ctx)
if ids == nil {
return ""
}
return ids.trace
}
func ExecutionIDFromContext(ctx context.Context) string {
ids := loggingIDsFromContext(ctx)
if ids == nil {
return ""
}
return ids.executionID
}
func SpanIDFromContext(ctx context.Context) string {
ids := loggingIDsFromContext(ctx)
if ids == nil {
return ""
}
return ids.spanID
}
func deconstructXCloudTraceContext(s string) (traceID, spanID string, traceSampled bool) {
// As per the format described at https://cloud.google.com/trace/docs/setup#force-trace
// "X-Cloud-Trace-Context: TRACE_ID/SPAN_ID;o=TRACE_TRUE"
// for example:
// "X-Cloud-Trace-Context: 105445aa7843bc8bf206b120001000/1;o=1"
matches := validXCloudTraceContext.FindStringSubmatch(s)
if matches != nil {
traceID, spanID, traceSampled = matches[1], matches[2], matches[3] == "1"
}
if spanID == "0" {
spanID = ""
}
return
}
// structuredLogEvent declares a subset of the fields supported by cloudlogging structured log events.
// See https://cloud.google.com/logging/docs/structured-logging.
type structuredLogEvent struct {
Message string `json:"message"`
Trace string `json:"logging.googleapis.com/trace,omitempty"`
SpanID string `json:"logging.googleapis.com/spanId,omitempty"`
Labels map[string]string `json:"logging.googleapis.com/labels,omitempty"`
}
// structuredLogWriter writes structured logs
type structuredLogWriter struct {
mu sync.Mutex
w io.Writer
loggingIDs loggingIDs
buf []byte
}
func (w *structuredLogWriter) writeStructuredLog(loggingIDs loggingIDs, message string) (int, error) {
event := structuredLogEvent{
Message: message,
Trace: loggingIDs.trace,
SpanID: loggingIDs.spanID,
}
if loggingIDs.executionID != "" {
event.Labels = map[string]string{
"execution_id": loggingIDs.executionID,
}
}
marshalled, err := json.Marshal(event)
if err != nil {
return 0, err
}
marshalled = append(marshalled, '\n')
return w.w.Write(marshalled)
}
func (w *structuredLogWriter) Write(output []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
w.buf = append(w.buf, output...)
buf := w.buf
wroteLines := 0
for {
advance, token, err := bufio.ScanLines(buf, false)
if token == nil || err != nil {
break
}
buf = buf[advance:]
if _, err := w.writeStructuredLog(w.loggingIDs, string(token)); err != nil {
return 0, err
}
wroteLines += 1
}
if wroteLines > 0 {
// Compact the buffer by copying remaining bytes to the start.
w.buf = append(w.buf[:0], buf...)
}
return len(output), nil
}
func (w *structuredLogWriter) Close() error {
if len(w.buf) == 0 {
return nil
}
_, err := w.writeStructuredLog(w.loggingIDs, string(w.buf))
return err
}
// LogWriter returns an io.Writer as a log sink for the request context.
// One log event is generated for each new line terminated byte sequence
// written to the io.Writer.
//
// This can be used with common logging frameworks, for example:
//
// import (
// "log"
// "github.com/GoogleCloudPlatform/functions-framework-go/funcframework"
// )
// ...
// func helloWorld(w http.ResponseWriter, r *http.Request) {
// l := log.New(funcframework.LogWriter(r.Context()), "", 0)
// l.Println("hello world!")
// }
func LogWriter(ctx context.Context) io.WriteCloser {
loggingIDs := loggingIDsFromContext(ctx)
if loggingIDs == nil {
return os.Stderr
}
return &structuredLogWriter{
w: os.Stderr,
loggingIDs: *loggingIDs,
}
}