-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
logger.go
94 lines (83 loc) · 2.2 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
// Package logger is used to store details of events in the node.
// Events can be categorized by Trace, Debug, Info, Error, Fatal, and Panic.
package logger
import (
"log"
"reflect"
"runtime"
"github.com/pkg/errors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Logger is the main interface of this package.
// It implements uber/zap's SugaredLogger interface and adds conditional logging helpers.
type Logger struct {
*zap.SugaredLogger
}
// Write logs a message at the Info level and returns the length
// of the given bytes.
func (l *Logger) Write(b []byte) (int, error) {
l.Info(string(b))
return len(b), nil
}
// WarnIf logs the error if present.
func (l *Logger) WarnIf(err error) {
if err != nil {
l.Warn(err)
}
}
// ErrorIf logs the error if present.
func (l *Logger) ErrorIf(err error, optionalMsg ...string) {
if err != nil {
if len(optionalMsg) > 0 {
l.Error(errors.Wrap(err, optionalMsg[0]))
} else {
l.Error(err)
}
}
}
// ErrorIfCalling calls the given function and logs the error of it if there is.
func (l *Logger) ErrorIfCalling(f func() error, optionalMsg ...string) {
err := f()
if err != nil {
e := errors.Wrap(err, runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name())
if len(optionalMsg) > 0 {
Default.Error(errors.Wrap(e, optionalMsg[0]))
} else {
Default.Error(e)
}
}
}
func (l *Logger) PanicIf(err error) {
if err != nil {
l.Panic(err)
}
}
// CreateLogger dwisott
func CreateLogger(zl *zap.SugaredLogger) *Logger {
return &Logger{
SugaredLogger: zl,
}
}
// CreateProductionLogger returns a log config for the passed directory
// with the given LogLevel and customizes stdout for pretty printing.
func CreateProductionLogger(
dir string, jsonConsole bool, lvl zapcore.Level, toDisk bool) *Logger {
config := zap.NewProductionConfig()
if !jsonConsole {
config.OutputPaths = []string{"pretty://console"}
}
if toDisk {
destination := logFileURI(dir)
config.OutputPaths = append(config.OutputPaths, destination)
config.ErrorOutputPaths = append(config.ErrorOutputPaths, destination)
}
config.Level.SetLevel(lvl)
zl, err := config.Build(zap.AddCallerSkip(1))
if err != nil {
log.Fatal(err)
}
return &Logger{
SugaredLogger: zl.Sugar(),
}
}