Skip to content

Commit ab9dbe7

Browse files
committed
feat: support for SetReportCaller(true)
1 parent 4968324 commit ab9dbe7

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

example/main.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ func printDemo(f logrus.Formatter, title string) {
2626
l.SetFormatter(f)
2727
}
2828

29+
// enable/disable file/function name
30+
l.SetReportCaller(false)
31+
2932
l.Infof("this is %v demo", title)
3033

3134
lWebServer := l.WithField("component", "web-server")

formatter.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,17 @@ func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) {
7272
} else {
7373
b.WriteString(entry.Message)
7474
}
75+
76+
if entry.HasCaller() {
77+
fmt.Fprintf(
78+
b,
79+
" (%s:%d %s)",
80+
entry.Caller.File,
81+
entry.Caller.Line,
82+
entry.Caller.Function,
83+
)
84+
}
85+
7586
b.WriteByte('\n')
7687

7788
return b.Bytes(), nil

tests/formatter_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package formatter_test
22

33
import (
4+
"bytes"
45
"os"
6+
"regexp"
7+
"testing"
58

69
formatter "github.com/antonfisher/nested-logrus-formatter"
710
"github.com/sirupsen/logrus"
@@ -157,3 +160,40 @@ func ExampleFormatter_Format_trim_message() {
157160
// - [WARN] test3
158161
// - [ERRO] test4
159162
}
163+
164+
func TestFormatter_Format_with_report_caller(t *testing.T) {
165+
output := bytes.NewBuffer([]byte{})
166+
167+
l := logrus.New()
168+
l.SetOutput(output)
169+
l.SetLevel(logrus.DebugLevel)
170+
l.SetFormatter(&formatter.Formatter{
171+
NoColors: true,
172+
TimestampFormat: "-",
173+
})
174+
l.SetReportCaller(true)
175+
176+
l.Debug("test1")
177+
178+
line, err := output.ReadString('\n')
179+
if err != nil {
180+
t.Errorf("Cannot read log output: %v", err)
181+
}
182+
183+
expectedRegExp := "- \\[DEBU\\] test1 \\(.+/tests/formatter_test\\.go:[0-9]+ " +
184+
"command-line-arguments_test\\.TestFormatter_Format_with_report_caller\\)\n$"
185+
186+
match, err := regexp.MatchString(
187+
expectedRegExp,
188+
line,
189+
)
190+
if err != nil {
191+
t.Errorf("Cannot check regexp: %v", err)
192+
} else if !match {
193+
t.Errorf(
194+
"logger.SetReportCaller(true) output doesn't match, expected: %s to find in: '%s'",
195+
expectedRegExp,
196+
line,
197+
)
198+
}
199+
}

0 commit comments

Comments
 (0)