-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
70 lines (55 loc) · 1.49 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
package logger
import (
"os"
"os/signal"
"syscall"
"github.com/blendle/zapdriver"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// New returns a new logger, ready to use in our services.
func New(service, version string, options ...zap.Option) (*zap.Logger, error) {
level := zap.NewAtomicLevelAt(zapcore.InfoLevel)
config := &zap.Config{
Level: level,
Encoding: "json",
EncoderConfig: zapdriver.NewProductionEncoderConfig(),
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
if os.Getenv("ENV") == "development" {
config.Development = true
}
if v := os.Getenv("DEBUG"); v != "" && v != "0" && v != "false" {
level.SetLevel(zap.DebugLevel)
}
stackcore := zapdriver.WrapCore()
fields := zap.Fields(
zapdriver.Label("service", service),
zapdriver.Label("version", version),
)
go levelToggler(level)
return config.Build(append(options, stackcore, fields)...)
}
// Must is a convenience function that takes a zaplog and error as input, panics
// if the error is not nil, and returns the passed in logger.
//
// This can be used for example with `Must(zap.NewProduction())`
func Must(zaplog *zap.Logger, err error) *zap.Logger {
if err != nil {
panic(err)
}
return zaplog
}
func levelToggler(level zap.AtomicLevel) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGUSR1)
for {
<-ch
if level.Level() == zap.DebugLevel {
level.SetLevel(zap.InfoLevel)
} else {
level.SetLevel(zap.DebugLevel)
}
}
}