Created
July 13, 2020 09:50
-
-
Save ninedraft/d05ed75e42c0078a8be3d8180976b959 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package log | |
import ( | |
"context" | |
) | |
type ctxKeyType struct{} | |
var ctxKey ctxKeyType | |
// Inject stores the logger in the context. | |
func Inject(ctx context.Context, log *Logger) context.Context { | |
return context.WithValue(ctx, ctxKey, log) | |
} | |
// FromContext extracts a logger from the context or returns false, if log is not found. | |
func FromContext(ctx context.Context) (*Logger, bool) { | |
var log, ok = ctx.Value(ctxKey).(*Logger) | |
return log, ok | |
} | |
// FromContextOr extracts a logger from the context or returns the provided alternative (from the `or` parameter). | |
func FromContextOr(ctx context.Context, or *Logger) *Logger { | |
var log, ok = FromContext(ctx) | |
if !ok { | |
return or | |
} | |
return log | |
} | |
// Named extracts logger from context or uses the provided default, names it and returns context with named logger. | |
func Named(ctx context.Context, name string, def *Logger) (context.Context, *Logger) { | |
var lg = FromContextOr(ctx, def).Named(name) | |
return Inject(ctx, lg), lg | |
} | |
// MustFromContext return a non-nil logger from the context or panic if the logger is not found. | |
func MustFromContext(ctx context.Context) *Logger { | |
var log, _ = ctx.Value(ctxKey).(*Logger) | |
if log == nil { | |
panic("[log.MustFromContext] logger is not found in the context") | |
} | |
return log | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment