-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
75 lines (57 loc) · 1.33 KB
/
logger.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
package logger
import (
"fmt"
"io"
"os"
"sync"
)
type Logger struct {
mutex sync.Mutex
output io.Writer
prefix string
buffer []byte
// This function will be call every time Print function is call to update the prefix
UpdatePrefix func() string
}
var std = New(os.Stderr, "")
func New(out io.Writer, prefix string) *Logger {
return &Logger{output: out, prefix: prefix}
}
func GetDefault() *Logger { return std }
func (l *Logger) SetPrefix(prefix string) {
l.mutex.Lock()
defer l.mutex.Unlock()
l.prefix = prefix
}
func (l *Logger) SetOutput(w io.Writer) {
l.mutex.Lock()
defer l.mutex.Unlock()
l.output = w
}
func (l *Logger) outpuT(s string) error {
l.mutex.Lock()
defer l.mutex.Unlock()
l.buffer = l.buffer[:0]
l.buffer = append(l.buffer, l.prefix...)
l.buffer = append(l.buffer, s...)
_, err := l.output.Write(l.buffer)
return err
}
func (l *Logger) Print(v ...any) {
if l.UpdatePrefix != nil {
l.prefix = l.UpdatePrefix()
}
l.outpuT(fmt.Sprint(v...))
}
func (l *Logger) Println(v ...any) {
if l.UpdatePrefix != nil {
l.prefix = l.UpdatePrefix()
}
l.outpuT(fmt.Sprintln(v...))
}
func (l *Logger) Printf(format string, v ...any) {
if l.UpdatePrefix != nil {
l.prefix = l.UpdatePrefix()
}
l.outpuT(fmt.Sprintf(format, v...) + "\n")
}