-
Notifications
You must be signed in to change notification settings - Fork 13
/
log.go
101 lines (87 loc) · 2.3 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
package server
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/decred/slog"
"github.com/jrick/logrotate/rotator"
)
type logBackend struct {
stdOut io.Writer
logRotator *rotator.Rotator
bknd *slog.Backend
defaultLogLevel slog.Level
logLevels map[string]slog.Level
loggers map[string]slog.Logger
}
func newLogBackend(logFile, debugLevel string, stdOut io.Writer) (*logBackend, error) {
var logRotator *rotator.Rotator
if logFile != "" {
logDir, _ := filepath.Split(logFile)
err := os.MkdirAll(logDir, 0700)
if err != nil {
return nil, fmt.Errorf("failed to create log directory: %v\n", err)
}
logRotator, err = rotator.New(logFile, 1024, false, 10)
if err != nil {
return nil, fmt.Errorf("failed to create file rotator: %v\n", err)
}
}
b := &logBackend{
stdOut: stdOut,
logRotator: logRotator,
defaultLogLevel: slog.LevelInfo,
logLevels: make(map[string]slog.Level),
loggers: make(map[string]slog.Logger),
}
b.bknd = slog.NewBackend(b)
// Parse the debugLevel string into log levels for each subsystem.
for _, v := range strings.Split(debugLevel, ",") {
fields := strings.Split(v, "=")
if len(fields) == 1 {
b.defaultLogLevel, _ = slog.LevelFromString(fields[0])
} else if len(fields) == 2 {
subsys := fields[0]
level, _ := slog.LevelFromString(fields[1])
b.logLevels[subsys] = level
} else {
return nil, fmt.Errorf("unable to parse %q as subsys=level "+
"debuglevel string", v)
}
}
return b, nil
}
func (bknd *logBackend) Write(b []byte) (int, error) {
if bknd.stdOut != nil {
bknd.stdOut.Write(b)
}
if bknd.logRotator != nil {
bknd.logRotator.Write(b)
}
return len(b), nil
}
// untrackedLogger is a logger that is not retained by the backend.
func (bknd *logBackend) untrackedLogger(subsys string) slog.Logger {
l := bknd.bknd.Logger(subsys)
if level, ok := bknd.logLevels[subsys]; ok {
l.SetLevel(level)
} else {
l.SetLevel(bknd.defaultLogLevel)
}
return l
}
func (bknd *logBackend) logger(subsys string) slog.Logger {
if l, ok := bknd.loggers[subsys]; ok {
return l
}
l := bknd.bknd.Logger(subsys)
bknd.loggers[subsys] = l
if level, ok := bknd.logLevels[subsys]; ok {
l.SetLevel(level)
} else {
l.SetLevel(bknd.defaultLogLevel)
}
return l
}