This repository has been archived by the owner on Dec 31, 2023. It is now read-only.
/
ctx.hook.go
76 lines (68 loc) · 1.49 KB
/
ctx.hook.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
/*
* Copyright © 2019 Hedzr Yeh.
*/
package hook
import (
"fmt"
"github.com/sirupsen/logrus"
"path"
"runtime"
"strings"
)
// ContextHook ...
type ContextHook struct {
Field string
Skip int
levels []logrus.Level
}
var (
DefaultContextHook = &ContextHook{"src", 5, []logrus.Level{}}
)
// Levels ...
func (hook *ContextHook) Levels() []logrus.Level {
if len(hook.levels) == 0 {
return logrus.AllLevels
}
return hook.levels
}
// Fire ...
func (hook *ContextHook) Fire(entry *logrus.Entry) error {
entry.Data[hook.Field] = hook.findCaller(entry, hook.Skip)
// entry.Data["file"] = fmt.Sprintf(" %v", entry.Caller.File)
return nil
}
func (hook *ContextHook) findCaller(entry *logrus.Entry, skip int) string {
file := ""
line := 0
funcName := ""
for i := 0; i < 10; i++ {
file, line, funcName = getCaller(entry, skip+i)
if !strings.HasPrefix(funcName, "logrus.") {
break
}
}
return fmt.Sprintf("%s:%d:%s", file, line, funcName)
}
func getCaller(entry *logrus.Entry, skip int) (file string, line int, funcName string) {
var ok bool
var pc uintptr
if pc, file, line, ok = runtime.Caller(skip); ok {
funcName = runtime.FuncForPC(pc).Name()
pos := strings.Index(funcName, "/")
part1 := funcName[0:pos]
pos = strings.Index(file, part1)
file = file[pos:]
funcName = path.Base(funcName)
// n := 0
// for i := len(file) - 1; i > 0; i-- {
// if file[i] == '/' {
// n++
// if n >= 2 {
// file = file[i+1:]
// break
// }
// }
// }
}
return
}