forked from daneshvar/go-logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
std.go
60 lines (52 loc) · 1.1 KB
/
std.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
package logger
import (
"bytes"
stdlog "log"
"os"
)
const (
_loggerWriterDepth = 2
_stdLogDefaultDepth = 1
)
func redirectStdLogAt(core *Core, scope string, level Level) func() {
flags := stdlog.Flags()
prefix := stdlog.Prefix()
stdlog.SetFlags(0)
stdlog.SetPrefix("")
l := core.GetLogger(scope)
l.Skip(_stdLogDefaultDepth + _loggerWriterDepth)
logFunc := levelToFunc(l, level)
stdlog.SetOutput(&loggerWriter{logFunc})
return func() {
stdlog.SetFlags(flags)
stdlog.SetPrefix(prefix)
stdlog.SetOutput(os.Stderr)
}
}
func levelToFunc(logger *Logger, level Level) func(messages ...interface{}) {
switch level {
case TraceLevel:
return logger.Trace
case DebugLevel:
return logger.Debug
case InfoLevel:
return logger.Info
case WarnLevel:
return logger.Warn
case ErrorLevel:
return logger.Error
case FatalLevel:
return logger.Fatal
case PanicLevel:
return logger.Panic
}
return logger.Info
}
type loggerWriter struct {
logFunc func(messages ...interface{})
}
func (l *loggerWriter) Write(p []byte) (int, error) {
p = bytes.TrimSpace(p)
l.logFunc(string(p))
return len(p), nil
}