Skip to content

Commit

Permalink
fix: init global factory (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
richardlt authored Dec 7, 2023
1 parent ca4b7ae commit ba2fda1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
11 changes: 3 additions & 8 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,11 @@ const (
)

var global *Logger
var Factory WrapperFactoryFunc
var Factory WrapperFactoryFunc = NewLogrusWrapper(logrus.StandardLogger())

func init() {
global = New()
global.callerFrameToSkip = 3
global.globalFactory = true
}

type Logger struct {
Expand All @@ -34,13 +33,10 @@ type Logger struct {
excludeRulesMutex sync.RWMutex
factory WrapperFactoryFunc
callerFrameToSkip int

// if globalFactory is true, Logger.factory is ignored and Factory is used instead.
globalFactory bool
}

func New() *Logger {
return NewWithFactory(NewLogrusWrapper(logrus.StandardLogger()))
return NewWithFactory(nil)
}

func NewWithFactory(factory WrapperFactoryFunc) *Logger {
Expand Down Expand Up @@ -148,8 +144,7 @@ func (l *Logger) Panic(ctx context.Context, format string, args ...interface{})

func (l *Logger) call(ctx context.Context, level Level, format string, args ...interface{}) {
var entry Wrapper

if l.globalFactory {
if l.factory == nil {
entry = Factory()
} else {
entry = l.factory()
Expand Down
12 changes: 11 additions & 1 deletion log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ func ExampleNewZapWrapper() {
func TestErrorWithStackTrace(t *testing.T) {
// Init the wrapper
log.Factory = log.NewTestingWrapper(t)
log.UnregisterField(log.FieldSourceLine, log.FieldSourceFile)
// Init the context
ctx := context.Background()
ctx = context.WithValue(ctx, fieldComponent, "rockbears/log")
Expand All @@ -111,6 +110,17 @@ func TestErrorWithStackTrace(t *testing.T) {
log.ErrorWithStackTrace(ctx, errors.WithStack(fmt.Errorf("this is an error")))
}

func TestErrorWithStackTraceAndFactory(t *testing.T) {
// Init the wrapper
logger := log.NewWithFactory(log.NewTestingWrapper(t))
// Init the context
ctx := context.Background()
ctx = context.WithValue(ctx, fieldComponent, "rockbears/log")
ctx = context.WithValue(ctx, fieldAsset, "ExampleErrorWithStackTrace")
logger.ErrorWithStackTrace(ctx, fmt.Errorf("this is an error"))
logger.ErrorWithStackTrace(ctx, errors.WithStack(fmt.Errorf("this is an error")))
}

func ExampleNewStdWrapperAndSkip() {
// Init the wrapper
log.Factory = log.NewStdWrapper(log.StdWrapperOptions{Level: log.LevelInfo, DisableTimestamp: true})
Expand Down

0 comments on commit ba2fda1

Please sign in to comment.