-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathlogging.go
85 lines (71 loc) · 1.86 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package logging
import (
"fmt"
"io"
stdlog "log"
"os"
"strings"
isatty "github.com/mattn/go-isatty"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/sean-/conswriter"
)
var acceptedLogLevels = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
var acceptedLogFormat = []string{"HUMAN", "JSON"}
// SetupLogger sets the log level and outout format.
// Accepted levels are panic, fatal, error, warn, info and debug.
// Accepted formats are human or json.
func SetupLogger(level, format string) (err error) {
if err = setLogFormat(strings.ToUpper(format)); err != nil {
return err
}
if err = setLogLevel(strings.ToUpper(level)); err != nil {
return err
}
return nil
}
func setLogLevel(level string) error {
switch level {
case "DEBUG":
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case "INFO":
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case "WARN":
zerolog.SetGlobalLevel(zerolog.WarnLevel)
case "ERROR":
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
case "FATAL":
zerolog.SetGlobalLevel(zerolog.FatalLevel)
default:
return fmt.Errorf("unsupported log level: %q (supported levels: %s)", level,
strings.Join(acceptedLogLevels, " "))
}
return nil
}
func setLogFormat(format string) error {
var logWriter io.Writer
var zLog zerolog.Logger
if isatty.IsTerminal(os.Stdout.Fd()) ||
isatty.IsCygwinTerminal(os.Stdout.Fd()) {
logWriter = conswriter.GetTerminal()
} else {
logWriter = os.Stdout
}
switch format {
case "HUMAN":
w := zerolog.ConsoleWriter{
Out: logWriter,
NoColor: true,
}
zLog = zerolog.New(w).With().Timestamp().Logger()
case "JSON":
zLog = zerolog.New(logWriter).With().Timestamp().Logger()
default:
return fmt.Errorf("unsupported log format: %q (supported formats: %s)", format,
strings.Join(acceptedLogFormat, " "))
}
log.Logger = zLog
stdlog.SetFlags(0)
stdlog.SetOutput(zLog)
return nil
}