2017-05-19 19:59:10 +00:00
|
|
|
package zerolog
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io/ioutil"
|
|
|
|
"reflect"
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestCtx(t *testing.T) {
|
|
|
|
log := New(ioutil.Discard)
|
|
|
|
ctx := log.WithContext(context.Background())
|
2017-05-20 07:22:37 +00:00
|
|
|
log2 := Ctx(ctx)
|
2017-08-30 05:53:32 +00:00
|
|
|
if !reflect.DeepEqual(log, *log2) {
|
2017-05-20 07:22:37 +00:00
|
|
|
t.Error("Ctx did not return the expected logger")
|
2017-05-19 19:59:10 +00:00
|
|
|
}
|
|
|
|
|
2017-05-20 08:48:00 +00:00
|
|
|
// update
|
|
|
|
log = log.Level(InfoLevel)
|
|
|
|
ctx = log.WithContext(ctx)
|
|
|
|
log2 = Ctx(ctx)
|
2017-08-30 05:53:32 +00:00
|
|
|
if !reflect.DeepEqual(log, *log2) {
|
2017-05-20 08:48:00 +00:00
|
|
|
t.Error("Ctx did not return the expected logger")
|
|
|
|
}
|
|
|
|
|
2017-05-20 07:22:37 +00:00
|
|
|
log2 = Ctx(context.Background())
|
2017-08-30 05:53:32 +00:00
|
|
|
if log2 != disabledLogger {
|
2017-05-20 07:22:37 +00:00
|
|
|
t.Error("Ctx did not return the expected logger")
|
2017-05-19 19:59:10 +00:00
|
|
|
}
|
2021-08-12 00:18:16 +00:00
|
|
|
|
|
|
|
DefaultContextLogger = &log
|
|
|
|
t.Cleanup(func() { DefaultContextLogger = nil })
|
|
|
|
log2 = Ctx(context.Background())
|
|
|
|
if log2 != &log {
|
|
|
|
t.Error("Ctx did not return the expected logger")
|
|
|
|
}
|
2017-05-19 19:59:10 +00:00
|
|
|
}
|
2017-08-30 05:53:32 +00:00
|
|
|
|
|
|
|
func TestCtxDisabled(t *testing.T) {
|
2018-07-03 01:23:53 +00:00
|
|
|
dl := New(ioutil.Discard).Level(Disabled)
|
|
|
|
ctx := dl.WithContext(context.Background())
|
2017-08-30 05:53:32 +00:00
|
|
|
if ctx != context.Background() {
|
|
|
|
t.Error("WithContext stored a disabled logger")
|
|
|
|
}
|
|
|
|
|
2018-07-03 01:23:53 +00:00
|
|
|
l := New(ioutil.Discard).With().Str("foo", "bar").Logger()
|
|
|
|
ctx = l.WithContext(ctx)
|
2022-02-24 00:17:11 +00:00
|
|
|
if !reflect.DeepEqual(Ctx(ctx), &l) {
|
2017-08-30 05:53:32 +00:00
|
|
|
t.Error("WithContext did not store logger")
|
|
|
|
}
|
|
|
|
|
2018-07-03 01:23:53 +00:00
|
|
|
l.UpdateContext(func(c Context) Context {
|
|
|
|
return c.Str("bar", "baz")
|
|
|
|
})
|
|
|
|
ctx = l.WithContext(ctx)
|
2022-02-24 00:17:11 +00:00
|
|
|
if !reflect.DeepEqual(Ctx(ctx), &l) {
|
2018-07-03 01:23:53 +00:00
|
|
|
t.Error("WithContext did not store updated logger")
|
|
|
|
}
|
|
|
|
|
|
|
|
l = l.Level(DebugLevel)
|
|
|
|
ctx = l.WithContext(ctx)
|
2022-02-24 00:17:11 +00:00
|
|
|
if !reflect.DeepEqual(Ctx(ctx), &l) {
|
2018-07-03 01:23:53 +00:00
|
|
|
t.Error("WithContext did not store copied logger")
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx = dl.WithContext(ctx)
|
2022-02-24 00:17:11 +00:00
|
|
|
if !reflect.DeepEqual(Ctx(ctx), &dl) {
|
2021-12-21 12:07:54 +00:00
|
|
|
t.Error("WithContext did not override logger with a disabled logger")
|
2017-08-30 05:53:32 +00:00
|
|
|
}
|
|
|
|
}
|