1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-24 10:07:04 +02:00
go-micro/debug/trace/default.go

90 lines
1.7 KiB
Go
Raw Normal View History

2020-12-29 17:49:26 +02:00
package trace
2020-01-18 12:20:46 +02:00
import (
"context"
"time"
"github.com/google/uuid"
"github.com/micro/go-micro/v2/util/ring"
2020-01-18 12:20:46 +02:00
)
2020-12-29 17:49:26 +02:00
type memTracer struct {
opts Options
2020-01-18 12:20:46 +02:00
// ring buffer of traces
buffer *ring.Buffer
}
2020-12-29 17:49:26 +02:00
func (t *memTracer) Read(opts ...ReadOption) ([]*Span, error) {
var options ReadOptions
2020-01-24 23:24:51 +02:00
for _, o := range opts {
o(&options)
}
sp := t.buffer.Get(t.buffer.Size())
2020-12-29 17:49:26 +02:00
spans := make([]*Span, 0, len(sp))
2020-01-24 23:24:51 +02:00
for _, span := range sp {
2020-12-29 17:49:26 +02:00
val := span.Value.(*Span)
2020-01-24 23:24:51 +02:00
// skip if trace id is specified and doesn't match
if len(options.Trace) > 0 && val.Trace != options.Trace {
continue
}
spans = append(spans, val)
}
return spans, nil
2020-01-18 12:20:46 +02:00
}
2020-12-29 17:49:26 +02:00
func (t *memTracer) Start(ctx context.Context, name string) (context.Context, *Span) {
span := &Span{
2020-01-18 12:20:46 +02:00
Name: name,
Trace: uuid.New().String(),
Id: uuid.New().String(),
Started: time.Now(),
Metadata: make(map[string]string),
}
// return span if no context
if ctx == nil {
2020-12-29 17:49:26 +02:00
return ToContext(context.Background(), span.Trace, span.Id), span
2020-01-18 12:20:46 +02:00
}
2020-12-29 17:49:26 +02:00
traceID, parentSpanID, ok := FromContext(ctx)
// If the trace can not be found in the header,
// that means this is where the trace is created.
2020-01-18 12:20:46 +02:00
if !ok {
2020-12-29 17:49:26 +02:00
return ToContext(ctx, span.Trace, span.Id), span
2020-01-18 12:20:46 +02:00
}
// set trace id
span.Trace = traceID
2020-01-18 12:20:46 +02:00
// set parent
span.Parent = parentSpanID
2020-01-18 12:20:46 +02:00
// return the span
2020-12-29 17:49:26 +02:00
return ToContext(ctx, span.Trace, span.Id), span
2020-01-18 12:20:46 +02:00
}
2020-12-29 17:49:26 +02:00
func (t *memTracer) Finish(s *Span) error {
2020-01-18 12:20:46 +02:00
// set finished time
2020-01-24 23:24:51 +02:00
s.Duration = time.Since(s.Started)
2020-01-18 12:20:46 +02:00
// save the span
t.buffer.Put(s)
return nil
}
2020-12-29 17:49:26 +02:00
func NewTracer(opts ...Option) Tracer {
var options Options
2020-01-18 12:20:46 +02:00
for _, o := range opts {
o(&options)
}
2020-12-29 17:49:26 +02:00
return &memTracer{
2020-01-18 12:20:46 +02:00
opts: options,
// the last 256 requests
buffer: ring.New(256),
2020-01-18 12:20:46 +02:00
}
}