This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 302
/
logger.go
178 lines (153 loc) · 4.7 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
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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package logging sets up and configures logging.
package logging
import (
"context"
"fmt"
"sync"
"time"
"go.opencensus.io/trace"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// contextKey is a private string type to prevent collisions in the context map.
type contextKey string
// loggerKey points to the value in the context where the logger is stored.
const loggerKey = contextKey("logger")
var (
// defaultLogger is the default logger. It is initialized once per package
// include upon calling DefaultLogger.
defaultLogger *zap.SugaredLogger
defaultLoggerOnce sync.Once
)
// NewLogger creates a new logger with the given configuration.
func NewLogger(debug bool) *zap.SugaredLogger {
config := &zap.Config{
Level: zap.NewAtomicLevelAt(zap.InfoLevel),
Development: false,
Sampling: samplingConfig,
Encoding: encodingJSON,
EncoderConfig: encoderConfig,
OutputPaths: outputStderr,
ErrorOutputPaths: outputStderr,
}
// Add more details if logging is in debug mode.
if debug {
config.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
config.Development = true
config.Sampling = nil
}
logger, err := config.Build()
if err != nil {
logger = zap.NewNop()
}
return logger.Sugar()
}
// DefaultLogger returns the default logger for the package.
func DefaultLogger() *zap.SugaredLogger {
defaultLoggerOnce.Do(func() {
defaultLogger = NewLogger(false)
})
return defaultLogger
}
// WithLogger creates a new context with the provided logger attached.
func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context {
return context.WithValue(ctx, loggerKey, logger)
}
// FromContext returns the logger stored in the context. If no such logger
// exists, a default logger is returned.
func FromContext(ctx context.Context) *zap.SugaredLogger {
if logger, ok := ctx.Value(loggerKey).(*zap.SugaredLogger); ok {
return logger
}
return DefaultLogger()
}
const (
timestamp = "timestamp"
severity = "severity"
logger = "logger"
caller = "caller"
message = "message"
stacktrace = "stacktrace"
levelDebug = "DEBUG"
levelInfo = "INFO"
levelWarning = "WARNING"
levelError = "ERROR"
levelCritical = "CRITICAL"
levelAlert = "ALERT"
levelEmergency = "EMERGENCY"
encodingJSON = "json"
)
var outputStderr = []string{"stderr"}
var encoderConfig = zapcore.EncoderConfig{
TimeKey: timestamp,
LevelKey: severity,
NameKey: logger,
CallerKey: caller,
MessageKey: message,
StacktraceKey: stacktrace,
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: levelEncoder(),
EncodeTime: timeEncoder(),
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
var samplingConfig = &zap.SamplingConfig{
Initial: 250,
Thereafter: 250,
}
// levelEncoder transforms a zap level to the associated stackdriver level.
func levelEncoder() zapcore.LevelEncoder {
return func(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
switch l {
case zapcore.DebugLevel:
enc.AppendString(levelDebug)
case zapcore.InfoLevel:
enc.AppendString(levelInfo)
case zapcore.WarnLevel:
enc.AppendString(levelWarning)
case zapcore.ErrorLevel:
enc.AppendString(levelError)
case zapcore.DPanicLevel:
enc.AppendString(levelCritical)
case zapcore.PanicLevel:
enc.AppendString(levelAlert)
case zapcore.FatalLevel:
enc.AppendString(levelEmergency)
}
}
}
// TraceFromContext adds the correct Stackdriver trace fields.
//
// see: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
func TraceFromContext(ctx context.Context) []zap.Field {
span := trace.FromContext(ctx)
if span == nil {
return nil
}
sc := span.SpanContext()
return []zap.Field{
// TODO(icco): Figure out how to add project ID to this.
zap.String("trace", fmt.Sprintf("traces/%s", sc.TraceID)),
zap.String("spanId", sc.SpanID.String()),
zap.Bool("traceSampled", sc.IsSampled()),
}
}
// timeEncoder encodes the time as RFC3339 nano
func timeEncoder() zapcore.TimeEncoder {
return func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format(time.RFC3339Nano))
}
}