-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtext_parser.go
More file actions
117 lines (94 loc) · 2.44 KB
/
text_parser.go
File metadata and controls
117 lines (94 loc) · 2.44 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
package log
import (
"context"
"fmt"
"log"
"runtime"
)
// logParser contains parsing logic for a logger.
type logParser struct {
*logOptions
log *log.Logger
}
// WithPrefix appends the given prefix to the existing prefix.
func (l *logParser) WithPrefix(p string, message interface{}) string {
if l.prefix != "" {
if p == "" {
return fmt.Sprintf("%s] [%+v", l.prefix, message)
}
return fmt.Sprintf("%s.%s] [%+v", l.prefix, p, message)
}
return fmt.Sprintf("%s] [%+v", p, message)
}
// isLoggable checks whether it is possible to log in the given level under current configurations.
func (l *logParser) isLoggable(level Level) bool {
return logTypes[level] <= logTypes[l.logLevel]
}
// colored colour encodes the log level tag.
//
// Whether this returns coloured tags or not depends on the colour configuration of the logger.
func (l *logParser) colored(level Level) string {
if l.colors {
return string(logColors[level])
}
return string(level)
}
// logEntry prints the log entry to the configured io.Writer.
func (l *logParser) logEntry(ctx context.Context, level Level, message interface{}, prms ...interface{}) {
if !l.isLoggable(level) {
return
}
var params []interface{}
format := "%s [%s] [%+v]"
logLevel := l.colored(level)
// add extracted trace id
var traceID string
if l.ctxTraceExt != nil {
traceID = l.ctxTraceExt(ctx)
}
params = append(params, logLevel, traceID, fmt.Sprintf("%v", message))
if l.filePath || l.funcPath {
format = l.applyCallerInfo(format)
}
if len(prms) > 0 {
format += " %+v"
params = append(params, prms)
}
// add extracted context details
if l.ctxExt != nil {
if ctxData := l.ctxExt(ctx); len(ctxData) > 0 {
format += " %v"
params = append(params, ctxData)
}
}
if l.ctxMapExt != nil {
if ctxData := l.ctxMapExt(ctx); len(ctxData) > 0 {
format += " %v"
params = append(params, ctxData)
}
}
if level == FATAL {
l.log.Fatalf(format, params...)
}
l.log.Printf(format, params...)
}
func (l *logParser) applyCallerInfo(format string) string {
funcName := "<Unknown>"
file := "<Unknown>"
line := 0
pc, f, ln, ok := runtime.Caller(l.skipFrameCount + 1)
if ok {
funcName = runtime.FuncForPC(pc).Name()
}
file = f
line = ln
// file and func format
var filePath, funcPath string
if l.funcPath {
funcPath = " on func " + funcName
}
if l.filePath {
filePath = " on " + file + " line " + fmt.Sprint(line)
}
return "%s [%s] [%+v" + funcPath + filePath + "]"
}