Browse Source

trace: Add NewContext and FromContext functions.

These will be the standard way for inserting a Trace into a Context,
and retrieving it later. NewContext will typically only be used by
top-level context creators (e.g. the gRPC package).

Change-Id: Ifb6fc81f46a71bb965196f664714d3042a9aea18
David Symonds 10 năm trước cách đây
mục cha
commit
38f3db3860
1 tập tin đã thay đổi với 17 bổ sung0 xóa
  1. 17 0
      trace/trace.go

+ 17 - 0
trace/trace.go

@@ -36,6 +36,7 @@ import (
 	"sync/atomic"
 	"sync/atomic"
 	"time"
 	"time"
 
 
+	"golang.org/x/net/context"
 	"golang.org/x/net/internal/timeseries"
 	"golang.org/x/net/internal/timeseries"
 )
 )
 
 
@@ -207,6 +208,22 @@ func lookupBucket(fam string, b int) *traceBucket {
 	return f.Buckets[b]
 	return f.Buckets[b]
 }
 }
 
 
+type contextKeyT string
+
+var contextKey = contextKeyT("golang.org/x/net/trace.Trace")
+
+// NewContext returns a copy of the parent context
+// and associates it with a Trace.
+func NewContext(ctx context.Context, tr Trace) context.Context {
+	return context.WithValue(ctx, contextKey, tr)
+}
+
+// FromContext returns the Trace bound to the context, if any.
+func FromContext(ctx context.Context) (tr Trace, ok bool) {
+	tr, ok = ctx.Value(contextKey).(Trace)
+	return
+}
+
 // Trace represents an active request.
 // Trace represents an active request.
 type Trace interface {
 type Trace interface {
 	// LazyLog adds x to the event log. It will be evaluated each time the
 	// LazyLog adds x to the event log. It will be evaluated each time the