Created
December 12, 2020 14:24
-
-
Save diafour/ca1c92ea46b9707befb8162a5513d10f to your computer and use it in GitHub Desktop.
logrus with short caller and caller only for some levels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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