Created
February 19, 2019 10:54
-
-
Save gaorong/e869394725d85671bd7cab1abc789c4f to your computer and use it in GitHub Desktop.
this is for logrus log with line number, just add hook.go in logrus's code file with debug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package logrus | |
import ( | |
"fmt" | |
"runtime" | |
"strings" | |
) | |
type LineHook struct { | |
Field string | |
Skip int | |
levels []Level | |
Formatter func(file, function string, line int) string | |
} | |
func (hook *LineHook) Levels() []Level { | |
return hook.levels | |
} | |
func (hook *LineHook) Fire(entry *Entry) error { | |
entry.Data[hook.Field] = hook.Formatter(findCaller(hook.Skip)) | |
return nil | |
} | |
func NewLineHook(levels ...Level) *LineHook { | |
hook := LineHook{ | |
Field: "source", | |
Skip: 5, | |
levels: levels, | |
Formatter: func(file, function string, line int) string { | |
return fmt.Sprintf("%s:%d", file, line) | |
}, | |
} | |
if len(hook.levels) == 0 { | |
hook.levels = AllLevels | |
} | |
return &hook | |
} | |
func findCaller(skip int) (string, string, int) { | |
var ( | |
pc uintptr | |
file string | |
function string | |
line int | |
) | |
for i := 0; i < 10; i++ { | |
pc, file, line = getCaller(skip + i) | |
if !strings.HasPrefix(file, "logrus") { | |
break | |
} | |
} | |
if pc != 0 { | |
frames := runtime.CallersFrames([]uintptr{pc}) | |
frame, _ := frames.Next() | |
function = frame.Function | |
} | |
return file, function, line | |
} | |
func getCaller(skip int) (uintptr, string, int) { | |
pc, file, line, ok := runtime.Caller(skip) | |
if !ok { | |
return 0, "", 0 | |
} | |
n := 0 | |
for i := len(file) - 1; i > 0; i-- { | |
if file[i] == '/' { | |
n += 1 | |
if n >= 2 { | |
file = file[i+1:] | |
break | |
} | |
} | |
} | |
return pc, file, line | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/Sirupsen/logrus" | |
) | |
func main() { | |
hook := logrus.NewLineHook() | |
hook.Field = "line" | |
logrus.AddHook(hook) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment