Skip to content

Instantly share code, notes, and snippets.

@diafour
Created December 12, 2020 14:24
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 diafour/ca1c92ea46b9707befb8162a5513d10f to your computer and use it in GitHub Desktop.
Save diafour/ca1c92ea46b9707befb8162a5513d10f to your computer and use it in GitHub Desktop.
logrus with short caller and caller only for some levels
import (
"fmt"
"runtime"
"testing"
"github.com/sirupsen/logrus"
)
type MyFormatter struct {
*logrus.TextFormatter
CallerLevels map[logrus.Level]bool
}
func (f *MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
if _, has := f.CallerLevels[entry.Level] ; !has {
entry.Caller = nil
}
return f.TextFormatter.Format(entry)
}
func Test_Logrus(t *testing.T) {
logrus.SetReportCaller(true)
logrus.SetFormatter(&MyFormatter{
TextFormatter: &logrus.TextFormatter{
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
_, filename := path.Split(f.File)
filename = fmt.Sprintf("%s:%d", filename, f.Line)
return "", filename
},
},
CallerLevels: map[logrus.Level]bool{
logrus.ErrorLevel: true,
logrus.DebugLevel: true,
},
})
logrus.Info("info level message")
logrus.Error("error level message")
logrus.Debug("debug level message")
}
# Output:
=== RUN Test_Logrus
time="2020-12-12T17:19:34+03:00" level=info msg="info level message"
time="2020-12-12T17:19:34+03:00" level=error msg="error level message" file="logger.go:192"
--- PASS: Test_Logrus (0.00s)
PASS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment