Variables

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var (

// ErrUnsupportedFormat occurs when the `format` passed to Tracer.Inject() or
	// Tracer.Extract() is not recognized by the Tracer implementation.
	ErrUnsupportedFormat = errors.New("opentracing: Unknown or unsupported Inject/Extract format")

	// ErrSpanContextNotFound occurs when the `carrier` passed to
	// Tracer.Extract() is valid and uncorrupted but has insufficient
	// information to extract a SpanContext.
	ErrSpanContextNotFound = errors.New("opentracing: SpanContext not found in Extract carrier")

	// ErrInvalidSpanContext errors occur when Tracer.Inject() is asked to
	// operate on a SpanContext which it is not prepared to handle (for
	// example, since it was created by a different tracer implementation).
	ErrInvalidSpanContext = errors.New("opentracing: SpanContext type incompatible with tracer")

	// ErrInvalidCarrier errors occur when Tracer.Inject() or Tracer.Extract()
	// implementations expect a different type of `carrier` than they are
	// given.
	ErrInvalidCarrier = errors.New("opentracing: Invalid Inject/Extract carrier")

	// ErrSpanContextCorrupted occurs when the `carrier` passed to
	// Tracer.Extract() is of the expected type but is corrupted.
	ErrSpanContextCorrupted = errors.New("opentracing: SpanContext data corrupted in Extract carrier")
)

func ContextWithSpan

1
func ContextWithSpan(ctx context.Context, span Span) context.Context

ContextWithSpan返回一个新的“ context.Context”,其中包含对span的引用。如果span为nil,则返回没有活动span的新context。

func InitGlobalTracer

1
func InitGlobalTracer(tracer Tracer)

不建议使用InitGlobalTracer。请使用SetGlobalTracer。

func IsGlobalTracerRegistered

1
func IsGlobalTracerRegistered() bool

IsGlobalTracerRegistered返回“bool”,以指示是否已全局注册跟踪器

func SetGlobalTracer

1
func SetGlobalTracer(tracer Tracer)

SetGlobalTracer sets the [singleton] opentracing.Tracer returned by GlobalTracer(). Those who use GlobalTracer (rather than directly manage an opentracing.Tracer instance) should call SetGlobalTracer as early as possible in main(), prior to calling the StartSpan global func below. Prior to calling SetGlobalTracer, any Spans started via the StartSpan (etc) globals are noops.

SetGlobalTracer设置由GlobalTracer()返回的单例opentracing.Tracer。那些使用GlobalTracer(而不是直接管理opentracing.Tracer实例)的用户应在main()之前尽早调用SetGlobalTracer,然后再调用下面的StartSpan全局函数。在调用SetGlobalTracer之前,通过StartSpan等全局变量启动的所有Span都是noop。

type BuiltinFormat

1
type BuiltinFormat byte

BuiltinFormat用于在“opentracing”包中划分与Tracer.Inject()和Tracer.Extract()方法一起使用的值。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const (
	// Binary represents SpanContexts as opaque binary data.
	//
	// For Tracer.Inject(): the carrier must be an `io.Writer`.
	//
	// For Tracer.Extract(): the carrier must be an `io.Reader`.
	Binary BuiltinFormat = iota

	// TextMap represents SpanContexts as key:value string pairs.
	//
	// Unlike HTTPHeaders, the TextMap format does not restrict the key or
	// value character sets in any way.
	//
	// For Tracer.Inject(): the carrier must be a `TextMapWriter`.
	//
	// For Tracer.Extract(): the carrier must be a `TextMapReader`.
	TextMap

	// HTTPHeaders represents SpanContexts as HTTP header string pairs.
	//
	// Unlike TextMap, the HTTPHeaders format requires that the keys and values
	// be valid as HTTP headers as-is (i.e., character casing may be unstable
	// and special characters are disallowed in keys, values should be
	// URL-escaped, etc).
	//
	// For Tracer.Inject(): the carrier must be a `TextMapWriter`.
	//
	// For Tracer.Extract(): the carrier must be a `TextMapReader`.
	//
	// See HTTPHeadersCarrier for an implementation of both TextMapWriter
	// and TextMapReader that defers to an http.Header instance for storage.
	// For example, Inject():
	//
	//    carrier := opentracing.HTTPHeadersCarrier(httpReq.Header)
	//    err := span.Tracer().Inject(
	//        span.Context(), opentracing.HTTPHeaders, carrier)
	//
	// Or Extract():
	//
	//    carrier := opentracing.HTTPHeadersCarrier(httpReq.Header)
	//    clientContext, err := tracer.Extract(
	//        opentracing.HTTPHeaders, carrier)
	//
	HTTPHeaders
)

type FinishOptions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
type FinishOptions struct {

// FinishTime overrides the Span's finish time, or implicitly becomes
	// time.Now() if FinishTime.IsZero().
	//
	// FinishTime must resolve to a timestamp that's >= the Span's StartTime
	// (per StartSpanOptions).
	FinishTime time.Time

	// LogRecords allows the caller to specify the contents of many LogFields()
	// calls with a single slice. May be nil.
	//
	// None of the LogRecord.Timestamp values may be .IsZero() (i.e., they must
	// be set explicitly). Also, they must be >= the Span's start timestamp and
	// <= the FinishTime (or time.Now() if FinishTime.IsZero()). Otherwise the
	// behavior of FinishWithOptions() is undefined.
	//
	// If specified, the caller hands off ownership of LogRecords at
	// FinishWithOptions() invocation time.
	//
	// If specified, the (deprecated) BulkLogData must be nil or empty.
	LogRecords []LogRecord

	// BulkLogData is DEPRECATED.
	BulkLogData []LogData
}

FinishOptions允许Span.FinishWithOptions调用方覆盖完成时间戳,并通过批量接口提供日志数据。

type HTTPHeadersCarrier

1
type HTTPHeadersCarrier http.Header

HTTPHeadersCarrier同时满足TextMapWriter和TextMapReader。

服务器端用法示例:

1
2
carrier := opentracing.HTTPHeadersCarrier(httpReq.Header)
clientContext, err := tracer.Extract(opentracing.HTTPHeaders, carrier)

客户端的用法示例:

1
2
3
4
5
carrier := opentracing.HTTPHeadersCarrier(httpReq.Header)
err := tracer.Inject(
    span.Context(),
    opentracing.HTTPHeaders,
    carrier)

func (HTTPHeadersCarrier) ForeachKey

1
func (c HTTPHeadersCarrier) ForeachKey(handler func(key, val string) error) error

ForeachKey符合TextMapReader接口。

func (HTTPHeadersCarrier) Set

1
func (c HTTPHeadersCarrier) Set(key, val string)

Set符合TextMapWriter接口。

type LogData

1
2
3
4
5
type LogData struct {
    Timestamp time.Time
	Event     string
	Payload   interface{}
}

LogData已弃用

func (*LogData) ToLogRecord

1
func (ld *LogData) ToLogRecord() LogRecord

ToLogRecord将不推荐使用的LogData转换为推荐使用的LogRecord

type LogRecord

1
2
3
4
type LogRecord struct {
    Timestamp time.Time
	Fields    []log.Field
}

LogRecord是与单个Span日志关联的数据。每个LogRecord实例必须至少指定一个字段。

type NoopTracer

1
type NoopTracer struct{}

NoopTracer是Tracer的一个琐碎的,最小开销的实现,所有操作均禁止操作。

此实现的主要用途是在诸如RPC框架之类的库中,这些库使跟踪由最终用户控制的可选功能成为可能。无操作实现允许所述库将其用作默认跟踪程序,不需要编写继续检查跟踪程序实例是否为nil的工具。

出于相同的原因,NoopTracer是默认的“全局”跟踪器(请参阅GlobalTracer和SetGlobalTracer函数)。

警告:NoopTracer不支持baggage运输。

func (NoopTracer) Extract

1
func (n NoopTracer) Extract(format interface{}, carrier interface{}) (SpanContext, error)

提取属于Tracer接口。

func (NoopTracer) Inject

1
func (n NoopTracer) Inject(sp SpanContext, format interface{}, carrier interface{}) error

注入属于Tracer接口。

func (NoopTracer) StartSpan

1
func (n NoopTracer) StartSpan(operationName string, opts ...StartSpanOption) Span

StartSpan属于Tracer接口。

type Span

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
type Span interface {

// Sets the end timestamp and finalizes Span state.
	//
	// With the exception of calls to Context() (which are always allowed),
	// Finish() must be the last call made to any span instance, and to do
	// otherwise leads to undefined behavior.
	Finish()
	// FinishWithOptions is like Finish() but with explicit control over
	// timestamps and log data.
	FinishWithOptions(opts FinishOptions)

	// Context() yields the SpanContext for this Span. Note that the return
	// value of Context() is still valid after a call to Span.Finish(), as is
	// a call to Span.Context() after a call to Span.Finish().
	Context() SpanContext

	// Sets or changes the operation name.
	//
	// Returns a reference to this Span for chaining.
	SetOperationName(operationName string) Span

	// Adds a tag to the span.
	//
	// If there is a pre-existing tag set for `key`, it is overwritten.
	//
	// Tag values can be numeric types, strings, or bools. The behavior of
	// other tag value types is undefined at the OpenTracing level. If a
	// tracing system does not know how to handle a particular value type, it
	// may ignore the tag, but shall not panic.
	//
	// Returns a reference to this Span for chaining.
	SetTag(key string, value interface{}) Span

	// LogFields is an efficient and type-checked way to record key:value
	// logging data about a Span, though the programming interface is a little
	// more verbose than LogKV(). Here's an example:
	//
	//    span.LogFields(
	//        log.String("event", "soft error"),
	//        log.String("type", "cache timeout"),
	//        log.Int("waited.millis", 1500))
	//
	// Also see Span.FinishWithOptions() and FinishOptions.BulkLogData.
	LogFields(fields ...log.Field)

	// LogKV is a concise, readable way to record key:value logging data about
	// a Span, though unfortunately this also makes it less efficient and less
	// type-safe than LogFields(). Here's an example:
	//
	//    span.LogKV(
	//        "event", "soft error",
	//        "type", "cache timeout",
	//        "waited.millis", 1500)
	//
	// For LogKV (as opposed to LogFields()), the parameters must appear as
	// key-value pairs, like
	//
	//    span.LogKV(key1, val1, key2, val2, key3, val3, ...)
	//
	// The keys must all be strings. The values may be strings, numeric types,
	// bools, Go error instances, or arbitrary structs.
	//
	// (Note to implementors: consider the log.InterleavedKVToFields() helper)
	LogKV(alternatingKeyValues ...interface{})

	// SetBaggageItem sets a key:value pair on this Span and its SpanContext
	// that also propagates to descendants of this Span.
	//
	// SetBaggageItem() enables powerful functionality given a full-stack
	// opentracing integration (e.g., arbitrary application data from a mobile
	// app can make it, transparently, all the way into the depths of a storage
	// system), and with it some powerful costs: use this feature with care.
	//
	// IMPORTANT NOTE #1: SetBaggageItem() will only propagate baggage items to
	// *future* causal descendants of the associated Span.
	//
	// IMPORTANT NOTE #2: Use this thoughtfully and with care. Every key and
	// value is copied into every local *and remote* child of the associated
	// Span, and that can add up to a lot of network and cpu overhead.
	//
	// Returns a reference to this Span for chaining.
	SetBaggageItem(restrictedKey, value string) Span

	// Gets the value for a baggage item given its key. Returns the empty string
	// if the value isn't found in this Span.
	BaggageItem(restrictedKey string) string

	// Provides access to the Tracer that created this Span.
	Tracer() Tracer

	// Deprecated: use LogFields or LogKV
	LogEvent(event string)
	// Deprecated: use LogFields or LogKV
	LogEventWithPayload(event string, payload interface{})
	// Deprecated: use LogFields or LogKV
	Log(data LogData)
}

