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
204 lines (181 loc) · 5.61 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
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
// 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"
"os"
"strings"
"sync"
"time"
"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(level string, development bool) *zap.SugaredLogger {
var config *zap.Config
if development {
config = &zap.Config{
Level: zap.NewAtomicLevelAt(levelToZapLevel(level)),
Development: true,
Encoding: encodingConsole,
EncoderConfig: developmentEncoderConfig,
OutputPaths: outputStderr,
ErrorOutputPaths: outputStderr,
}
} else {
config = &zap.Config{
Level: zap.NewAtomicLevelAt(levelToZapLevel(level)),
Encoding: encodingJSON,
EncoderConfig: productionEncoderConfig,
OutputPaths: outputStderr,
ErrorOutputPaths: outputStderr,
}
}
logger, err := config.Build()
if err != nil {
logger = zap.NewNop()
}
return logger.Sugar()
}
// NewLoggerFromEnv creates a new logger from the environment. It consumes
// LOG_LEVEL for determining the level and LOG_MODE for determining the output
// parameters.
func NewLoggerFromEnv() *zap.SugaredLogger {
level := os.Getenv("LOG_LEVEL")
development := strings.ToLower(strings.TrimSpace(os.Getenv("LOG_MODE"))) == "development"
return NewLogger(level, development)
}
// DefaultLogger returns the default logger for the package.
func DefaultLogger() *zap.SugaredLogger {
defaultLoggerOnce.Do(func() {
defaultLogger = NewLoggerFromEnv()
})
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"
encodingConsole = "console"
encodingJSON = "json"
)
var outputStderr = []string{"stderr"}
var productionEncoderConfig = 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 developmentEncoderConfig = zapcore.EncoderConfig{
TimeKey: "",
LevelKey: "L",
NameKey: "N",
CallerKey: "C",
FunctionKey: zapcore.OmitKey,
MessageKey: "M",
StacktraceKey: "S",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
// levelToZapLevel converts the given string to the appropriate zap level
// value.
func levelToZapLevel(s string) zapcore.Level {
switch strings.ToUpper(strings.TrimSpace(s)) {
case levelDebug:
return zapcore.DebugLevel
case levelInfo:
return zapcore.InfoLevel
case levelWarning:
return zapcore.WarnLevel
case levelError:
return zapcore.ErrorLevel
case levelCritical:
return zapcore.DPanicLevel
case levelAlert:
return zapcore.PanicLevel
case levelEmergency:
return zapcore.FatalLevel
}
return zapcore.WarnLevel
}
// 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)
}
}
}
// 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))
}
}