Skip to content

Commit

Permalink
log: support save logger into context
Browse files Browse the repository at this point in the history
  • Loading branch information
mozillazg committed Nov 30, 2023
1 parent c276ada commit 0a54361
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions pkg/log/ctx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package log

import (
"context"
"fmt"
"go.uber.org/zap"
)

type contextKey struct{}

func Named(name string) *zap.SugaredLogger {
return Logger.Named(fmt.Sprintf("[%s]", name))
}

func FromContext(ctx context.Context) *zap.SugaredLogger {
if v, ok := ctx.Value(contextKey{}).(*zap.SugaredLogger); ok {
return v
}

return Logger
}

func NewContext(ctx context.Context, logger *zap.SugaredLogger) context.Context {
return context.WithValue(ctx, contextKey{}, logger)
}

func IntoContext(ctx context.Context, log *zap.SugaredLogger) context.Context {
return NewContext(ctx, log)
}

0 comments on commit 0a54361

Please sign in to comment.