Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't panic if there is no logger in the context #22

Merged
merged 1 commit into from
Aug 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package logger

import (
"context"
"sync"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
Expand All @@ -12,8 +11,6 @@ type logFiedType int

const logField logFiedType = iota

var mu sync.Mutex

// EncoderConfig is the config of log encoder.
var EncoderConfig = zapcore.EncoderConfig{
TimeKey: "ts",
Expand Down Expand Up @@ -58,10 +55,11 @@ func With(ctx context.Context, fields ...zap.Field) context.Context {

// Get gets logger from context.
func Get(ctx context.Context) *zap.Logger {
mu.Lock()
defer mu.Unlock()

return ctx.Value(logField).(*zap.Logger)
log := ctx.Value(logField)
if log == nil {
return nil
}
return log.(*zap.Logger)
}

// WithLogger adds existing logger to context.
Expand Down