Merge pull request #903 from gavincabbage/entry-logf-level

prevent string formatting in Entry.Logf when log level is not enabled
This commit is contained in:
David Bariod 2019-02-10 13:38:47 +01:00 committed by GitHub
commit 1261c1f8a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 2 deletions

View File

@ -298,7 +298,9 @@ func (entry *Entry) Panic(args ...interface{}) {
// Entry Printf family functions // Entry Printf family functions
func (entry *Entry) Logf(level Level, format string, args ...interface{}) { func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
entry.Log(level, fmt.Sprintf(format, args...)) if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, fmt.Sprintf(format, args...))
}
} }
func (entry *Entry) Tracef(format string, args ...interface{}) { func (entry *Entry) Tracef(format string, args ...interface{}) {
@ -390,4 +392,4 @@ func (entry *Entry) Panicln(args ...interface{}) {
func (entry *Entry) sprintlnn(args ...interface{}) string { func (entry *Entry) sprintlnn(args ...interface{}) string {
msg := fmt.Sprintln(args...) msg := fmt.Sprintln(args...)
return msg[:len(msg)-1] return msg[:len(msg)-1]
} }

View File

@ -139,3 +139,17 @@ func TestEntryWithIncorrectField(t *testing.T) {
assert.Equal(eWithFunc.err, `can not add field "func"`) assert.Equal(eWithFunc.err, `can not add field "func"`)
assert.Equal(eWithFuncPtr.err, `can not add field "funcPtr"`) assert.Equal(eWithFuncPtr.err, `can not add field "funcPtr"`)
} }
func TestEntryLogfLevel(t *testing.T) {
logger := New()
buffer := &bytes.Buffer{}
logger.Out = buffer
logger.SetLevel(InfoLevel)
entry := NewEntry(logger)
entry.Logf(DebugLevel, "%s", "debug")
assert.NotContains(t, buffer.String(), "debug", )
entry.Logf(WarnLevel, "%s", "warn")
assert.Contains(t, buffer.String(), "warn", )
}