Skip to content

Instantly share code, notes, and snippets.

@gaorong
Created February 19, 2019 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaorong/e869394725d85671bd7cab1abc789c4f to your computer and use it in GitHub Desktop.
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
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
}
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