From 778ac302b27278b25bb2dabfc1cda99780cbc60b Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sun, 30 Jul 2023 18:36:33 +0200 Subject: [PATCH] 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 --- log/context.go | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/log/context.go b/log/context.go index ee94d55e0..a6075a8ce 100644 --- a/log/context.go +++ b/log/context.go @@ -23,16 +23,8 @@ import ( "github.com/sirupsen/logrus" ) -var ( - // G is an alias for GetLogger. - // - // 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()) -) +// L is an alias for the standard logger. +var L = logrus.NewEntry(logrus.StandardLogger()) 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 // available, the default logger is returned. func GetLogger(ctx context.Context) *logrus.Entry { - logger := ctx.Value(loggerKey{}) - - if logger == nil { - return L.WithContext(ctx) - } - - return logger.(*logrus.Entry) + return G(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 L.WithContext(ctx) }