File tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change @@ -9,6 +9,7 @@ package log
99// It might seem redundant, but we really want the different output streams.
1010
1111import (
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
182203func init () {
183204 logger = logrus .New ()
You can’t perform that action at this time.
0 commit comments