Span表示OpenTracing系统中活动的未完成的span。

Span由Tracer接口创建。

func SpanFromContext

1
func SpanFromContext(ctx context.Context) Span

SpanFromContext返回以前与ctx关联的Span,如果找不到这样的Span,则返回nil。

注意:context.Context!= SpanContext:前者是Go的进程内上下文传播机制,后者是OpenTracing的每span标识和行李信息。

func StartSpan

1
func StartSpan(operationName string, opts ...StartSpanOption) Span

StartSpan遵循Tracer.StartSpan。参见GlobalTracer()

func StartSpanFromContext

1
func StartSpanFromContext(ctx context.Context, operationName string, opts ...StartSpanOption) (Span, context.Context)

StartSpanFromContext启动并返回带有“operationName”的Span,使用在“ctx”中找到的任何Span作为ChildOfRef。如果找不到此类父级,则StartSpanFromContext将创建一个根(无父级)span。

第二个返回值是围绕返回的Span构建的context.Context对象。

用法示例:

1
2
3
4
5
SomeFunction(ctx context.Context, ...) {
    sp, ctx := opentracing.StartSpanFromContext(ctx, "SomeFunction")
    defer sp.Finish()
    ...
}

func StartSpanFromContextWithTracer

1
func StartSpanFromContextWithTracer(ctx context.Context, tracer Tracer, operationName string, opts ...StartSpanOption) (Span, context.Context)

StartSpanFromContextWithTracer使用在context中找到的span作为ChildOfRef来启动并返回带有“ operationName”的span。如果不存在,则会创建一个根范围。它还返回一个context.Context对象,该对象围绕返回的范围构建。

它的行为与StartSpanFromContext相同,除了它使用显式跟踪程序而不是使用全局跟踪程序。

type SpanContext

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type SpanContext interface {

// ForeachBaggageItem grants access to all baggage items stored in the
	// SpanContext.
	// The handler function will be called for each baggage key/value pair.
	// The ordering of items is not guaranteed.
	//
	// The bool return value indicates if the handler wants to continue iterating
	// through the rest of the baggage items; for example if the handler is trying to
	// find some baggage item by pattern matching the name, it can return false
	// as soon as the item is found to stop further iterations.
	ForeachBaggageItem(handler func(k, v string) bool)
}

SpanContext表示必须传播到后代Span并跨越进程边界的Span状态(例如,<trace_id,span_id,sampled>元组)。

type SpanReference

1
2
3
4
type SpanReference struct {
    Type              SpanReferenceType
	ReferencedContext SpanContext
}

SpanReference是将SpanReferenceType和引用的SpanContext配对的StartSpanOption。有关受支持的关系,请参见SpanReferenceType文档。如果SpanReference是使用ReferencedContext == nil创建的,则无效。因此,它为开始span提供了更简洁的语法:

1
2
sc, _ := tracer.Extract(someFormat, someCarrier)
span := tracer.StartSpan("operation", opentracing.ChildOf(sc))

如果sc == nil,则上面的ChildOf(sc)选项不会惊慌,只会将父级span引用添加到选项中。

func ChildOf

1
func ChildOf(sc SpanContext) SpanReference

ChildOf返回一个StartSpanOption,它指向一个依赖的父范围。如果sc == nil,则该选项无效。

参见ChildOfRef,SpanReference

func FollowsFrom

1
func FollowsFrom(sc SpanContext) SpanReference

FollowsFrom返回一个StartSpanOption,它指向导致子Span的父Span,但不以任何方式直接取决于其结果。如果sc == nil,则该选项无效。

