2019-06-14 16:32:09 -06:00
|
|
|
// Copyright 2019 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2019-06-26 20:46:12 -06:00
|
|
|
// Package trace adds support for telemetry tracing.
|
2019-06-14 16:32:09 -06:00
|
|
|
package trace
|
|
|
|
|
2019-06-24 22:50:01 -06:00
|
|
|
import (
|
|
|
|
"context"
|
2019-06-26 20:46:12 -06:00
|
|
|
"time"
|
2019-06-14 16:32:09 -06:00
|
|
|
|
2019-08-14 10:51:42 -06:00
|
|
|
"golang.org/x/tools/internal/telemetry"
|
|
|
|
"golang.org/x/tools/internal/telemetry/export"
|
2019-08-13 13:07:39 -06:00
|
|
|
"golang.org/x/tools/internal/telemetry/tag"
|
2019-06-14 16:32:09 -06:00
|
|
|
)
|
|
|
|
|
2019-08-14 10:51:42 -06:00
|
|
|
func StartSpan(ctx context.Context, name string, tags ...telemetry.Tag) (context.Context, func()) {
|
|
|
|
start := time.Now()
|
|
|
|
span := &telemetry.Span{Name: name}
|
|
|
|
if parent := telemetry.GetSpan(ctx); parent != nil {
|
|
|
|
span.ID.TraceID = parent.ID.TraceID
|
|
|
|
span.ParentID = parent.ID.SpanID
|
2019-06-26 20:46:12 -06:00
|
|
|
} else {
|
2019-08-14 10:51:42 -06:00
|
|
|
span.ID.TraceID = telemetry.NewTraceID()
|
2019-06-26 20:46:12 -06:00
|
|
|
}
|
2019-08-14 10:51:42 -06:00
|
|
|
span.ID.SpanID = telemetry.NewSpanID()
|
|
|
|
ctx = telemetry.WithSpan(ctx, span)
|
2019-06-26 20:46:12 -06:00
|
|
|
if len(tags) > 0 {
|
|
|
|
ctx = tag.With(ctx, tags...)
|
|
|
|
}
|
2019-08-14 10:51:42 -06:00
|
|
|
export.StartSpan(ctx, span, start)
|
|
|
|
return ctx, func() { export.FinishSpan(ctx, span, time.Now()) }
|
2019-06-26 20:46:12 -06:00
|
|
|
}
|
2019-07-16 20:20:43 -06:00
|
|
|
|
|
|
|
// Detach returns a context without an associated span.
|
|
|
|
// This allows the creation of spans that are not children of the current span.
|
2019-06-26 20:46:12 -06:00
|
|
|
func Detach(ctx context.Context) context.Context {
|
2019-08-14 10:51:42 -06:00
|
|
|
return telemetry.WithSpan(ctx, nil)
|
2019-06-26 20:46:12 -06:00
|
|
|
}
|