fix: logging.From panic (#268)

This commit is contained in:
Martin Kobetic 2022-07-23 08:12:56 -04:00 committed by GitHub
parent 1d88f03caa
commit fbdc814b1b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 2 deletions

View File

@ -8,9 +8,11 @@ import (
var logKey = &struct{}{} var logKey = &struct{}{}
// From allows retrieving the Logger from a Context // From allows retrieving the Logger from a Context.
// Returns nil if Context does not have one.
func From(ctx context.Context) *zap.Logger { func From(ctx context.Context) *zap.Logger {
return ctx.Value(logKey).(*zap.Logger) logger, _ := ctx.Value(logKey).(*zap.Logger)
return logger
} }
// With associates a Logger with a Context to allow passing // With associates a Logger with a Context to allow passing

21
logging/context_test.go Normal file
View File

@ -0,0 +1,21 @@
package logging
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
func Test_EmptyContext(t *testing.T) {
logger := From(context.Background())
require.Nil(t, logger)
}
func Test_With(t *testing.T) {
logger, err := zap.NewDevelopment()
require.NoError(t, err)
ctx := With(context.Background(), logger)
require.Equal(t, logger, From(ctx))
}