diff --git a/ctx.go b/ctx.go new file mode 100644 index 0000000..d5616bc --- /dev/null +++ b/ctx.go @@ -0,0 +1,16 @@ +package zerolog + +import "context" + +type ctxKey struct{} + +// WithContext returns a copy of ctx with l associated. +func (l Logger) WithContext(ctx context.Context) context.Context { + return context.WithValue(ctx, ctxKey{}, l) +} + +// FromContext returns the Logger associated with the ctx. +func FromContext(ctx context.Context) (l Logger, ok bool) { + l, ok = ctx.Value(ctxKey{}).(Logger) + return +} diff --git a/ctx_test.go b/ctx_test.go new file mode 100644 index 0000000..770e670 --- /dev/null +++ b/ctx_test.go @@ -0,0 +1,28 @@ +package zerolog + +import ( + "context" + "io/ioutil" + "reflect" + "testing" +) + +func TestCtx(t *testing.T) { + log := New(ioutil.Discard) + ctx := log.WithContext(context.Background()) + log2, ok := FromContext(ctx) + if !ok { + t.Error("Expected ok=true from FromContext") + } + if !reflect.DeepEqual(log, log2) { + t.Error("FromContext did not return the expected logger") + } + + log2, ok = FromContext(context.Background()) + if ok { + t.Error("Expected ok=false from FromContext") + } + if !reflect.DeepEqual(log2, Logger{}) { + t.Error("FromContext did not return the expected logger") + } +}