forked from morganfly/bilibili
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile.go
92 lines (83 loc) · 1.79 KB
/
file.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
package log
import (
"context"
"io"
"path/filepath"
"time"
"go-common/library/log/internal/filewriter"
)
// level idx
const (
_infoIdx = iota
_warnIdx
_errorIdx
_totalIdx
)
var _fileNames = map[int]string{
_infoIdx: "info.log",
_warnIdx: "warning.log",
_errorIdx: "error.log",
}
// FileHandler .
type FileHandler struct {
render Render
fws [_totalIdx]*filewriter.FileWriter
}
// NewFile crete a file logger.
func NewFile(dir string, bufferSize, rotateSize int64, maxLogFile int) *FileHandler {
// new info writer
newWriter := func(name string) *filewriter.FileWriter {
var options []filewriter.Option
if rotateSize > 0 {
options = append(options, filewriter.MaxSize(rotateSize))
}
if maxLogFile > 0 {
options = append(options, filewriter.MaxFile(maxLogFile))
}
w, err := filewriter.New(filepath.Join(dir, name), options...)
if err != nil {
panic(err)
}
return w
}
handler := &FileHandler{
render: newPatternRender("[%D %T] [%L] [%S] %M"),
}
for idx, name := range _fileNames {
handler.fws[idx] = newWriter(name)
}
return handler
}
// Log loggint to file .
func (h *FileHandler) Log(ctx context.Context, lv Level, args ...D) {
d := make(map[string]interface{}, 10+len(args))
for _, arg := range args {
d[arg.Key] = arg.Value
}
// add extra fields
addExtraField(ctx, d)
d[_time] = time.Now().Format(_timeFormat)
var w io.Writer
switch lv {
case _warnLevel:
w = h.fws[_warnIdx]
case _errorLevel:
w = h.fws[_errorIdx]
default:
w = h.fws[_infoIdx]
}
h.render.Render(w, d)
w.Write([]byte("\n"))
}
// Close log handler
func (h *FileHandler) Close() error {
for _, fw := range h.fws {
// ignored error
fw.Close()
}
return nil
}
// SetFormat set log format
func (h *FileHandler) SetFormat(format string) {
h.render = newPatternRender(format)
}