/
logging.go
68 lines (58 loc) · 1.34 KB
/
logging.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
package logging
import (
"errors"
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var logger *zap.Logger
var logLevel zap.AtomicLevel
type Level string
const (
DebugLevel Level = "debug"
InfoLevel Level = "info"
WarnLevel Level = "warn"
ErrorLevel Level = "error"
FatalLevel Level = "fatal"
DefaultLevel Level = InfoLevel
)
type Config struct {
Level Level
}
func init() {
logLevel = zap.NewAtomicLevelAt(zapcore.InfoLevel)
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.TimeKey = ""
logger = zap.New(zapcore.NewCore(
zapcore.NewConsoleEncoder(encoderConfig),
zapcore.Lock(os.Stdout),
logLevel,
))
}
func SetLogLevel(level string) error {
lvl, err := parseLogLevel(level)
if err != nil {
return err
}
logLevel.SetLevel(lvl)
return nil
}
func AllowedLogLevels() []Level {
return []Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel}
}
func parseLogLevel(level string) (zapcore.Level, error) {
switch level {
case string(DebugLevel):
return zapcore.DebugLevel, nil
case string(InfoLevel):
return zapcore.InfoLevel, nil
case string(WarnLevel):
return zapcore.WarnLevel, nil
case string(ErrorLevel):
return zapcore.ErrorLevel, nil
case string(FatalLevel):
return zapcore.FatalLevel, nil
default:
return zapcore.DebugLevel, errors.New("unknown log level: " + string(level))
}
}