Skip to content

Commit 398db53

Browse files
authored
Add helpers to return a new context.Context that carries the provided logrus Entry. (#1171)
Signed-off-by: Denis Karpelevich <[email protected]>
1 parent 4f64086 commit 398db53

File tree

1 file changed

+21
-0
lines changed
  • registry-scanner/pkg/log

1 file changed

+21
-0
lines changed

registry-scanner/pkg/log/log.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ package log
99
// It might seem redundant, but we really want the different output streams.
1010

1111
import (
12+
"context"
1213
"fmt"
1314
"io"
1415
"os"
@@ -178,6 +179,26 @@ func disableLogColors() bool {
178179
return strings.ToLower(os.Getenv("ENABLE_LOG_COLORS")) == "false"
179180
}
180181

182+
// A private key type is used to prevent collisions with context keys from other packages.
183+
type loggerKey struct{}
184+
185+
// ContextWithLogger returns a new context.Context that carries the provided logrus Entry.
186+
// Use this to pass a contextual logger down through a call stack.
187+
func ContextWithLogger(ctx context.Context, logger *logrus.Entry) context.Context {
188+
return context.WithValue(ctx, loggerKey{}, logger)
189+
}
190+
191+
// LoggerFromContext retrieves the logrus Entry from the context.
192+
// If no logger is found in the context, it returns the global logger, ensuring
193+
// that a valid logger is always returned.
194+
func LoggerFromContext(ctx context.Context) *logrus.Entry {
195+
if logger, ok := ctx.Value(loggerKey{}).(*logrus.Entry); ok {
196+
return logger
197+
}
198+
// Fallback to the global logger if none is found in the context.
199+
return logrus.NewEntry(Log())
200+
}
201+
181202
// Initializes the logging subsystem with default values
182203
func init() {
183204
logger = logrus.New()

0 commit comments

Comments
 (0)