-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_with_prefix.go
More file actions
61 lines (50 loc) · 1.5 KB
/
log_with_prefix.go
File metadata and controls
61 lines (50 loc) · 1.5 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
package log
import "strings"
type PrefixLogger interface {
PrefixLogf(level Level, calldepth int, prefix, format string, value ...interface{})
}
type withPrefixLogger struct {
Logger
prefix string
logf func(level Level, calldepth int, prefix, format string, value ...interface{})
}
func (l *withPrefixLogger) Logf(level Level, calldepth int, format string, value ...interface{}) {
if l.logf == nil {
return
}
l.logf(level, calldepth+1, l.prefix, format, value...)
}
// WithPrefix specifies a prefix for the logger.
func (l Log) WithPrefix(prefix string) Log {
if l.logger == nil {
return l
}
if prefix == "" {
return l
}
// Escape the prefix to avoid it interfering with the format string; replace any % with %%
prefix = strings.ReplaceAll(prefix, "%", "%%")
// If the logger is already a withPrefixLogger, combine the prefixes. Also, use the logger within the withPrefixLogger
parentLogger := l.logger
if withPrefix, ok := l.logger.(*withPrefixLogger); ok {
prefix = withPrefix.prefix + prefix
parentLogger = withPrefix.Logger
}
// If the parentLogger is PrefixLogger
if ppl, ok := parentLogger.(PrefixLogger); ok {
l.logger = &withPrefixLogger{
Logger: parentLogger,
prefix: prefix,
logf: ppl.PrefixLogf,
}
} else {
l.logger = &withPrefixLogger{
Logger: parentLogger,
prefix: prefix,
logf: func(level Level, calldepth int, prefix, format string, value ...interface{}) {
parentLogger.Logf(level, calldepth+1, prefix+format, value...)
},
}
}
return l
}