Skip to content

Commit

Permalink
fix: ensure (Logger).exit is non-nil before calling (#132)
Browse files Browse the repository at this point in the history
On an empty logger (which we use), it's possible for (Logger).Fatal to
panic when attempting to call exit. This ensures that `l.exit` isn't nil
before calling it.
  • Loading branch information
coadler committed Dec 9, 2021
1 parent 930b877 commit 8191438
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
7 changes: 7 additions & 0 deletions slog.go
Expand Up @@ -21,6 +21,8 @@ import (
"go.opencensus.io/trace"
)

var defaultExitFn = os.Exit

// Sink is the destination of a Logger.
//
// All sinks must be safe for concurrent use.
Expand Down Expand Up @@ -114,6 +116,11 @@ func (l Logger) Critical(ctx context.Context, msg string, fields ...Field) {
func (l Logger) Fatal(ctx context.Context, msg string, fields ...Field) {
l.log(ctx, LevelFatal, msg, fields)
l.Sync()

if l.exit == nil {
l.exit = defaultExitFn
}

l.exit(1)
}

Expand Down
35 changes: 35 additions & 0 deletions slog_exit_test.go
@@ -0,0 +1,35 @@
package slog

import (
"context"
"testing"

"cdr.dev/slog/internal/assert"
)

func TestExit(t *testing.T) {
// This can't be parallel since it modifies a global variable.
t.Run("defaultExitFn", func(t *testing.T) {
var (
ctx = context.Background()
log Logger
defaultExitFnCalled bool
)

prevExitFn := defaultExitFn
t.Cleanup(func() { defaultExitFn = prevExitFn })

defaultExitFn = func(_ int) {
defaultExitFnCalled = true
}

log.Debug(ctx, "hi")
log.Info(ctx, "hi")
log.Warn(ctx, "hi")
log.Error(ctx, "hi")
log.Critical(ctx, "hi")
log.Fatal(ctx, "hi")

assert.True(t, "default exit fn used", defaultExitFnCalled)
})
}

0 comments on commit 8191438

Please sign in to comment.