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
9
9
// It might seem redundant, but we really want the different output streams.
10
10
11
11
import (
12
+ "context"
12
13
"fmt"
13
14
"io"
14
15
"os"
@@ -178,6 +179,26 @@ func disableLogColors() bool {
178
179
return strings .ToLower (os .Getenv ("ENABLE_LOG_COLORS" )) == "false"
179
180
}
180
181
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
+
181
202
// Initializes the logging subsystem with default values
182
203
func init () {
183
204
logger = logrus .New ()
You can’t perform that action at this time.
0 commit comments