-
Notifications
You must be signed in to change notification settings - Fork 2
/
aeloggingstackdriver.go
362 lines (304 loc) · 10.1 KB
/
aeloggingstackdriver.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
package appwrap
import (
"bytes"
"context"
"fmt"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
"cloud.google.com/go/logging"
"google.golang.org/api/option"
mrpb "google.golang.org/genproto/googleapis/api/monitoredres"
logtypepb "google.golang.org/genproto/googleapis/logging/type"
)
var loggingCtxKey = struct{ k string }{"hlog context key"}
const IPListHeader = "X-Forwarded-For"
type loggingCtxValue struct {
aeInfo AppengineInfo
hreq *http.Request
labels map[string]string
logger *logging.Logger
parent string
sev logtypepb.LogSeverity
trace string
}
// statusWriter pulled from here - used to keep track of size of response and the response code.
// https://www.reddit.com/r/golang/comments/7p35s4/how_do_i_get_the_response_status_for_my_middleware/dse625w/?context=8&depth=9
type statusWriter struct {
http.ResponseWriter
status int
length int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = 200
}
n, err := w.ResponseWriter.Write(b)
w.length += n
return n, err
}
const (
// thresholds that, when reached, cause a flush of logs to be sent over grpc
loggingFlushTimeTrigger = 5 * time.Second
loggingFlushSizeTrigger = 5 << 20
loggingFlushCountTrigger = 5000
)
func resourceLabels(aeInfo AppengineInfo) map[string]string {
if InKubernetes() {
return map[string]string{
"project_id": aeInfo.DataProjectID(),
"namespace_name": aeInfo.DataProjectID(),
"pod_name": aeInfo.InstanceID(),
}
} else {
return map[string]string{
"module_id": aeInfo.ModuleName(),
"version_id": aeInfo.VersionID(),
"project_id": aeInfo.NativeProjectID(),
}
}
}
func getLogger(aeInfo AppengineInfo, lc *logging.Client, logName string) *logging.Logger {
return lc.Logger(logName, logging.CommonResource(&mrpb.MonitoredResource{
Type: monitoredType(),
Labels: resourceLabels(aeInfo),
}), logging.DelayThreshold(loggingFlushTimeTrigger), logging.EntryByteThreshold(loggingFlushSizeTrigger), logging.EntryCountThreshold(loggingFlushCountTrigger))
}
func getLogCtxVal(aeInfo AppengineInfo, hreq *http.Request, logger *logging.Logger, trace string) *loggingCtxValue {
var remoteIp string
if addr := hreq.Header.Get(IPListHeader); addr != "" {
remoteIp = strings.Split(addr, ",")[0]
}
labels := map[string]string{
"appengine.googleapis.com/instance_name": aeInfo.InstanceID(),
"pendo_io_service": aeInfo.ModuleName(),
"pendo_io_version": aeInfo.VersionID(),
"pendo_io_request_host": hreq.Host,
"pendo_io_request_method": hreq.Method,
"pendo_io_request_url": hreq.URL.String(),
"pendo_io_remote_ip": remoteIp,
"pendo_io_useragent": hreq.UserAgent(),
}
tlsVersionHeader, tlsCipherSuiteHeader := hreq.Header.Get("X-Client-TLS-Version"), hreq.Header.Get("X-Client-Cipher-Suite")
if tlsVersionHeader != "" {
labels["pendo_io_client_tls_version"] = tlsVersionHeader
}
if tlsCipherSuiteHeader != "" {
labels["pendo_io_client_cipher_suite"] = tlsCipherSuiteHeader
}
return &loggingCtxValue{
aeInfo: aeInfo,
hreq: hreq,
labels: labels,
logger: logger,
trace: trace,
}
}
// for use in flex services with long-running tasks that don't handle http requests
func WrapBackgroundContextWithStackdriverLogger(c context.Context, logName string) context.Context {
if IsDevAppServer {
return c
}
return wrapBackgroundContextWithStackdriverLogger(c, logName, GetOrCreateLoggingClient())
}
func wrapBackgroundContextWithStackdriverLogger(c context.Context, logName string, lc *logging.Client) context.Context {
aeInfo := NewAppengineInfoFromContext(c)
project := aeInfo.NativeProjectID()
if project == "" {
panic("aelog: no GCP project set in environment")
}
parent := "projects/" + project
if logName == "" {
logName = ChildLogName
}
req, err := http.NewRequest(http.MethodGet, "pendo.io/background", bytes.NewReader([]byte{}))
if err != nil {
panic(err)
}
return context.WithValue(c, loggingCtxKey, getLogCtxVal(aeInfo, req, getLogger(aeInfo, lc, logName), parent+"/traces/"+fmt.Sprintf("%d", rand.Int63())))
}
func WrapBackgroundContextWithStackdriverLoggerWithCloseFunc(c context.Context, logName string) (context.Context, func()) {
if IsDevAppServer {
return c, func() {}
}
aeInfo := NewAppengineInfoFromContext(c)
client, err := logging.NewClient(c, fmt.Sprintf("projects/%s", aeInfo.NativeProjectID()))
if err != nil {
panic(fmt.Sprintf("failed to create logging client %s", err.Error()))
}
ctx := wrapBackgroundContextWithStackdriverLogger(c, logName, client)
return ctx, func() {
_ = client.Close()
}
}
var sharedClientCtxKey = struct{ k string }{"shared client context key"}
type sharedClientLogCtxVal struct {
aeInfo AppengineInfo
client *logging.Client
logger *logging.Logger
parent string
parentLogger *logging.Logger
}
func AddSharedLogClientToBackgroundContext(c context.Context, logName string) context.Context {
if IsDevAppServer {
return c
}
aeInfo := NewAppengineInfoFromContext(c)
project := aeInfo.NativeProjectID()
if project == "" {
panic("aelog: no GCP project set in environment")
}
parent := "projects/" + project
lc := GetOrCreateLoggingClient()
if logName == "" {
logName = ChildLogName
}
logger := getLogger(aeInfo, lc, logName)
parentLogger := getLogger(aeInfo, lc, requestLogPath)
return context.WithValue(c, sharedClientCtxKey, &sharedClientLogCtxVal{
aeInfo: aeInfo,
client: lc,
logger: logger,
parent: parent,
parentLogger: parentLogger,
})
}
func RunFuncWithDedicatedLogger(c context.Context, simulatedUrl, traceId string, fn func(log Logging)) {
ctxVal := c.Value(sharedClientCtxKey)
if ctxVal == nil {
panic("must wrap context with AddSharedLogClientToBackgroundContext")
}
req, err := http.NewRequest(http.MethodGet, simulatedUrl, nil)
if err != nil {
panic(err)
}
sharedClientCtxVal := ctxVal.(*sharedClientLogCtxVal)
if traceId == "" {
traceId = strconv.FormatInt(rand.Int63(), 10)
}
logCtxVal := getLogCtxVal(sharedClientCtxVal.aeInfo, req, sharedClientCtxVal.logger, sharedClientCtxVal.parent+"/traces/"+traceId)
fctx := context.WithValue(c, loggingCtxKey, logCtxVal)
dedicatedLogger := NewStackdriverLogging(fctx)
start := time.Now()
defer func() {
sev := logging.Severity(logCtxVal.sev)
status := http.StatusOK
if sev >= logging.Error {
status = http.StatusInternalServerError
}
sharedClientCtxVal.parentLogger.Log(logging.Entry{
HTTPRequest: &logging.HTTPRequest{
Latency: time.Now().Sub(start),
ResponseSize: 0,
Request: req,
Status: status,
},
Labels: logCtxVal.getLabels(),
Severity: sev,
Timestamp: start,
Trace: logCtxVal.trace,
})
}()
fn(dedicatedLogger)
}
func WrapHandlerWithStackdriverLogger(h http.Handler, logName string, opts ...option.ClientOption) http.Handler {
if IsDevAppServer {
return h
}
ctx := context.Background()
aeInfo := NewAppengineInfoFromContext(ctx)
project := aeInfo.NativeProjectID()
if project == "" {
panic("aelog: no GCP project set in environment")
}
parent := "projects/" + project
lc := GetOrCreateLoggingClient()
if logName == "" {
logName = ChildLogName
}
logger := getLogger(aeInfo, lc, logName)
parentLogger := getLogger(aeInfo, lc, requestLogPath)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
logCtxVal := getLogCtxVal(aeInfo, r, logger, "")
traceHeader := r.Header.Get("X-Cloud-Trace-Context")
if traceHeader != "" {
logCtxVal.trace = parent + "/traces/" + strings.Split(traceHeader, "/")[0]
} else {
logCtxVal.trace = parent + "/traces/" + fmt.Sprintf("%d", rand.Int63())
}
ctx := context.WithValue(r.Context(), loggingCtxKey, logCtxVal)
sw := &statusWriter{
ResponseWriter: w,
status: http.StatusOK, // default response if we don't explicitly set one
}
h.ServeHTTP(sw, r.WithContext(ctx))
e := logging.Entry{
HTTPRequest: &logging.HTTPRequest{
Latency: time.Now().Sub(start),
ResponseSize: int64(sw.length),
Request: r,
Status: sw.status,
},
Labels: logCtxVal.getLabels(),
Severity: logging.Severity(logCtxVal.sev),
Timestamp: start,
Trace: logCtxVal.trace,
}
parentLogger.Log(e)
})
}
func IsValidLoggingContext(ctx context.Context) bool {
return ctx.Value(loggingCtxKey) != nil
}
func logFromContext(ctx context.Context, sev logtypepb.LogSeverity, format string, args ...interface{}) {
ctxVal := ctx.Value(loggingCtxKey)
if ctxVal == nil {
panic("need to wrap http handler to use stackdriver logger")
}
logCtxVal := ctxVal.(*loggingCtxValue)
e := logging.Entry{
Labels: logCtxVal.getLabels(),
Payload: truncateLog(format, args...),
Severity: logging.Severity(sev),
Timestamp: time.Now(),
Trace: logCtxVal.trace,
}
logCtxVal.logger.Log(e)
if sev > logCtxVal.sev {
logCtxVal.sev = sev
}
}
// set to 240k, slightly under real max of 256k
const maxLogLength = 240 << 10
const truncatedLogPrefix = "TRUNCATED: (full log in stderr) "
func truncateLog(format string, args ...interface{}) string {
payload := fmt.Sprintf(format, args...)
if len(payload) > maxLogLength {
_, _ = fmt.Fprintln(os.Stderr, payload)
payload = truncatedLogPrefix + payload[:maxLogLength]
}
return strings.ToValidUTF8(payload, "\uFFFD")
}
func Criticalf(ctx context.Context, format string, args ...interface{}) {
logFromContext(ctx, logtypepb.LogSeverity_CRITICAL, format, args...)
}
func Debugf(ctx context.Context, format string, args ...interface{}) {
logFromContext(ctx, logtypepb.LogSeverity_DEBUG, format, args...)
}
func Errorf(ctx context.Context, format string, args ...interface{}) {
logFromContext(ctx, logtypepb.LogSeverity_ERROR, format, args...)
}
func Infof(ctx context.Context, format string, args ...interface{}) {
logFromContext(ctx, logtypepb.LogSeverity_INFO, format, args...)
}
func Warningf(ctx context.Context, format string, args ...interface{}) {
logFromContext(ctx, logtypepb.LogSeverity_WARNING, format, args...)
}