From 2ae0a60c780bbe800c83855a76c167e2ebfd03a5 Mon Sep 17 00:00:00 2001 From: Andrey Date: Thu, 23 Jan 2020 14:13:25 +0300 Subject: [PATCH] Add Depth to filename. --- filename/filename.go | 4 +++- filename/filename_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 filename/filename_test.go diff --git a/filename/filename.go b/filename/filename.go index fdbd833..97aaa66 100644 --- a/filename/filename.go +++ b/filename/filename.go @@ -29,6 +29,7 @@ func newFormatter(old logrus.Formatter, hook *Hook) logrus.Formatter { type Hook struct { Field string Skip int + Depth int levels []logrus.Level SkipPrefixes []string Formatter func(file, function string, line int) string @@ -53,7 +54,7 @@ func (hook *Hook) findCaller() (string, string, int) { function string line int ) - for i := 0; i < 10; i++ { + for i := 0; i < hook.Depth; i++ { pc, file, line = getCaller(hook.Skip + i) if !hook.skipFile(file) { break @@ -82,6 +83,7 @@ func NewHook(levels ...logrus.Level) *Hook { hook := Hook{ Field: "_source", Skip: 5, + Depth: 20, levels: levels, SkipPrefixes: []string{"logrus/", "logrus@"}, Formatter: func(file, function string, line int) string { diff --git a/filename/filename_test.go b/filename/filename_test.go new file mode 100644 index 0000000..16caee5 --- /dev/null +++ b/filename/filename_test.go @@ -0,0 +1,27 @@ +package filename + +import ( + "bytes" + "testing" + + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestFilenameHook(t *testing.T) { + hook := NewHook() + + buff := new(bytes.Buffer) + logrus.SetOutput(buff) + logrus.AddHook(hook) + logrus.SetFormatter(new(logrus.JSONFormatter)) + + logrus.Info("Test") + + require.NotEqual(t, "", buff.String()) + require.Equal(t, + "filename/filename_test.go:20", + gjson.Get(buff.String(), DefaultField).Str, + ) +}