请参见FollowsFromRef,SpanReference

func (SpanReference) Apply

1
func (r SpanReference) Apply(o *StartSpanOptions)

Apply 满足StartSpanOption接口.

type SpanReferenceType

1
type SpanReferenceType int

panReferenceType是一个枚举类型,描述了两个Span之间关系的不同类别。如果Span-2引用Span-1,则SpanReferenceType从Span-2的角度描述Span-1。例如,ChildOfRef表示Span-1创建了Span-2。

注意:Span-1和Span-2不一定*彼此依赖才能完成;例如,Span-2可能是Span-1排队的后台作业的一部分,或者Span-2可能坐在Span-1后面的分布式队列中。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const (
	// ChildOfRef refers to a parent Span that caused *and* somehow depends
	// upon the new child Span. Often (but not always), the parent Span cannot
	// finish until the child Span does.
	//
	// An timing diagram for a ChildOfRef that's blocked on the new Span:
	//
	//     [-Parent Span---------]
	//          [-Child Span----]
	//
	// See <http://opentracing.io/spec/>
	//
	// See opentracing.ChildOf()
	ChildOfRef SpanReferenceType = iota

	// FollowsFromRef refers to a parent Span that does not depend in any way
	// on the result of the new child Span. For instance, one might use
	// FollowsFromRefs to describe pipeline stages separated by queues,
	// or a fire-and-forget cache insert at the tail end of a web request.
	//
	// A FollowsFromRef Span is part of the same logical trace as the new Span:
	// i.e., the new Span is somehow caused by the work of its FollowsFromRef.
	//
	// All of the following could be valid timing diagrams for children that
	// "FollowFrom" a parent.
	//
	//     [-Parent Span-]  [-Child Span-]
	//
	//
	//     [-Parent Span--]
	//      [-Child Span-]
	//
	//
	//     [-Parent Span-]
	//                 [-Child Span-]
	//
	// See http://opentracing.io/spec/
	//
	// See opentracing.FollowsFrom()
	FollowsFromRef
)

type StartSpanOption

1
2
3
type StartSpanOption interface {
    Apply(*StartSpanOptions)
}

StartSpanOption实例(零个或多个)可以传递给Tracer.StartSpan。

根据http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis,StartSpanOption借鉴了“功能选项”模式

type StartSpanOptions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type StartSpanOptions struct {
    // Zero or more causal references to other Spans (via their SpanContext).
	// If empty, start a "root" Span (i.e., start a new trace).
	References []SpanReference

	// StartTime overrides the Span's start time, or implicitly becomes
	// time.Now() if StartTime.IsZero().
	StartTime time.Time

	// Tags may have zero or more entries; the restrictions on map values are
	// identical to those for Span.SetTag(). May be nil.
	//
	// If specified, the caller hands off ownership of Tags at
	// StartSpan() invocation time.
	Tags map[string]interface{}
}

StartSpanOptions允许Tracer.StartSpan()调用者和实现者一种机制来覆盖开始时间戳,指定Span引用以及在Span开始时提供单个或多个Tag。

StartSpan()调用者应查看此包中可用的StartSpanOption接口和实现。

跟踪程序的实现可以将StartSpanOption实例的一部分转换为StartSpanOptions结构,如下所示:

1
2
3
4
5
6
7
func StartSpan(opName string, opts ...opentracing.StartSpanOption) {
    sso := opentracing.StartSpanOptions{}
    for _, o := range opts {
        o.Apply(&sso)
    }
    ...
}

type StartTime

1
type StartTime time.Time

StartTime是一个StartSpanOption,它为新Span设置了明确的开始时间戳。

func (StartTime) Apply

1
func (t StartTime) Apply(o *StartSpanOptions)

Apply 满足StartSpanOption接口.

type Tag

1
2
3
4
type Tag struct {
    Key   string
	Value interface{}
}

