-
Notifications
You must be signed in to change notification settings - Fork 67
/
stdlog.go
67 lines (60 loc) · 1.46 KB
/
stdlog.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
package log
import (
"log"
"strings"
)
type stdLogWriter struct {
l *Logger
opt *StandardLogOptions
}
func (l *stdLogWriter) Write(p []byte) (n int, err error) {
str := strings.TrimSuffix(string(p), "\n")
if l.opt != nil {
switch l.opt.ForceLevel {
case DebugLevel:
l.l.Debug(str)
case InfoLevel:
l.l.Info(str)
case WarnLevel:
l.l.Warn(str)
case ErrorLevel:
l.l.Error(str)
}
} else {
switch {
case strings.HasPrefix(str, "DEBUG"):
l.l.Debug(strings.TrimSpace(str[5:]))
case strings.HasPrefix(str, "INFO"):
l.l.Info(strings.TrimSpace(str[4:]))
case strings.HasPrefix(str, "WARN"):
l.l.Warn(strings.TrimSpace(str[4:]))
case strings.HasPrefix(str, "ERROR"):
l.l.Error(strings.TrimSpace(str[5:]))
case strings.HasPrefix(str, "ERR"):
l.l.Error(strings.TrimSpace(str[3:]))
default:
l.l.Info(str)
}
}
return len(p), nil
}
// StandardLogOptions can be used to configure the standard log adapter.
type StandardLogOptions struct {
ForceLevel Level
}
// StandardLog returns a standard logger from Logger. The returned logger
// can infer log levels from message prefix. Expected prefixes are DEBUG, INFO,
// WARN, ERROR, and ERR.
func (l *Logger) StandardLog(opts ...StandardLogOptions) *log.Logger {
nl := l.With()
// The caller stack is
// log.Printf() -> l.Output() -> l.out.Write(stdLogger.Write)
nl.callerOffset += 3
sl := &stdLogWriter{
l: nl,
}
if len(opts) > 0 {
sl.opt = &opts[0]
}
return log.New(sl, "", 0)
}