-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
105 lines (85 loc) · 1.87 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
// SPDX-License-Identifier: 0BSD
package olog
import (
"fmt"
"io"
"os"
"sync"
)
// Priority same as in log/syslog
type Priority int
const (
LOG_EMERG Priority = iota + '0'
LOG_ALERT
LOG_CRIT
LOG_ERR
LOG_WARNING
LOG_NOTICE
LOG_INFO
LOG_DEBUG
)
const (
CRIT = "<2>"
ERR = "<3>"
WARN = "<4>"
NOTICE = "<5>"
INFO = "<6>"
DEBUG = "<7>"
)
var logStdOut = &Logger{Out: os.Stdout, LogLevel: LOG_INFO}
var logStdErr = &Logger{Out: os.Stderr, LogLevel: LOG_INFO}
type Logger struct {
Out io.Writer // destination for output
LogLevel Priority
mu sync.Mutex // ensures atomic writes
}
func (l *Logger) Printf(format string, v ...any) {
if len(format) < 4 {
return
}
// Priority prefix looks like <6> we get the 6 from it
prioChar := format[1]
prio := Priority(prioChar)
if l.IsLoggable(prio) {
l.printfBlocking(format, v...)
}
}
func (l *Logger) printfBlocking(format string, v ...any) {
l.mu.Lock()
_, _ = fmt.Fprintf(l.Out, format, v...)
l.mu.Unlock()
}
func (l *Logger) Fatalf(format string, v ...any) {
l.printfBlocking(CRIT+format, v...)
os.Exit(1)
}
func (l *Logger) IsLoggable(logLevel Priority) bool {
// errors are always logged
return logLevel <= l.LogLevel
}
// shorthand functions for stdout
func Printf(format string, v ...any) {
logStdOut.Printf(format, v...)
}
func IsLoggable(logLevel Priority) bool {
return logStdOut.IsLoggable(logLevel)
}
func SetLogLevel(logLevel Priority) {
logStdOut.LogLevel = logLevel
}
func Fatalf(format string, v ...any) {
logStdOut.Fatalf(format, v...)
}
// shorthand functions for stderr
func ErrPrintf(format string, v ...any) {
logStdErr.Printf(format, v...)
}
func ErrIsLoggable(logLevel Priority) bool {
return logStdErr.IsLoggable(logLevel)
}
func ErrSetLogLevel(logLevel Priority) {
logStdErr.LogLevel = logLevel
}
func ErrFatalf(format string, v ...any) {
logStdErr.Fatalf(format, v...)
}