@@ -17,6 +17,8 @@ limitations under the License.
17
17
package log
18
18
19
19
import (
20
+ "context"
21
+
20
22
"github.com/go-logr/logr"
21
23
. "github.com/onsi/ginkgo"
22
24
. "github.com/onsi/gomega"
@@ -214,4 +216,44 @@ var _ = Describe("logging", func() {
214
216
))
215
217
})
216
218
})
219
+
220
+ Describe ("logger from context" , func () {
221
+ It ("should return default logger when context is empty" , func () {
222
+ gotLog := FromContext (context .Background ())
223
+ Expect (gotLog ).To (Not (BeNil ()))
224
+ })
225
+
226
+ It ("should return existing logger" , func () {
227
+ root := & fakeLoggerRoot {}
228
+ baseLog := & fakeLogger {root : root }
229
+
230
+ wantLog := baseLog .WithName ("my-logger" )
231
+ ctx := IntoContext (context .Background (), wantLog )
232
+
233
+ gotLog := FromContext (ctx )
234
+ Expect (gotLog ).To (Not (BeNil ()))
235
+
236
+ gotLog .Info ("test message" )
237
+ Expect (root .messages ).To (ConsistOf (
238
+ logInfo {name : []string {"my-logger" }, msg : "test message" },
239
+ ))
240
+ })
241
+
242
+ It ("should have added key-values" , func () {
243
+ root := & fakeLoggerRoot {}
244
+ baseLog := & fakeLogger {root : root }
245
+
246
+ wantLog := baseLog .WithName ("my-logger" )
247
+ ctx := IntoContext (context .Background (), wantLog )
248
+
249
+ gotLog := FromContext (ctx , "tag1" , "value1" )
250
+ Expect (gotLog ).To (Not (BeNil ()))
251
+
252
+ gotLog .Info ("test message" )
253
+ Expect (root .messages ).To (ConsistOf (
254
+ logInfo {name : []string {"my-logger" }, tags : []interface {}{"tag1" , "value1" }, msg : "test message" },
255
+ ))
256
+ })
257
+ })
258
+
217
259
})
0 commit comments