标记可以作为StartSpanOption传递,以将标记添加到新的span,或者可以使用其Set方法将标记应用于现有Span,例如:

1
tracer.StartSpan("opName", Tag{"Key", value})

or

1
Tag{"key", value}.Set(span)

func (Tag) Apply

1
func (t Tag) Apply(o *StartSpanOptions)

Apply 满足StartSpanOption接口.

func (Tag) Set

1
func (t Tag) Set(s Span)

Set将标签应用于现有的Span。

type Tags

1
type Tags map[string]interface{}

标签是从任意字符串键到不透明值类型的通用映射。基础跟踪系统负责解释和序列化值。

func (Tags) Apply

1
func (t Tags) Apply(o *StartSpanOptions)

Apply 满足StartSpanOption接口.

type TextMapCarrier

1
type TextMapCarrier map[string]string

TextMapCarrier允许将常规map[string]string用作TextMapWriter和TextMapReader。

func (TextMapCarrier) ForeachKey

1
func (c TextMapCarrier) ForeachKey(handler func(key, val string) error) error

ForeachKey符合TextMapReader接口。

func (TextMapCarrier) Set

1
func (c TextMapCarrier) Set(key, val string)

Set实现opentracing.TextMapWriter的Set()

type TextMapReader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
type TextMapReader interface {
    // ForeachKey returns TextMap contents via repeated calls to the `handler`
	// function. If any call to `handler` returns a non-nil error, ForeachKey
	// terminates and returns that error.
	//
	// NOTE: The backing store for the TextMapReader may contain data unrelated
	// to SpanContext. As such, Inject() and Extract() implementations that
	// call the TextMapWriter and TextMapReader interfaces must agree on a
	// prefix or other convention to distinguish their own key:value pairs.
	//
	// The "foreach" callback pattern reduces unnecessary copying in some cases
	// and also allows implementations to hold locks while the map is read.
	ForeachKey(handler func(key, val string) error) error
}

TextMapReader是TextMap内置格式的Extract()载体。使用它,调用方可以将传播的SpanContext解码为unicode字符串映射中的条目。

type TextMapWriter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type TextMapWriter interface {
    // Set a key:value pair to the carrier. Multiple calls to Set() for the
	// same key leads to undefined behavior.
	//
	// NOTE: The backing store for the TextMapWriter may contain data unrelated
	// to SpanContext. As such, Inject() and Extract() implementations that
	// call the TextMapWriter and TextMapReader interfaces must agree on a
	// prefix or other convention to distinguish their own key:value pairs.
	Set(key, val string)
}

TextMapWriter是TextMap内置格式的Inject()载体。有了它,调用者可以对SpanContext进行编码,以作为unicode字符串映射中的条目传播。

