Skip to content

Commit

Permalink
Add Depth to filename.
Browse files Browse the repository at this point in the history
  • Loading branch information
onrik committed Jan 23, 2020
1 parent f91d39f commit 2ae0a60
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
4 changes: 3 additions & 1 deletion filename/filename.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
27 changes: 27 additions & 0 deletions filename/filename_test.go
Original file line number Diff line number Diff line change
@@ -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,
)
}

0 comments on commit 2ae0a60

Please sign in to comment.