-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
golog.go
380 lines (339 loc) · 8.23 KB
/
golog.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
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// The colorful and simple logging library
// Copyright (c) 2017 Fadhli Dzil Ikram
package golog
import (
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"sync"
"time"
"github.com/p4gefau1t/trojan-go/log"
"github.com/p4gefau1t/trojan-go/log/golog/colorful"
"golang.org/x/crypto/ssh/terminal"
)
func init() {
log.RegisterLogger(New(os.Stdout))
}
// FdWriter interface extends existing io.Writer with file descriptor function
// support
type FdWriter interface {
io.Writer
Fd() uintptr
}
// Logger struct define the underlying storage for single logger
type Logger struct {
mu sync.RWMutex
color bool
out io.Writer
debug bool
timestamp bool
quiet bool
buf colorful.ColorBuffer
logLevel int
}
// Prefix struct define plain and color byte
type Prefix struct {
Plain []byte
Color []byte
File bool
}
var (
// Plain prefix template
plainFatal = []byte("[FATAL] ")
plainError = []byte("[ERROR] ")
plainWarn = []byte("[WARN] ")
plainInfo = []byte("[INFO] ")
plainDebug = []byte("[DEBUG] ")
plainTrace = []byte("[TRACE] ")
// FatalPrefix show fatal prefix
FatalPrefix = Prefix{
Plain: plainFatal,
Color: colorful.Red(plainFatal),
File: true,
}
// ErrorPrefix show error prefix
ErrorPrefix = Prefix{
Plain: plainError,
Color: colorful.Red(plainError),
File: true,
}
// WarnPrefix show warn prefix
WarnPrefix = Prefix{
Plain: plainWarn,
Color: colorful.Orange(plainWarn),
}
// InfoPrefix show info prefix
InfoPrefix = Prefix{
Plain: plainInfo,
Color: colorful.Green(plainInfo),
}
// DebugPrefix show info prefix
DebugPrefix = Prefix{
Plain: plainDebug,
Color: colorful.Purple(plainDebug),
File: true,
}
// TracePrefix show info prefix
TracePrefix = Prefix{
Plain: plainTrace,
Color: colorful.Cyan(plainTrace),
}
)
// New returns new Logger instance with predefined writer output and
// automatically detect terminal coloring support
func New(out FdWriter) *Logger {
return &Logger{
color: terminal.IsTerminal(int(out.Fd())),
out: out,
timestamp: true,
}
}
func (l *Logger) SetLogLevel(level log.LogLevel) {
l.mu.Lock()
defer l.mu.Unlock()
l.logLevel = int(level)
}
func (l *Logger) SetOutput(w io.Writer) {
l.mu.Lock()
defer l.mu.Unlock()
l.color = false
if fdw, ok := w.(FdWriter); ok {
l.color = terminal.IsTerminal(int(fdw.Fd()))
}
l.out = w
}
// WithColor explicitly turn on colorful features on the log
func (l *Logger) WithColor() *Logger {
l.mu.Lock()
defer l.mu.Unlock()
l.color = true
return l
}
// WithoutColor explicitly turn off colorful features on the log
func (l *Logger) WithoutColor() *Logger {
l.mu.Lock()
defer l.mu.Unlock()
l.color = false
return l
}
// WithDebug turn on debugging output on the log to reveal debug and trace level
func (l *Logger) WithDebug() *Logger {
l.mu.Lock()
defer l.mu.Unlock()
l.debug = true
return l
}
// WithoutDebug turn off debugging output on the log
func (l *Logger) WithoutDebug() *Logger {
l.mu.Lock()
defer l.mu.Unlock()
l.debug = false
return l
}
// IsDebug check the state of debugging output
func (l *Logger) IsDebug() bool {
l.mu.RLock()
defer l.mu.RUnlock()
return l.debug
}
// WithTimestamp turn on timestamp output on the log
func (l *Logger) WithTimestamp() *Logger {
l.mu.Lock()
defer l.mu.Unlock()
l.timestamp = true
return l
}
// WithoutTimestamp turn off timestamp output on the log
func (l *Logger) WithoutTimestamp() *Logger {
l.mu.Lock()
defer l.mu.Unlock()
l.timestamp = false
return l
}
// Quiet turn off all log output
func (l *Logger) Quiet() *Logger {
l.mu.Lock()
defer l.mu.Unlock()
l.quiet = true
return l
}
// NoQuiet turn on all log output
func (l *Logger) NoQuiet() *Logger {
l.mu.Lock()
defer l.mu.Unlock()
l.quiet = false
return l
}
// IsQuiet check for quiet state
func (l *Logger) IsQuiet() bool {
l.mu.RLock()
defer l.mu.RUnlock()
return l.quiet
}
// Output print the actual value
func (l *Logger) Output(depth int, prefix Prefix, data string) error {
// Check if quiet is requested, and try to return no error and be quiet
if l.IsQuiet() {
return nil
}
// Get current time
now := time.Now()
// Temporary storage for file and line tracing
var file string
var line int
var fn string
// Check if the specified prefix needs to be included with file logging
if prefix.File {
var ok bool
var pc uintptr
// Get the caller filename and line
if pc, file, line, ok = runtime.Caller(depth + 2); !ok {
file = "<unknown file>"
fn = "<unknown function>"
line = 0
} else {
file = filepath.Base(file)
fn = runtime.FuncForPC(pc).Name()
}
}
// Acquire exclusive access to the shared buffer
l.mu.Lock()
defer l.mu.Unlock()
// Reset buffer so it start from the begining
l.buf.Reset()
// Write prefix to the buffer
if l.color {
l.buf.Append(prefix.Color)
} else {
l.buf.Append(prefix.Plain)
}
// Check if the log require timestamping
if l.timestamp {
// Print timestamp color if color enabled
if l.color {
l.buf.Blue()
}
// Print date and time
year, month, day := now.Date()
l.buf.AppendInt(year, 4)
l.buf.AppendByte('/')
l.buf.AppendInt(int(month), 2)
l.buf.AppendByte('/')
l.buf.AppendInt(day, 2)
l.buf.AppendByte(' ')
hour, min, sec := now.Clock()
l.buf.AppendInt(hour, 2)
l.buf.AppendByte(':')
l.buf.AppendInt(min, 2)
l.buf.AppendByte(':')
l.buf.AppendInt(sec, 2)
l.buf.AppendByte(' ')
// Print reset color if color enabled
if l.color {
l.buf.Off()
}
}
// Add caller filename and line if enabled
if prefix.File {
// Print color start if enabled
if l.color {
l.buf.Orange()
}
// Print filename and line
l.buf.Append([]byte(fn))
l.buf.AppendByte(':')
l.buf.Append([]byte(file))
l.buf.AppendByte(':')
l.buf.AppendInt(line, 0)
l.buf.AppendByte(' ')
// Print color stop
if l.color {
l.buf.Off()
}
}
// Print the actual string data from caller
l.buf.Append([]byte(data))
if len(data) == 0 || data[len(data)-1] != '\n' {
l.buf.AppendByte('\n')
}
// Flush buffer to output
_, err := l.out.Write(l.buf.Buffer)
return err
}
// Fatal print fatal message to output and quit the application with status 1
func (l *Logger) Fatal(v ...interface{}) {
if l.logLevel <= 4 {
l.Output(1, FatalPrefix, fmt.Sprintln(v...))
}
os.Exit(1)
}
// Fatalf print formatted fatal message to output and quit the application
// with status 1
func (l *Logger) Fatalf(format string, v ...interface{}) {
if l.logLevel <= 4 {
l.Output(1, FatalPrefix, fmt.Sprintf(format, v...))
}
os.Exit(1)
}
// Error print error message to output
func (l *Logger) Error(v ...interface{}) {
if l.logLevel <= 3 {
l.Output(1, ErrorPrefix, fmt.Sprintln(v...))
}
}
// Errorf print formatted error message to output
func (l *Logger) Errorf(format string, v ...interface{}) {
if l.logLevel <= 3 {
l.Output(1, ErrorPrefix, fmt.Sprintf(format, v...))
}
}
// Warn print warning message to output
func (l *Logger) Warn(v ...interface{}) {
if l.logLevel <= 2 {
l.Output(1, WarnPrefix, fmt.Sprintln(v...))
}
}
// Warnf print formatted warning message to output
func (l *Logger) Warnf(format string, v ...interface{}) {
if l.logLevel <= 2 {
l.Output(1, WarnPrefix, fmt.Sprintf(format, v...))
}
}
// Info print informational message to output
func (l *Logger) Info(v ...interface{}) {
if l.logLevel <= 1 {
l.Output(1, InfoPrefix, fmt.Sprintln(v...))
}
}
// Infof print formatted informational message to output
func (l *Logger) Infof(format string, v ...interface{}) {
if l.logLevel <= 1 {
l.Output(1, InfoPrefix, fmt.Sprintf(format, v...))
}
}
// Debug print debug message to output if debug output enabled
func (l *Logger) Debug(v ...interface{}) {
if l.logLevel == 0 {
l.Output(1, DebugPrefix, fmt.Sprintln(v...))
}
}
// Debugf print formatted debug message to output if debug output enabled
func (l *Logger) Debugf(format string, v ...interface{}) {
if l.logLevel == 0 {
l.Output(1, DebugPrefix, fmt.Sprintf(format, v...))
}
}
// Trace print trace message to output if debug output enabled
func (l *Logger) Trace(v ...interface{}) {
if l.logLevel == 0 {
l.Output(1, TracePrefix, fmt.Sprintln(v...))
}
}
// Tracef print formatted trace message to output if debug output enabled
func (l *Logger) Tracef(format string, v ...interface{}) {
if l.logLevel == 0 {
l.Output(1, TracePrefix, fmt.Sprintf(format, v...))
}
}