Skip to content

Commit

Permalink
Fix SkippedCallerFrames for logger.xxxf
Browse files Browse the repository at this point in the history
When logger.xxxf is used (such as logger.Infof) the SkippedCallerFrames is too small.
  • Loading branch information
elgopher committed Jan 16, 2022
1 parent 6b2ee8e commit 8bbb7a8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
8 changes: 4 additions & 4 deletions logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,31 +96,31 @@ func (l Logger) Debug(msg string) {
}

func (l Logger) Debugf(format string, args ...interface{}) {
l.Debug(fmt.Sprintf(format, args...))
l.WithSkippedCallerFrame().Debug(fmt.Sprintf(format, args...))
}

func (l Logger) Info(msg string) {
l.log(InfoLevel, msg)
}

func (l Logger) Infof(format string, args ...interface{}) {
l.Info(fmt.Sprintf(format, args...))
l.WithSkippedCallerFrame().Info(fmt.Sprintf(format, args...))
}

func (l Logger) Warn(msg string) {
l.log(WarnLevel, msg)
}

func (l Logger) Warnf(format string, args ...interface{}) {
l.Warn(fmt.Sprintf(format, args...))
l.WithSkippedCallerFrame().Warn(fmt.Sprintf(format, args...))
}

func (l Logger) Error(msg string) {
l.log(ErrorLevel, msg)
}

func (l Logger) Errorf(format string, args ...interface{}) {
l.Error(fmt.Sprintf(format, args...))
l.WithSkippedCallerFrame().Error(fmt.Sprintf(format, args...))
}

func (l Logger) log(level Level, msg string) {
Expand Down
30 changes: 30 additions & 0 deletions logger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package logger_test
import (
"context"
"errors"
"fmt"
"testing"

"github.com/jacekolszak/yala/logger"
Expand Down Expand Up @@ -52,6 +53,35 @@ func TestGlobalLogging(t *testing.T) {
}
})

t.Run("should format message using global service", func(t *testing.T) {
type functionUnderTest func(ctx context.Context, fmt string, args ...interface{})
tests := map[logger.Level]functionUnderTest{
logger.DebugLevel: logger.Debugf,
logger.InfoLevel: logger.Infof,
logger.WarnLevel: logger.Warnf,
logger.ErrorLevel: logger.Errorf,
}

for lvl, log := range tests {
testName := string(lvl)

t.Run(testName, func(t *testing.T) {
service := &serviceMock{}
logger.SetService(service)
// when
log(ctx, fmt.Sprintf("formatted %s", "message"))
// then
service.HasExactlyOneEntry(t,
logger.Entry{
Level: lvl,
Message: "formatted message",
SkippedCallerFrames: 5,
},
)
})
}
})

t.Run("should log message with field", func(t *testing.T) {
service := &serviceMock{}
logger.SetService(service)
Expand Down

0 comments on commit 8bbb7a8

Please sign in to comment.