Skip to content

Commit

Permalink
Add warning that no global logger is set
Browse files Browse the repository at this point in the history
Print warning message that global logger was not set. This is a hint for the library user, that the lib is trying to log something, but logging is disabled.
  • Loading branch information
elgopher committed Jan 21, 2022
1 parent 852e3dd commit c8c492e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion logger/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ type Field struct {
}

func init() {
SetAdapter(noopLogger{})
SetAdapter(&initialNoopLogger{})
}

var globalLogger atomic.Value
Expand Down
4 changes: 4 additions & 0 deletions logger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ func TestGlobalLogging(t *testing.T) {
logger.Info(ctx, message)
})

t.Run("should log warning that global adapter was not set", func(t *testing.T) {
logger.Warn(ctx, message)
})

t.Run("should log message using global adapter", func(t *testing.T) {
type functionUnderTest func(ctx context.Context, msg string)
tests := map[logger.Level]functionUnderTest{
Expand Down
14 changes: 14 additions & 0 deletions logger/noop.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,22 @@ package logger

import (
"context"
"fmt"
"sync"
)

type noopLogger struct{}

func (n noopLogger) Log(context.Context, Entry) {}

var once sync.Once

type initialNoopLogger struct{}

func (g *initialNoopLogger) Log(_ context.Context, entry Entry) {
if entry.Level == WarnLevel || entry.Level == ErrorLevel {
once.Do(func() {
fmt.Printf("github.com/jacekolszak/yala/logger cannot log message with level %s. Please set the global logging adapter. For example: logger.SetAdapter(printer.StdoutAdapter()) to log all messages to stdout.\n", entry.Level) // nolint
})
}
}

0 comments on commit c8c492e

Please sign in to comment.