-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
106 lines (94 loc) · 2.42 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
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
package accelerator
import (
"bytes"
"fmt"
"io"
"log"
"os"
"path/filepath"
)
type logger struct {
logger *log.Logger
file *os.File
}
func newLogger(path string) (*logger, error) {
if path == "" {
lg := log.New(os.Stdout, "", log.LstdFlags)
return &logger{logger: lg}, nil
}
dir := filepath.Dir(path)
if dir != "." {
err := os.MkdirAll(dir, 0750)
if err != nil {
return nil, err
}
}
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600) // #nosec
if err != nil {
return nil, err
}
lg := log.New(io.MultiWriter(file, os.Stdout), "", log.LstdFlags)
return &logger{logger: lg, file: file}, nil
}
func (l *logger) Info(v ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 64))
buf.WriteString("[info] ")
_, _ = fmt.Fprintln(buf, v...)
l.logger.Print(buf)
}
func (l *logger) Infof(format string, v ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 64))
buf.WriteString("[info] ")
_, _ = fmt.Fprintf(buf, format, v...)
l.logger.Println(buf)
}
func (l *logger) Warning(v ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 64))
buf.WriteString("[warning] ")
_, _ = fmt.Fprintln(buf, v...)
l.logger.Print(buf)
}
func (l *logger) Warningf(format string, v ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 64))
buf.WriteString("[warning] ")
_, _ = fmt.Fprintf(buf, format, v...)
l.logger.Println(buf)
}
func (l *logger) Error(v ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 64))
buf.WriteString("[error] ")
_, _ = fmt.Fprintln(buf, v...)
l.logger.Print(buf)
}
func (l *logger) Errorf(format string, v ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 64))
buf.WriteString("[error] ")
_, _ = fmt.Fprintf(buf, format, v...)
l.logger.Println(buf)
}
func (l *logger) Fatal(fn string, v ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 64))
buf.WriteString("[fatal] ")
buf.WriteString("panic in " + fn + "\n")
_, _ = fmt.Fprintln(buf, v...)
l.logger.Print(buf)
}
func (l *logger) Fatalf(fn, format string, v ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 64))
buf.WriteString("[fatal] ")
buf.WriteString("panic in " + fn + "\n")
_, _ = fmt.Fprintf(buf, format, v...)
l.logger.Println(buf)
}
func (l *logger) Close() error {
var err error
if l.file != nil {
err = l.file.Close()
if err != nil {
l.logger.SetOutput(os.Stderr)
l.Error("failed to close log file:", err)
}
}
l.logger.SetOutput(io.Discard)
return err
}