-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime.go
89 lines (76 loc) · 2.03 KB
/
runtime.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
package eraspacelog
import (
"fmt"
"path/filepath"
"runtime"
"strings"
"github.com/sirupsen/logrus"
)
// FunctionKey holds the function field
const FunctionKey = "function"
// PackageKey holds the package field
const PackageKey = "package"
// LineKey holds the line field
const LineKey = "line"
// FileKey holds the file field
const FileKey = "file"
const (
logrusStackJump = 5
logrusFieldlessStackJump = 7
)
// Formatter decorates log entries with function name and package name (optional) and line number (optional)
type Formatter struct {
ChildFormatter logrus.Formatter
// When true, line number will be tagged to fields as well
Line bool
// When true, package name will be tagged to fields as well
Package bool
// When true, file name will be tagged to fields as well
File bool
// When true, only base name of the file will be tagged to fields
BaseNameOnly bool
}
// Format the current log entry by adding the function name and line number of the caller.
func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) {
function, file, line := f.getCurrentPosition(entry)
packageEnd := strings.LastIndex(function, ".")
functionName := function[packageEnd+1:]
data := logrus.Fields{FunctionKey: functionName}
if f.Line {
data[LineKey] = line
}
if f.Package {
packageName := function[:packageEnd]
data[PackageKey] = packageName
}
if f.File {
if f.BaseNameOnly {
data[FileKey] = filepath.Base(file)
} else {
data[FileKey] = file
}
}
for k, v := range entry.Data {
data[k] = v
}
entry.Data = data
return f.ChildFormatter.Format(entry)
}
func (f *Formatter) getCurrentPosition(entry *logrus.Entry) (string, string, string) {
skip := logrusStackJump
if len(entry.Data) == 0 {
skip = logrusFieldlessStackJump
}
start:
pc, file, line, _ := runtime.Caller(skip)
lineNumber := ""
if f.Line {
lineNumber = fmt.Sprintf("%d", line)
}
function := runtime.FuncForPC(pc).Name()
if strings.LastIndex(function, "sirupsen/logrus.") != -1 {
skip++
goto start
}
return function, file, lineNumber
}