Merge pull request #27 from iand/context
Add context support
Tim Hockin authored 3 years ago
GitHub committed 3 years ago
138 | 138 | // } |
139 | 139 | package logr |
140 | 140 | |
141 | import ( | |
142 | "context" | |
143 | ) | |
144 | ||
141 | 145 | // TODO: consider adding back in format strings if they're really needed |
142 | 146 | // TODO: consider other bits of zap/zapcore functionality like ObjectMarshaller (for arbitrary objects) |
143 | 147 | // TODO: consider other bits of glog functionality like Flush, InfoDepth, OutputStats |
188 | 192 | // InfoLogger provides compatibility with code that relies on the v0.1.0 interface |
189 | 193 | // Deprecated: use Logger instead. This will be removed in a future release. |
190 | 194 | 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 | } |