From c4e4882020c0da433ed03f82be0bed3a497dbacc Mon Sep 17 00:00:00 2001 From: Gavin Cabbage Date: Wed, 6 Feb 2019 14:51:07 -0500 Subject: [PATCH] prevent string formatting in Entry.Logf when log level is not enabled --- entry.go | 6 ++++-- entry_test.go | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/entry.go b/entry.go index df6d188de..c5b489e97 100644 --- a/entry.go +++ b/entry.go @@ -298,7 +298,9 @@ func (entry *Entry) Panic(args ...interface{}) { // Entry Printf family functions 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{}) { @@ -390,4 +392,4 @@ func (entry *Entry) Panicln(args ...interface{}) { func (entry *Entry) sprintlnn(args ...interface{}) string { msg := fmt.Sprintln(args...) return msg[:len(msg)-1] -} +} \ No newline at end of file diff --git a/entry_test.go b/entry_test.go index 5e6634112..c4ad8c891 100644 --- a/entry_test.go +++ b/entry_test.go @@ -139,3 +139,17 @@ func TestEntryWithIncorrectField(t *testing.T) { assert.Equal(eWithFunc.err, `can not add field "func"`) 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", ) +} \ No newline at end of file