Debian Codegraph @

log/log.go

raw
1 package log
2
3 import (
4 "io"
5 "log"
6 "os"
7 "strings"
8 "sync"
9 "time"
10 )
11
12 // Defaults for package level variables
13 var (
14 DefaultLevel = InfoLevel
15 DefaultFormat = TextFormat
16 DefaultOutput = &peekLogWriter{os.Stderr}
17 )
18
19 var (
20 level = DefaultLevel
21 format = DefaultFormat
22 overrides = make(map[string][]*levelOverride)
23 output io.Writer = DefaultOutput
24 filename = ""
25 mu = &sync.RWMutex{}
26 )
27
28 // init sets the default log output (including log.SetOutput)
29 //
30 // This has to be explicitly called, because DefaultOutput is a peekLogWriter,
31 // which wraps os.Stderr.
32 func init() {
33 SetOutput(DefaultOutput)
34 }
35
36 // Fatal prints the given message, and exits the program
37 func Fatal(message string, v ...any) {
38 newEvent().Fatal(message, v...)
39 }
40
41 // Error prints the given message, if the current log level is ERROR or lower
42 func Error(message string, v ...any) {
43 newEvent().Error(message, v...)
44 }
45
46 // Warn prints the given message, if the current log level is WARN or lower
47 func Warn(message string, v ...any) {
48 newEvent().Warn(message, v...)
49 }
50
51 // Info prints the given message, if the current log level is INFO or lower
52 func Info(message string, v ...any) {
53 newEvent().Info(message, v...)
54 }
55
56 // Debug prints the given message, if the current log level is DEBUG or lower
57 func Debug(message string, v ...any) {
58 newEvent().Debug(message, v...)
59 }
60
61 // Trace prints the given message, if the current log level is TRACE
62 func Trace(message string, v ...any) {
63 newEvent().Trace(message, v...)
64 }
65
66 // With creates a new log event and adds the fields of the given Contexter structs
67 func With(contexts ...Contexter) *Event {
68 return newEvent().With(contexts...)
69 }
70
71 // Field creates a new log event and adds a custom field and value to it
72 func Field(key string, value any) *Event {
73 return newEvent().Field(key, value)
74 }
75
76 // Fields creates a new log event and adds a map of fields to it
77 func Fields(fields Context) *Event {
78 return newEvent().Fields(fields)
79 }
80
81 // Tag creates a new log event and adds a "tag" field to it
82 func Tag(tag string) *Event {
83 return newEvent().Tag(tag)
84 }
85
86 // Time creates a new log event and sets the time field
87 func Time(time time.Time) *Event {
88 return newEvent().Time(time)
89 }
90
91 // Timing runs f and records the time if took to execute it in "time_taken_ms"
92 func Timing(f func()) *Event {
93 return newEvent().Timing(f)
94 }
95
96 // CurrentLevel returns the current log level
97 func CurrentLevel() Level {
98 mu.RLock()
99 defer mu.RUnlock()
100 return level
101 }
102
103 // SetLevel sets a new log level
104 func SetLevel(newLevel Level) {
105 mu.Lock()
106 defer mu.Unlock()
107 level = newLevel
108 }
109
110 // SetLevelOverride adds a log override for the given field
111 func SetLevelOverride(field string, value string, level Level) {
112 mu.Lock()
113 defer mu.Unlock()
114 if _, ok := overrides[field]; !ok {
115 overrides[field] = make([]*levelOverride, 0)
116 }
117 overrides[field] = append(overrides[field], &levelOverride{value: value, level: level})
118 }
119
120 // ResetLevelOverrides removes all log level overrides
121 func ResetLevelOverrides() {
122 mu.Lock()
123 defer mu.Unlock()
124 overrides = make(map[string][]*levelOverride)
125 }
126
127 // CurrentFormat returns the current log format
128 func CurrentFormat() Format {
129 mu.RLock()
130 defer mu.RUnlock()
131 return format
132 }
133
134 // SetFormat sets a new log format
135 func SetFormat(newFormat Format) {
136 mu.Lock()
137 defer mu.Unlock()
138 format = newFormat
139 if newFormat == JSONFormat {
140 DisableDates()
141 }
142 }
143
144 // SetOutput sets the log output writer
145 func SetOutput(w io.Writer) {
146 mu.Lock()
147 defer mu.Unlock()
148 output = &peekLogWriter{w}
149 if f, ok := w.(*os.File); ok {
150 filename = f.Name()
151 } else {
152 filename = ""
153 }
154 log.SetOutput(output)
155 }
156
157 // File returns the log file, if any, or an empty string otherwise
158 func File() string {
159 mu.RLock()
160 defer mu.RUnlock()
161 return filename
162 }
163
164 // IsFile returns true if the output is a non-default file
165 func IsFile() bool {
166 mu.RLock()
167 defer mu.RUnlock()
168 return filename != ""
169 }
170
171 // DisableDates disables the date/time prefix
172 func DisableDates() {
173 log.SetFlags(0)
174 }
175
176 // Loggable returns true if the given log level is lower or equal to the current log level
177 func Loggable(l Level) bool {
178 return CurrentLevel() <= l
179 }
180
181 // IsTrace returns true if the current log level is TraceLevel
182 func IsTrace() bool {
183 return Loggable(TraceLevel)
184 }
185
186 // IsDebug returns true if the current log level is DebugLevel or below
187 func IsDebug() bool {
188 return Loggable(DebugLevel)
189 }
190
191 // peekLogWriter is an io.Writer which will peek at the rendered log event,
192 // and ensure that the rendered output is valid JSON. This is a hack!
193 type peekLogWriter struct {
194 w io.Writer
195 }
196
197 func (w *peekLogWriter) Write(p []byte) (n int, err error) {
198 if len(p) == 0 || p[0] == '{' || CurrentFormat() == TextFormat {
199 return w.w.Write(p)
200 }
201 m := newEvent().Tag(tagStdLog).Render(InfoLevel, "%s", strings.TrimSpace(string(p)))
202 if m == "" {
203 return 0, nil
204 }
205 return w.w.Write([]byte(m + "\n"))
206 }