type Tracer

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
type Tracer interface {
	// Create, start, and return a new Span with the given `operationName` and
	// incorporate the given StartSpanOption `opts`. (Note that `opts` borrows
	// from the "functional options" pattern, per
	// http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis)
	//
	// A Span with no SpanReference options (e.g., opentracing.ChildOf() or
	// opentracing.FollowsFrom()) becomes the root of its own trace.
	//
	// Examples:
	//
	//     var tracer opentracing.Tracer = ...
	//
	//     // The root-span case:
	//     sp := tracer.StartSpan("GetFeed")
	//
	//     // The vanilla child span case:
	//     sp := tracer.StartSpan(
	//         "GetFeed",
	//         opentracing.ChildOf(parentSpan.Context()))
	//
	//     // All the bells and whistles:
	//     sp := tracer.StartSpan(
	//         "GetFeed",
	//         opentracing.ChildOf(parentSpan.Context()),
	//         opentracing.Tag{"user_agent", loggedReq.UserAgent},
	//         opentracing.StartTime(loggedReq.Timestamp),
	//     )
	//
	StartSpan(operationName string, opts ...StartSpanOption) Span

	// Inject() takes the `sm` SpanContext instance and injects it for
	// propagation within `carrier`. The actual type of `carrier` depends on
	// the value of `format`.
	//
	// OpenTracing defines a common set of `format` values (see BuiltinFormat),
	// and each has an expected carrier type.
	//
	// Other packages may declare their own `format` values, much like the keys
	// used by `context.Context` (see https://godoc.org/context#WithValue).
	//
	// Example usage (sans error handling):
	//
	//     carrier := opentracing.HTTPHeadersCarrier(httpReq.Header)
	//     err := tracer.Inject(
	//         span.Context(),
	//         opentracing.HTTPHeaders,
	//         carrier)
	//
	// NOTE: All opentracing.Tracer implementations MUST support all
	// BuiltinFormats.
	//
	// Implementations may return opentracing.ErrUnsupportedFormat if `format`
	// is not supported by (or not known by) the implementation.
	//
	// Implementations may return opentracing.ErrInvalidCarrier or any other
	// implementation-specific error if the format is supported but injection
	// fails anyway.
	//
	// See Tracer.Extract().
	Inject(sm SpanContext, format interface{}, carrier interface{}) error

	// Extract() returns a SpanContext instance given `format` and `carrier`.
	//
	// OpenTracing defines a common set of `format` values (see BuiltinFormat),
	// and each has an expected carrier type.
	//
	// Other packages may declare their own `format` values, much like the keys
	// used by `context.Context` (see
	// https://godoc.org/golang.org/x/net/context#WithValue).
	//
	// Example usage (with StartSpan):
	//
	//
	//     carrier := opentracing.HTTPHeadersCarrier(httpReq.Header)
	//     clientContext, err := tracer.Extract(opentracing.HTTPHeaders, carrier)
	//
	//     // ... assuming the ultimate goal here is to resume the trace with a
	//     // server-side Span:
	//     var serverSpan opentracing.Span
	//     if err == nil {
	//         span = tracer.StartSpan(
	//             rpcMethodName, ext.RPCServerOption(clientContext))
	//     } else {
	//         span = tracer.StartSpan(rpcMethodName)
	//     }
	//
	//
	// NOTE: All opentracing.Tracer implementations MUST support all
	// BuiltinFormats.
	//
	// Return values:
	//  - A successful Extract returns a SpanContext instance and a nil error
	//  - If there was simply no SpanContext to extract in `carrier`, Extract()
	//    returns (nil, opentracing.ErrSpanContextNotFound)
	//  - If `format` is unsupported or unrecognized, Extract() returns (nil,
	//    opentracing.ErrUnsupportedFormat)
	//  - If there are more fundamental problems with the `carrier` object,
	//    Extract() may return opentracing.ErrInvalidCarrier,
	//    opentracing.ErrSpanContextCorrupted, or implementation-specific
	//    errors.
	//
	// See Tracer.Inject().
	Extract(format interface{}, carrier interface{}) (SpanContext, error)
}

Tracer是用于Span创建和SpanContext传播的简单的接口。

func GlobalTracer

1
func GlobalTracer() Tracer

GlobalTracer返回全局单例“Tracer”实现。在调用SetGlobalTracer()之前,GlobalTracer()是一个noop实现,它将丢弃传递给它的所有数据。

type TracerContextWithSpanExtension

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
type TracerContextWithSpanExtension interface {
    // ContextWithSpanHook gets called by the ContextWithSpan
	// function, when the Tracer implementation also implements
	// this interface. It allows to put extra information into the
	// context and make it available to the callers of the
	// ContextWithSpan.
	//
	// This hook is invoked before the ContextWithSpan function
	// actually puts the span into the context.
	ContextWithSpanHook(ctx context.Context, span Span) context.Context
}

TracerContextWithSpanExtension是Tracer接口的实现可能想要实现的扩展接口。当调用ContextWithSpan时,它可以对go上下文进行一些控制。

此扩展的主要目的是从opentracing API到其他一些跟踪API的适配器。