Allow trace plugins to be registered from outside the package.

Fixes #248
This commit is contained in:
Anthony Yeh 2014-12-16 15:39:09 -08:00
Родитель 60e61c8304
Коммит 001586999a
2 изменённых файлов: 41 добавлений и 5 удалений

Просмотреть файл

@ -3,7 +3,8 @@
// license that can be found in the LICENSE file.
// Package trace contains a helper interface that allows various tracing
// tools to be plugged in to components using this interface.
// tools to be plugged in to components using this interface. If no plugin is
// registered, the default one makes all trace calls into no-ops.
package trace
import (
@ -57,13 +58,23 @@ func NewSpanFromContext(ctx context.Context) Span {
return NewSpan(nil)
}
// spanFactory should be changed by a plugin during init() to a factory that
// creates an actual Span implementation for that plugin's tracing framework.
var spanFactory interface {
// SpanFactory is an interface for creating spans or extracting them from Contexts.
type SpanFactory interface {
New(parent Span) Span
FromContext(ctx context.Context) (Span, bool)
NewContext(parent context.Context, span Span) context.Context
} = fakeSpanFactory{}
}
var spanFactory SpanFactory = fakeSpanFactory{}
// RegisterSpanFactory should be called by a plugin during init() to install a
// factory that creates Spans for that plugin's tracing framework. Each call to
// RegisterSpanFactory will overwrite any previous setting. If no factory is
// registered, the default fake factory will produce Spans whose methods are all
// no-ops.
func RegisterSpanFactory(sf SpanFactory) {
spanFactory = sf
}
type fakeSpanFactory struct{}

25
go/trace/trace_test.go Normal file
Просмотреть файл

@ -0,0 +1,25 @@
// Copyright 2014, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package trace
import (
"testing"
"golang.org/x/net/context"
)
func TestFakeSpan(t *testing.T) {
ctx := context.Background()
RegisterSpanFactory(fakeSpanFactory{})
// It should be safe to call all the usual methods as if a plugin were installed.
span := NewSpanFromContext(ctx)
span.StartLocal("label")
span.StartClient("label")
span.StartServer("label")
span.Annotate("key", "value")
span.Finish()
NewContext(ctx, span)
}