Skip to content

Commit dbbe28b

Browse files
committed
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/[email protected]/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 <[email protected]> (cherry picked from commit 778ac30) Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent 93b6cb7 commit dbbe28b

File tree

1 file changed

+9
-15
lines changed

1 file changed

+9
-15
lines changed

log/context.go

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,8 @@ import (
2323
"github.com/sirupsen/logrus"
2424
)
2525

26-
var (
27-
// G is an alias for GetLogger.
28-
//
29-
// We may want to define this locally to a package to get package tagged log
30-
// messages.
31-
G = GetLogger
32-
33-
// L is an alias for the standard logger.
34-
L = logrus.NewEntry(logrus.StandardLogger())
35-
)
26+
// L is an alias for the standard logger.
27+
var L = logrus.NewEntry(logrus.StandardLogger())
3628

3729
type loggerKey struct{}
3830

@@ -141,11 +133,13 @@ func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {
141133
// GetLogger retrieves the current logger from the context. If no logger is
142134
// available, the default logger is returned.
143135
func GetLogger(ctx context.Context) *logrus.Entry {
144-
logger := ctx.Value(loggerKey{})
136+
return G(ctx)
137+
}
145138

146-
if logger == nil {
147-
return L.WithContext(ctx)
139+
// G is a shorthand for [GetLogger].
140+
func G(ctx context.Context) *logrus.Entry {
141+
if logger := ctx.Value(loggerKey{}); logger != nil {
142+
return logger.(*logrus.Entry)
148143
}
149-
150-
return logger.(*logrus.Entry)
144+
return L.WithContext(ctx)
151145
}

0 commit comments

Comments
 (0)