-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathlogger.go
94 lines (82 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
package scribe
import (
"fmt"
"io"
"strings"
)
// A Logger provides a standard logging interface for doing basic low level
// logging tasks as well as debug logging.
type Logger struct {
writer io.Writer
LeveledLogger
Debug LeveledLogger
}
// NewLogger takes a writer and returns a Logger that writes to the given
// writer. The default writter sends all debug logging to io.Discard.
func NewLogger(writer io.Writer) Logger {
return Logger{
writer: writer,
LeveledLogger: NewLeveledLogger(writer),
Debug: NewLeveledLogger(io.Discard),
}
}
// WithLevel takes in a log level string and configures the log level of the
// logger. To enable debug logging the log level must be set to "DEBUG".
func (l Logger) WithLevel(level string) Logger {
switch strings.ToUpper(level) {
case "DEBUG":
return Logger{
writer: l.writer,
LeveledLogger: NewLeveledLogger(l.writer),
Debug: NewLeveledLogger(l.writer),
}
default:
return Logger{
writer: l.writer,
LeveledLogger: NewLeveledLogger(l.writer),
Debug: NewLeveledLogger(io.Discard),
}
}
}
// A LeveledLogger provides a standard interface for basic formatted logging.
type LeveledLogger struct {
Title FuncWriter
Process FuncWriter
Subprocess FuncWriter
Action FuncWriter
Detail FuncWriter
Subdetail FuncWriter
}
// NewLeveledLogger takes a writer and returns a LeveledLogger that writes to the given
// writer.
func NewLeveledLogger(writer io.Writer) LeveledLogger {
return LeveledLogger{
Title: NewFuncWriter(NewWriter(writer)),
Process: NewFuncWriter(NewWriter(writer, WithIndent(1))),
Subprocess: NewFuncWriter(NewWriter(writer, WithIndent(2))),
Action: NewFuncWriter(NewWriter(writer, WithIndent(3))),
Detail: NewFuncWriter(NewWriter(writer, WithIndent(4))),
Subdetail: NewFuncWriter(NewWriter(writer, WithIndent(5))),
}
}
// Break inserts a line break in the log output
func (l LeveledLogger) Break() {
l.Title("")
}
type _fw struct{}
type FuncWriter func(format string, v ...interface{}) io.Writer
func NewFuncWriter(writer io.Writer) FuncWriter {
return func(format string, v ...interface{}) io.Writer {
skip := len(v) > 0 && v[0] == _fw{}
if !skip {
if !strings.HasSuffix(format, "\n") {
format = format + "\n"
}
fmt.Fprintf(writer, format, v...)
}
return writer
}
}
func (fw FuncWriter) Write(b []byte) (int, error) {
return fw("", _fw{}).Write(b)
}