-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathwrite_close_syncer.go
84 lines (69 loc) · 2.05 KB
/
write_close_syncer.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
package handler
import (
"io"
"github.com/gookit/slog"
)
// SyncCloseHandler definition
type SyncCloseHandler struct {
slog.LevelFormattable
Output SyncCloseWriter
}
// NewSyncCloserWithLF create new SyncCloseHandler, with custom slog.LevelFormattable
func NewSyncCloserWithLF(out SyncCloseWriter, lf slog.LevelFormattable) *SyncCloseHandler {
return &SyncCloseHandler{
Output: out,
// init formatter and level handle
LevelFormattable: lf,
}
}
//
// ------------- Use max log level -------------
//
// SyncCloserWithMaxLevel create new SyncCloseHandler, with max log level
func SyncCloserWithMaxLevel(out SyncCloseWriter, maxLevel slog.Level) *SyncCloseHandler {
return NewSyncCloserWithLF(out, slog.NewLvFormatter(maxLevel))
}
//
// ------------- Use multi log levels -------------
//
// NewSyncCloser create new SyncCloseHandler, alias of NewSyncCloseHandler()
func NewSyncCloser(out SyncCloseWriter, levels []slog.Level) *SyncCloseHandler {
return NewSyncCloseHandler(out, levels)
}
// SyncCloserWithLevels create new SyncCloseHandler, alias of NewSyncCloseHandler()
func SyncCloserWithLevels(out SyncCloseWriter, levels []slog.Level) *SyncCloseHandler {
return NewSyncCloseHandler(out, levels)
}
// NewSyncCloseHandler create new SyncCloseHandler with limited log levels
//
// Usage:
//
// f, err := os.OpenFile("my.log", ...)
// h := handler.NewSyncCloseHandler(f, slog.AllLevels)
func NewSyncCloseHandler(out SyncCloseWriter, levels []slog.Level) *SyncCloseHandler {
return NewSyncCloserWithLF(out, slog.NewLvsFormatter(levels))
}
// Close the handler
func (h *SyncCloseHandler) Close() error {
if err := h.Flush(); err != nil {
return err
}
return h.Output.Close()
}
// Flush the handler
func (h *SyncCloseHandler) Flush() error {
return h.Output.Sync()
}
// Writer of the handler
func (h *SyncCloseHandler) Writer() io.Writer {
return h.Output
}
// Handle log record
func (h *SyncCloseHandler) Handle(record *slog.Record) error {
bts, err := h.Formatter().Format(record)
if err != nil {
return err
}
_, err = h.Output.Write(bts)
return err
}