-
Notifications
You must be signed in to change notification settings - Fork 21
/
basculeLogging.go
80 lines (68 loc) · 2.15 KB
/
basculeLogging.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
// SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"fmt"
"net/http"
"net/textproto"
"strings"
"time"
"github.com/xmidt-org/candlelight"
"github.com/xmidt-org/sallust"
"go.uber.org/zap"
// nolint:staticcheck
)
func sanitizeHeaders(headers http.Header) (filtered http.Header) {
filtered = headers.Clone()
if authHeader := filtered.Get("Authorization"); authHeader != "" {
filtered.Del("Authorization")
parts := strings.Split(authHeader, " ")
if len(parts) == 2 {
filtered.Set("Authorization-Type", parts[0])
}
}
return
}
func setLogger(logger *zap.Logger, lf ...LoggerFunc) func(delegate http.Handler) http.Handler {
return func(delegate http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
kvs := []interface{}{"requestHeaders", sanitizeHeaders(r.Header), "requestURL", r.URL.EscapedPath(), "method", r.Method, "requestURI", r.RequestURI, "remoteAddr", r.RemoteAddr}
if len(lf) > 0 {
for _, l := range lf {
kvs = append(kvs, l(kvs, r))
}
}
kvs, _ = candlelight.AppendTraceInfo(r.Context(), kvs)
ctx := r.Context()
ctx = addFieldsToLog(ctx, logger, kvs)
delegate.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func getLogger(ctx context.Context) *zap.Logger {
logger := sallust.Get(ctx).With(zap.Time("ts", time.Now().UTC())).WithOptions(zap.WithCaller(true))
return logger
}
func header(headerName, keyName string) LoggerFunc {
headerName = textproto.CanonicalMIMEHeaderKey(headerName)
return func(kv []interface{}, request *http.Request) []interface{} {
values := request.Header[headerName]
switch len(values) {
case 0:
return append(kv, keyName, "")
case 1:
return append(kv, keyName, values[0])
default:
return append(kv, keyName, values)
}
}
}
type LoggerFunc func([]interface{}, *http.Request) []interface{}
func addFieldsToLog(ctx context.Context, logger *zap.Logger, kvs []interface{}) context.Context {
for i := 0; i <= len(kvs)-2; i += 2 {
logger = logger.With(zap.Any(fmt.Sprint(kvs[i]), kvs[i+1]))
}
return sallust.With(ctx, logger)
}