log: define G() as a function instead of a variable
The `G` variable is exported, and not expected to be overwritten externally. Defining it as a function also documents it as a function on https://pkg.go.dev, instead of a variable; https://pkg.go.dev/github.com/containerd/containerd@v1.6.22/log#pkg-variables Note that (while the godoc suggests otherwise) I made `GetLogger` an alias for `G`, as `G` is the most commonly used function (not the other way round), although I don't think there's a performance gain in doing so. Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
parent
81ac648d91
commit
778ac302b2
@ -23,16 +23,8 @@ import (
|
|||||||
"github.com/sirupsen/logrus"
|
"github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
// L is an alias for the standard logger.
|
||||||
// G is an alias for GetLogger.
|
var L = logrus.NewEntry(logrus.StandardLogger())
|
||||||
//
|
|
||||||
// We may want to define this locally to a package to get package tagged log
|
|
||||||
// messages.
|
|
||||||
G = GetLogger
|
|
||||||
|
|
||||||
// L is an alias for the standard logger.
|
|
||||||
L = logrus.NewEntry(logrus.StandardLogger())
|
|
||||||
)
|
|
||||||
|
|
||||||
type loggerKey struct{}
|
type loggerKey struct{}
|
||||||
|
|
||||||
@ -141,11 +133,13 @@ func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {
|
|||||||
// GetLogger retrieves the current logger from the context. If no logger is
|
// GetLogger retrieves the current logger from the context. If no logger is
|
||||||
// available, the default logger is returned.
|
// available, the default logger is returned.
|
||||||
func GetLogger(ctx context.Context) *logrus.Entry {
|
func GetLogger(ctx context.Context) *logrus.Entry {
|
||||||
logger := ctx.Value(loggerKey{})
|
return G(ctx)
|
||||||
|
}
|
||||||
if logger == nil {
|
|
||||||
return L.WithContext(ctx)
|
// G is a shorthand for [GetLogger].
|
||||||
}
|
func G(ctx context.Context) *logrus.Entry {
|
||||||
|
if logger := ctx.Value(loggerKey{}); logger != nil {
|
||||||
return logger.(*logrus.Entry)
|
return logger.(*logrus.Entry)
|
||||||
|
}
|
||||||
|
return L.WithContext(ctx)
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user