未验证 提交 f10048c7 编写于 作者: Z zhang-wei 提交者: GitHub

add TraceID(ctx context.Context) (#41)

上级 01c5495c
......@@ -41,6 +41,14 @@ passing `context.Background()`. We must also be sure to end this span, which wil
span, ctx, err := tracer.CreateLocalSpan(context.Background())
```
## Get Global TraceID
Get the `TraceID` of the `activeSpan` in the `Context`.
```go
go2sky.TraceID(ctx)
```
## Create a sub span
A sub span created as the children of root span links to its parent with `Context`.
......
......@@ -18,6 +18,8 @@
package go2sky
import (
"fmt"
"strings"
"sync/atomic"
"github.com/SkyAPM/go2sky/internal/idgen"
......@@ -54,6 +56,14 @@ type SegmentContext struct {
spanIDGenerator *int32
}
func (ctx SegmentContext) GetReadableGlobalTraceID() string {
ii := make([]string, len(ctx.TraceID))
for i, v := range ctx.TraceID {
ii[i] = fmt.Sprint(v)
}
return strings.Join(ii, ".")
}
// ReportedSpan is accessed by Reporter to load reported data
type ReportedSpan interface {
Context() *SegmentContext
......
......@@ -30,7 +30,11 @@ import (
"github.com/SkyAPM/go2sky/propagation"
)
const errParameter = tool.Error("parameter are nil")
const (
errParameter = tool.Error("parameter are nil")
EmptyTraceID = "N/A"
NoopTraceID = "[Ignored Trace]"
)
// Tracer is go2sky tracer implementation.
type Tracer struct {
......@@ -235,3 +239,15 @@ type Reporter interface {
Send(spans []ReportedSpan)
Close()
}
func TraceID(ctx context.Context) string {
activeSpan := ctx.Value(ctxKeyInstance)
if activeSpan == nil {
return EmptyTraceID
}
span, ok := activeSpan.(segmentSpan)
if ok {
return span.context().GetReadableGlobalTraceID()
}
return NoopTraceID
}
......@@ -107,6 +107,43 @@ func verifySpans(t *testing.T, span ReportedSpan, subSpan ReportedSpan) {
}
}
func TestTrace_TraceID(t *testing.T) {
// activeSpan == nil
traceID := TraceID(context.Background())
verifyTraceID(t, EmptyTraceID, traceID)
// activeSpan == NoopSpan
reporter := &mockRegisterReporter{
success: false,
}
tracer, _ := NewTracer("service", WithReporter(reporter))
_, ctx, err := tracer.CreateLocalSpan(context.Background())
if err != nil {
t.Error(err)
}
traceID = TraceID(ctx)
verifyTraceID(t, NoopTraceID, traceID)
// activeSpan == segmentSpan
reporter = &mockRegisterReporter{
success: true,
}
tracer, _ = NewTracer("service", WithReporter(reporter))
tracer.WaitUntilRegister()
span, ctx, err := tracer.CreateLocalSpan(context.Background())
if err != nil {
t.Error(err)
}
traceID = TraceID(ctx)
verifyTraceID(t, span.(segmentSpan).context().GetReadableGlobalTraceID(), traceID)
}
func verifyTraceID(t *testing.T, expectTraceID string, actualTraceID string) {
if expectTraceID != actualTraceID {
t.Errorf("expectTraceID: %v, actualTraceID: %v", expectTraceID, actualTraceID)
}
}
type mockRegisterReporter struct {
success bool
wg sync.WaitGroup
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册