-
Notifications
You must be signed in to change notification settings - Fork 3
/
logger.go
337 lines (281 loc) · 7.54 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
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
package logger
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
type severity int
const (
DEBUG severity = iota
INFO
WARN
ERROR
CRITICAL
defaultCallerSkip = 2
)
func (s severity) String() string {
return logLevelName[s]
}
var logLevelName = [...]string{
"DEBUG",
"INFO",
"WARN",
"ERROR",
"CRITICAL",
}
var logLevelValue = map[string]severity{
"DEBUG": DEBUG,
"INFO": INFO,
"WARN": WARN,
"ERROR": ERROR,
"CRITICAL": CRITICAL,
}
// Fields is used to wrap the log entries payload
type Fields map[string]interface{}
// ServiceContext is required by the Stackdriver Error format
type ServiceContext struct {
Service string `json:"service,omitempty"`
Version string `json:"version,omitempty"`
}
// ReportLocation is required by the Stackdriver Error format
type ReportLocation struct {
FilePath string `json:"filePath"`
FunctionName string `json:"functionName"`
LineNumber int `json:"lineNumber"`
}
// Context is required by the Stackdriver Error format
type Context struct {
Data Fields `json:"data,omitempty"`
ReportLocation *ReportLocation `json:"reportLocation,omitempty"`
}
// Payload groups all the data for a log entry
type Payload struct {
Severity string `json:"severity"`
EventTime string `json:"eventTime"`
Caller string `json:"caller,omitempty"`
Message string `json:"message"`
ServiceContext *ServiceContext `json:"serviceContext,omitempty"`
Context *Context `json:"context,omitempty"`
Stacktrace string `json:"stacktrace,omitempty"`
}
// Log is the main type for the logger package
type Log struct {
level severity
mux sync.Mutex
payload *Payload
writer io.Writer
callerSkip int
}
var (
defaultLogLevel severity
service string
version string
)
func init() {
logLevel, ok := logLevelValue[strings.ToUpper(os.Getenv("LOG_LEVEL"))]
if !ok {
fmt.Println("logger WARN: LOG_LEVEL is not valid or not set, defaulting to INFO")
logLevel = logLevelValue[INFO.String()]
}
if os.Getenv("SERVICE") == "" || os.Getenv("VERSION") == "" {
fmt.Println("logger ERROR: cannot instantiate the logger, make sure the SERVICE and VERSION environment vars are set correctly")
}
initConfig(logLevel, os.Getenv("SERVICE"), os.Getenv("VERSION"))
}
func initConfig(lvl severity, svc, ver string) {
defaultLogLevel = lvl
service = svc
version = ver
}
// New instantiates and returns a Log object
func New() *Log {
// Set the ServiceContext only within a GCP context
p := &Payload{}
if service != "" && version != "" {
p = &Payload{
ServiceContext: &ServiceContext{
Service: service,
Version: version,
},
}
}
return &Log{
payload: p,
writer: os.Stdout,
level: defaultLogLevel,
callerSkip: defaultCallerSkip,
}
}
// WithOutput creates a copy of a Log with a different output.
func (l *Log) WithOutput(w io.Writer) *Log {
n := l.With(Fields{})
n.writer = w
return n
}
// WithLevel creates a copy of a Log with a different log level
func (l *Log) WithLevel(logLevel severity) *Log {
n := l.With(Fields{})
n.level = logLevel
return n
}
// AddCallerSkip increases the number of callers skipped by caller annotation.
// When building wrappers around the Logger, supplying this value prevents logger
// from always reporting the wrapper code as the caller.
func (l *Log) AddCallerSkip(skip int) {
l.mux.Lock()
defer l.mux.Unlock()
l.callerSkip += skip
}
func (l *Log) log(severity, message string) {
l.mux.Lock()
defer l.mux.Unlock()
// Do not persist the payload here, just format it, marshal it and return it
l.payload = &Payload{
Severity: severity,
EventTime: time.Now().Format(time.RFC3339),
Message: message,
ServiceContext: l.payload.ServiceContext,
Context: l.payload.Context,
Stacktrace: l.payload.Stacktrace,
}
payload, ok := json.Marshal(l.payload)
if ok != nil {
fmt.Printf("logger ERROR: cannot marshal payload: %s", ok.Error())
}
fmt.Fprintln(l.writer, string(payload))
}
// Checks whether the specified log level is valid
func (l *Log) isValidLogLevel(s severity) bool {
l.mux.Lock()
defer l.mux.Unlock()
return s >= l.level
}
// fields returns a valid Fields whether or not one exists in the *Log.
func (l *Log) fields() Fields {
f := make(Fields)
if l.payload == nil {
return f
}
if l.payload.Context == nil {
return f
}
if l.payload.Context.Data == nil {
return f
}
for k, v := range l.payload.Context.Data {
f[k] = v
}
return f
}
// With is used as a chained method to specify which values go in the log entry's context
func (l *Log) With(fields Fields) *Log {
l.mux.Lock()
defer l.mux.Unlock()
f := l.fields()
for k, v := range fields {
f[k] = v
}
return &Log{
payload: &Payload{
ServiceContext: l.payload.ServiceContext,
Context: &Context{
Data: f,
},
Stacktrace: "",
},
writer: l.writer,
level: l.level,
callerSkip: l.callerSkip,
}
}
// Debug prints out a message with DEBUG severity level
func (l *Log) Debug(message string) {
if !l.isValidLogLevel(DEBUG) {
return
}
l.log(DEBUG.String(), message)
}
// Debugf prints out a message with DEBUG severity level
func (l *Log) Debugf(message string, args ...interface{}) {
l.Debug(fmt.Sprintf(message, args...))
}
// Info prints out a message with INFO severity level
func (l *Log) Info(message string) {
if !l.isValidLogLevel(INFO) {
return
}
l.log(INFO.String(), message)
}
// Infof prints out a message with INFO severity level
func (l *Log) Infof(message string, args ...interface{}) {
l.Info(fmt.Sprintf(message, args...))
}
// Warn prints out a message with WARN severity level
func (l *Log) Warn(message string) {
if !l.isValidLogLevel(WARN) {
return
}
l.log(WARN.String(), message)
}
// Warnf prints out a message with WARN severity level
func (l *Log) Warnf(message string, args ...interface{}) {
l.Warn(fmt.Sprintf(message, args...))
}
// Error prints out a message with ERROR severity level
func (l *Log) Error(message string) {
l.error(ERROR.String(), message)
}
// Errorf prints out a message with ERROR severity level
func (l *Log) Errorf(message string, args ...interface{}) {
l.error(ERROR.String(), fmt.Sprintf(message, args...))
}
// Fatal is equivalent to Error() followed by a call to os.Exit(1).
// It prints out a message with CRITICAL severity level
func (l *Log) Fatal(message string) {
l.error(CRITICAL.String(), message)
os.Exit(1)
}
// Fatalf is equivalent to Errorf() followed by a call to os.Exit(1).
// It prints out a message with CRITICAL severity level
func (l *Log) Fatalf(message string, args ...interface{}) {
l.error(CRITICAL.String(), fmt.Sprintf(message, args...))
os.Exit(1)
}
// ERROR prints out a message with the passed severity level (ERROR or CRITICAL)
func (l *Log) error(severity, message string) {
buffer := make([]byte, 1024)
buffer = buffer[:runtime.Stack(buffer, false)]
fpc, file, line, _ := runtime.Caller(l.callerSkip)
funcName := "unknown"
fun := runtime.FuncForPC(fpc)
if fun != nil {
_, funcName = filepath.Split(fun.Name())
}
// Set the data when the context is empty
l.mux.Lock()
if l.payload.Context == nil {
l.payload.Context = &Context{
Data: Fields{},
}
}
l.payload = &Payload{
ServiceContext: l.payload.ServiceContext,
Context: &Context{
Data: l.payload.Context.Data,
ReportLocation: &ReportLocation{
FilePath: file,
FunctionName: funcName,
LineNumber: line,
},
},
Stacktrace: string(buffer),
}
l.mux.Unlock()
l.log(severity, message)
}