-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathloggers.go
More file actions
224 lines (200 loc) · 5.61 KB
/
loggers.go
File metadata and controls
224 lines (200 loc) · 5.61 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package log
import (
"fmt"
"os"
"strconv"
ct "github.com/daviddengcn/go-colortext"
"golang.org/x/xerrors"
)
// LoggerInfo is a structure that should be used when creating a logger.
// It contains parameters about how to log (with time, colors, ...) and
// embeds the Logger interface, which should define how the logger should log.
type LoggerInfo struct {
// These are information-debugging levels that can be turned on or off.
// Every logging greater than 'debugLvl' will be discarded . So you can
// Log at different levels and easily turn on or off the amount of logging
// generated by adjusting the 'debugLvl' variable.
DebugLvl int
// If 'showTime' is true, it will print the time for each line displayed
// by the logger.
ShowTime bool
// If 'AbsoluteFilePath' is true, it will print the absolute file path
// instead of the base.
AbsoluteFilePath bool
// If 'useColors' is true, logs will be colored (defaults to monochrome
// output). It also controls padding, since colorful output is higly
// correlated with humans who like their log lines padded.
UseColors bool
// If 'padding' is true, it will nicely pad the line that is written.
Padding bool
// If true, it will only send the raw message to the logger
RawMessage bool
}
// Logger is the interface that specifies how loggers
// will receive and display messages.
type Logger interface {
Log(level int, msg string)
Close()
GetLoggerInfo() *LoggerInfo
}
// Tracer is an additional interface that specifies a tracer extension to
//onet/log.
type Tracer interface {
TraceID(id []byte)
}
const (
// DefaultStdDebugLvl is the default debug level for the standard logger
DefaultStdDebugLvl = 1
// DefaultStdShowTime is the default value for 'showTime' for the standard logger
DefaultStdShowTime = false
// DefaultStdAbsoluteFilePath is the default to show absolute path for the standard logger
DefaultStdAbsoluteFilePath = false
// DefaultStdUseColors is the default value for 'useColors' for the standard logger
DefaultStdUseColors = false
// DefaultStdPadding is the default value for 'padding' for the standard logger
DefaultStdPadding = true
)
var (
// concurrent access is protected by debugMut
loggers = make(map[int]Logger)
loggersCounter int
)
// RegisterLogger will register a callback that will receive a copy of every
// message, fully formatted. It returns the key assigned to the logger (used
// to unregister the logger).
func RegisterLogger(l Logger) int {
debugMut.Lock()
defer debugMut.Unlock()
key := loggersCounter
loggers[key] = l
loggersCounter++
return key
}
// UnregisterLogger takes the key it was assigned and returned by
// 'RegisterLogger', closes the corresponding Logger and removes it from the
// loggers.
func UnregisterLogger(key int) {
debugMut.Lock()
defer debugMut.Unlock()
if l, ok := loggers[key]; ok {
l.Close()
delete(loggers, key)
}
}
type fileLogger struct {
lInfo *LoggerInfo
file *os.File
}
func (fl *fileLogger) Log(level int, msg string) {
if _, err := fl.file.WriteString(msg + "\n"); err != nil {
panic(err)
}
}
func (fl *fileLogger) Close() {
fl.file.Close()
}
func (fl *fileLogger) GetLoggerInfo() *LoggerInfo {
return fl.lInfo
}
// NewFileLogger creates a logger that writes into the file with
// the given path and is using the given LoggerInfo.
// It returns the logger.
func NewFileLogger(lInfo *LoggerInfo, path string) (Logger, error) {
// Override file if it already exists.
file, err := os.Create(path)
if err != nil {
return nil, xerrors.Errorf("creating file: %v", err)
}
return &fileLogger{
lInfo: lInfo,
file: file,
}, nil
}
type stdLogger struct {
lInfo *LoggerInfo
}
func (sl *stdLogger) Log(lvl int, msg string) {
// If the DEBUG_LVL is 0 or -1, don't print any colors or line-info,
// but just print plain text.
// 0 is the default level
// -1 is FormatPython to print
if sl.lInfo.DebugLvl <= 0 {
sl.print(lvl, msg)
return
}
if sl.lInfo.UseColors {
bright := lvl < 0
lvlAbs := lvl
if bright {
lvlAbs *= -1
}
switch lvl {
case lvlPrint:
ct.Foreground(ct.White, true)
case lvlInfo:
ct.Foreground(ct.White, true)
case lvlWarning:
ct.Foreground(ct.Green, true)
case lvlError:
ct.Foreground(ct.Red, false)
case lvlFatal:
ct.Foreground(ct.Red, true)
case lvlPanic:
ct.Foreground(ct.Red, true)
default:
if lvl != 0 {
if lvlAbs <= 5 {
colors := []ct.Color{ct.Yellow, ct.Cyan, ct.Green, ct.Blue, ct.Cyan}
ct.Foreground(colors[lvlAbs-1], bright)
}
}
}
}
if lvl < lvlInfo {
fmt.Fprintln(stdErr, msg)
} else {
fmt.Fprintln(stdOut, msg)
}
if sl.lInfo.UseColors {
ct.ResetColor()
}
}
func (sl *stdLogger) Close() {}
func (sl *stdLogger) GetLoggerInfo() *LoggerInfo {
return sl.lInfo
}
func (sl *stdLogger) print(lvl int, args ...interface{}) {
out := stdOut
if lvl < lvlInfo {
out = stdErr
}
switch loggers[0].GetLoggerInfo().DebugLvl {
case FormatPython:
prefix := []string{"[-]", "[!]", "[X]", "[Q]", "[+]", ""}
ind := lvl - lvlWarning
if ind < 0 || ind > 4 {
panic("index out of range " + strconv.Itoa(ind))
}
fmt.Fprint(out, prefix[ind], " ")
case FormatNone:
}
for i, a := range args {
fmt.Fprint(out, a)
if i != len(args)-1 {
fmt.Fprint(out, " ")
}
}
fmt.Fprint(out, "\n")
}
// Not public + not taking a LoggerInfo as argument because we don't want
// multiple stdLoggers.
func newStdLogger() (Logger, error) {
lInfo := &LoggerInfo{
DebugLvl: DefaultStdDebugLvl,
UseColors: DefaultStdUseColors,
ShowTime: DefaultStdShowTime,
AbsoluteFilePath: DefaultStdAbsoluteFilePath,
Padding: DefaultStdPadding,
}
return &stdLogger{lInfo: lInfo}, nil
}