Add context methods

This commit is contained in:
Olivier Poitrey 2017-05-19 12:59:10 -07:00
parent 77726764ed
commit 19dfb55aa8
2 changed files with 44 additions and 0 deletions

16
ctx.go Normal file
View File

@ -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
}

28
ctx_test.go Normal file
View File

@ -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")
}
}