Add context methods
This commit is contained in:
parent
77726764ed
commit
19dfb55aa8
|
@ -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
|
||||||
|
}
|
|
@ -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")
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue