Codebase list golang-github-go-logr-logr / 4fa77cb
Merge pull request #27 from iand/context Add context support Tim Hockin authored 3 years ago GitHub committed 3 years ago
1 changed file(s) with 31 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
138138 // }
139139 package logr
140140
141 import (
142 "context"
143 )
144
141145 // TODO: consider adding back in format strings if they're really needed
142146 // TODO: consider other bits of zap/zapcore functionality like ObjectMarshaller (for arbitrary objects)
143147 // TODO: consider other bits of glog functionality like Flush, InfoDepth, OutputStats
188192 // InfoLogger provides compatibility with code that relies on the v0.1.0 interface
189193 // Deprecated: use Logger instead. This will be removed in a future release.
190194 type InfoLogger = Logger
195
196 type contextKey struct{}
197
198 // FromContext returns a Logger constructed from ctx or nil if no
199 // logger details are found.
200 func FromContext(ctx context.Context) Logger {
201 if v, ok := ctx.Value(contextKey{}).(Logger); ok {
202 return v
203 }
204
205 return nil
206 }
207
208 // FromContextOrDiscard returns a Logger constructed from ctx or a Logger
209 // that discards all messages if no logger details are found.
210 func FromContextOrDiscard(ctx context.Context) Logger {
211 if v, ok := ctx.Value(contextKey{}).(Logger); ok {
212 return v
213 }
214
215 return discardLogger{}
216 }
217
218 // NewContext returns a new context derived from ctx that embeds the Logger.
219 func NewContext(ctx context.Context, l Logger) context.Context {
220 return context.WithValue(ctx, contextKey{}, l)
221 }