-
Notifications
You must be signed in to change notification settings - Fork 52
/
logger.go
73 lines (62 loc) · 1.64 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
package scope
import (
"context"
"net/http"
"github.com/lomik/graphite-clickhouse/helper/headers"
"github.com/lomik/zapwriter"
"go.uber.org/zap"
)
var (
CarbonapiUUIDName = "carbonapi_uuid"
RequestHeadersName = "request_headers"
)
// Logger returns zap.Logger instance
func Logger(ctx context.Context) *zap.Logger {
logger := ctx.Value(scopeKey("logger"))
var zapLogger *zap.Logger
if logger != nil {
if zl, ok := logger.(*zap.Logger); ok {
zapLogger = zl
return zapLogger
}
}
if zapLogger == nil {
zapLogger = zapwriter.Default()
}
requestId := RequestID(ctx)
if requestId != "" {
zapLogger = zapLogger.With(zap.String("request_id", requestId))
}
return zapLogger
}
// Logger returns zap.Logger instance
func LoggerWithHeaders(ctx context.Context, r *http.Request, headersToLog []string) *zap.Logger {
logger := ctx.Value(scopeKey("logger"))
var zapLogger *zap.Logger
if logger != nil {
if zl, ok := logger.(*zap.Logger); ok {
zapLogger = zl
return zapLogger
}
}
if zapLogger == nil {
zapLogger = zapwriter.Default()
}
requestId := RequestID(ctx)
if requestId != "" {
zapLogger = zapLogger.With(zap.String("request_id", requestId))
}
carbonapiUUID := r.Header.Get("X-Ctx-Carbonapi-Uuid")
if carbonapiUUID != "" {
zapLogger = zapLogger.With(zap.String("carbonapi_uuid", carbonapiUUID))
}
requestHeaders := headers.GetHeaders(&r.Header, headersToLog)
if len(requestHeaders) > 0 {
zapLogger = zapLogger.With(zap.Any("request_headers", requestHeaders))
}
return zapLogger
}
// WithLogger ...
func WithLogger(ctx context.Context, logger *zap.Logger) context.Context {
return With(ctx, "logger", logger)
}