Skip to content

Commit

Permalink
Update logging
Browse files Browse the repository at this point in the history
  • Loading branch information
roeldev committed Jun 19, 2024
1 parent 52fd377 commit af0b75a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
15 changes: 10 additions & 5 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,21 @@ type Logger interface {
LogHealthChanged(newStatus, oldStatus Status, statuses map[string]Status)
}

// DefaultLogger returns a [Logger] that uses a [log.Logger] to log health
// status events. It defaults to [log.Default] if the provided [log.Logger] l
// is nil.
func DefaultLogger(l *log.Logger) Logger {
const panicNewNilLogger = "healthcheck.NewLogger: log.Logger should not be nil"

// NewLogger returns a [Logger] that uses a [log.Logger] to log health
// status events.
func NewLogger(l *log.Logger) Logger {
if l == nil {
l = log.Default()
panic(panicNewNilLogger)
}
return &logger{l}
}

// DefaultLogger returns a [Logger] that uses [log.Default] to log health
// status events.
func DefaultLogger() Logger { return &logger{log.Default()} }

// NopLogger returns a [Logger] that does nothing.
func NopLogger() Logger { return new(nopLogger) }

Expand Down
12 changes: 10 additions & 2 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,21 @@ package healthcheck

type Option func(c *Checker) error

func WithLogger(l Logger) Option {
const panicNilLogger = "healthcheck.WithLogger: Logger should not be nil"

func WithLogger(log Logger) Option {
return func(c *Checker) error {
c.log = l
if log == nil {
panic(panicNilLogger)
}

c.log = log
return nil
}
}

func WithDefaultLogger() Option { return WithLogger(DefaultLogger()) }

func WithHealthChecker(name string, check HealthChecker) Option {
if check == nil {
panic(panicNilHealthChecker)
Expand Down
6 changes: 3 additions & 3 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import (

func TestWithLogger(t *testing.T) {
t.Run("nil", func(t *testing.T) {
c := Checker{log: DefaultLogger(nil)}
assert.NoError(t, WithLogger(nil)(&c))
assert.Nil(t, c.log)
assert.PanicsWithValue(t, panicNilLogger, func() {
_ = WithLogger(nil)(nil)
})
})

t.Run("non-nil", func(t *testing.T) {
Expand Down

0 comments on commit af0b75a

Please sign in to comment.