Skip to content
This repository was archived by the owner on Jul 31, 2023. It is now read-only.

Commit 553b823

Browse files
committed
trace: add starttime start option
Adds a StartTime option when creating a new span. In some cases, you are able to trace only after the operation was made. for example in some post-operation hook/observer. func myHook(ctx context.Context, info queryInfo) { _, span := StartSpan("mydatabase", WithStartTime(time.Now().Sub(info.Duration())) span.End() }
1 parent fb92c34 commit 553b823

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

trace/trace.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,10 @@ type StartOptions struct {
127127
// SpanKind represents the kind of a span. If none is set,
128128
// SpanKindUnspecified is used.
129129
SpanKind int
130+
131+
// StartTime is used as the start time of the span if provided. Else it will
132+
// use time.Now().
133+
StartTime time.Time
130134
}
131135

132136
// StartOption apply changes to StartOptions.
@@ -147,6 +151,13 @@ func WithSampler(sampler Sampler) StartOption {
147151
}
148152
}
149153

154+
// WithStartTime sets the span start time.
155+
func WithStartTime(t time.Time) StartOption {
156+
return func(o *StartOptions) {
157+
o.StartTime = t
158+
}
159+
}
160+
150161
// StartSpan starts a new child span of the current span in the context. If
151162
// there is no span in the context, creates a new trace and span.
152163
//
@@ -221,11 +232,14 @@ func startSpanInternal(name string, hasParent bool, parent SpanContext, remotePa
221232

222233
span.data = &SpanData{
223234
SpanContext: span.spanContext,
224-
StartTime: time.Now(),
235+
StartTime: o.StartTime,
225236
SpanKind: o.SpanKind,
226237
Name: name,
227238
HasRemoteParent: remoteParent,
228239
}
240+
if span.data.StartTime.IsZero() {
241+
span.data.StartTime = time.Now()
242+
}
229243
if hasParent {
230244
span.data.ParentSpanID = parent.SpanID
231245
}

trace/trace_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,20 @@ func TestStartSpanWithRemoteParent(t *testing.T) {
229229
}
230230
}
231231

232+
func TestStartSpanWithStartTime(t *testing.T) {
233+
start := time.Now()
234+
235+
ctx, span := StartSpan(context.Background(), "parent", WithSampler(AlwaysSample()), WithStartTime(start))
236+
if !span.data.StartTime.Equal(start) {
237+
t.Errorf("expected start time=%s was=%s", start, span.data.StartTime)
238+
}
239+
240+
_, span = StartSpan(ctx, "child")
241+
if !span.data.StartTime.After(start) {
242+
t.Error("expected child's start time to be after parent's")
243+
}
244+
}
245+
232246
// startSpan returns a context with a new Span that is recording events and will be exported.
233247
func startSpan(o StartOptions) *Span {
234248
_, span := StartSpanWithRemoteParent(context.Background(), "span0",

0 commit comments

Comments
 (0)