Skip to content

Commit

Permalink
feat: support for SetReportCaller(true)
Browse files Browse the repository at this point in the history
  • Loading branch information
antonfisher committed Feb 2, 2020
1 parent 4968324 commit ab9dbe7
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
3 changes: 3 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ func printDemo(f logrus.Formatter, title string) {
l.SetFormatter(f)
}

// enable/disable file/function name
l.SetReportCaller(false)

l.Infof("this is %v demo", title)

lWebServer := l.WithField("component", "web-server")
Expand Down
11 changes: 11 additions & 0 deletions formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) {
} else {
b.WriteString(entry.Message)
}

if entry.HasCaller() {
fmt.Fprintf(
b,
" (%s:%d %s)",
entry.Caller.File,
entry.Caller.Line,
entry.Caller.Function,
)
}

b.WriteByte('\n')

return b.Bytes(), nil
Expand Down
40 changes: 40 additions & 0 deletions tests/formatter_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package formatter_test

import (
"bytes"
"os"
"regexp"
"testing"

formatter "github.com/antonfisher/nested-logrus-formatter"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -157,3 +160,40 @@ func ExampleFormatter_Format_trim_message() {
// - [WARN] test3
// - [ERRO] test4
}

func TestFormatter_Format_with_report_caller(t *testing.T) {
output := bytes.NewBuffer([]byte{})

l := logrus.New()
l.SetOutput(output)
l.SetLevel(logrus.DebugLevel)
l.SetFormatter(&formatter.Formatter{
NoColors: true,
TimestampFormat: "-",
})
l.SetReportCaller(true)

l.Debug("test1")

line, err := output.ReadString('\n')
if err != nil {
t.Errorf("Cannot read log output: %v", err)
}

expectedRegExp := "- \\[DEBU\\] test1 \\(.+/tests/formatter_test\\.go:[0-9]+ " +
"command-line-arguments_test\\.TestFormatter_Format_with_report_caller\\)\n$"

match, err := regexp.MatchString(
expectedRegExp,
line,
)
if err != nil {
t.Errorf("Cannot check regexp: %v", err)
} else if !match {
t.Errorf(
"logger.SetReportCaller(true) output doesn't match, expected: %s to find in: '%s'",
expectedRegExp,
line,
)
}
}

0 comments on commit ab9dbe7

Please sign in to comment.