-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
120 lines (97 loc) · 2.49 KB
/
log.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
package log
import (
"fmt"
"os"
"strings"
"time"
"github.com/rs/zerolog"
)
// Zerolog
var Logger = zerolog.New(os.Stderr).With().Timestamp().Logger().Level(zerolog.TraceLevel)
func With() zerolog.Context {
return Logger.With()
}
func Fatal() *zerolog.Event {
return Logger.Info()
}
func Info() *zerolog.Event {
return Logger.Info()
}
func Error() *zerolog.Event {
return Logger.Error()
}
func Debug() *zerolog.Event {
return Logger.Debug()
}
func Trace() *zerolog.Event {
return Logger.Trace()
}
// TraceCheck checks if the log level is trace before evaluating the anon fn
func TraceCheck(fn func()) {
if Logger.GetLevel() == zerolog.TraceLevel {
fn()
}
}
// Zerolog simple wrappers
// Error for notable errors.
func Errorf(fmts string, a ...interface{}) {
Logger.Error().Msgf(fmts, a...)
}
// Info for regular messages.
func Infof(fmts string, a ...interface{}) {
Logger.Info().Msgf(fmts, a...)
}
// Debug for debugging messages.
func Debugf(fmts string, a ...interface{}) {
Logger.Debug().Msgf(fmts, a...)
}
// Trace for debugging messages.
func Tracef(fmts string, a ...interface{}) {
Logger.Trace().Msgf(fmts, a...)
}
// Traceln - prints to trace
func Traceln(args ...interface{}) {
Logger.Trace().Msg(fmt.Sprintln(args...))
}
// Helper functions
// Print - simple print, without timestamp, without regard to log level.
func Print(fmts string, args ...interface{}) {
fmt.Fprintf(os.Stdout, fmts+"\n", args...)
}
// Log init and settings
// SetLevel sets the log level.
func SetLevel(lvalue zerolog.Level) {
zerolog.SetGlobalLevel(lvalue)
jsonLog := os.Getenv("TL_LOG_JSON") == "true"
Logger = zerolog.New(os.Stderr).With().Timestamp().Logger().Level(lvalue)
if !jsonLog {
// use console logging
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
output.FormatLevel = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("[%-5s]", i))
}
Logger = Logger.Output(output)
}
zerolog.DefaultContextLogger = &Logger
Tracef("Set global log value to %s", lvalue)
}
// setLevelByName sets the log level by string name.
func getLevelByName(lstr string) zerolog.Level {
switch strings.ToUpper(lstr) {
case "FATAL":
return zerolog.FatalLevel
case "ERROR":
return zerolog.ErrorLevel
case "INFO":
return zerolog.InfoLevel
case "DEBUG":
return zerolog.DebugLevel
case "TRACE":
return zerolog.TraceLevel
}
return zerolog.InfoLevel
}
func init() {
SetLevel(getLevelByName(os.Getenv("TL_LOG")))
}