Skip to content
This repository was archived by the owner on Jan 21, 2026. It is now read-only.

Commit 319642a

Browse files
authored
feat: allow timestamps to be passed to endSpan (#747)
PR-URL: #747
1 parent 908e431 commit 319642a

3 files changed

Lines changed: 18 additions & 6 deletions

File tree

src/plugin-types.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,10 @@ export interface SpanData {
5252

5353
/**
5454
* Ends the span. This method should only be called once.
55+
* @param timestamp A custom span end time; defaults to the time when endSpan
56+
* was called if not provided.
5557
*/
56-
endSpan(): void;
58+
endSpan(timestamp?: Date): void;
5759
}
5860

5961
/**

src/span-data.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,9 @@ export abstract class BaseSpanData implements SpanData {
103103
this.span.labels[k] = v;
104104
}
105105

106-
endSpan() {
107-
this.span.endTime = (new Date()).toISOString();
106+
endSpan(timestamp?: Date) {
107+
timestamp = timestamp || new Date();
108+
this.span.endTime = timestamp.toISOString();
108109
}
109110
}
110111

@@ -131,8 +132,8 @@ export class RootSpanData extends BaseSpanData implements types.RootSpanData {
131132
skipFrames); /* # of frames to skip in stack trace */
132133
}
133134

134-
endSpan() {
135-
super.endSpan();
135+
endSpan(timestamp?: Date) {
136+
super.endSpan(timestamp);
136137
traceWriter.get().writeSpan(this.trace);
137138
}
138139
}

test/test-span-data.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,6 @@ describe('SpanData', () => {
8585
});
8686

8787
it('accurately records timestamps', async () => {
88-
// Create another span, to determine start time correctness
8988
const startLowerBound = Date.now();
9089
const spanData = new CommonSpanData(trace, 'name', '0', 0);
9190
const startUpperBound = Date.now();
@@ -106,6 +105,16 @@ describe('SpanData', () => {
106105
expectedTimes.slice().sort(ascending), expectedTimes);
107106
});
108107

108+
it('accepts a custom span end time', () => {
109+
const spanData = new CommonSpanData(trace, 'name', '0', 0);
110+
const startTime = new Date(spanData.span.startTime).getTime();
111+
// This input Date is far enough in the future that it's unlikely that the
112+
// time this function was called could be close to it.
113+
spanData.endSpan(new Date(startTime + 1000000));
114+
const endTime = new Date(spanData.span.endTime).getTime();
115+
assert.strictEqual(endTime - startTime, 1000000);
116+
});
117+
109118
it('truncates large span names to limit', () => {
110119
const name = 'a'.repeat(200);
111120
const spanData = new CommonSpanData(trace, name, '0', 0);

0 commit comments

Comments
 (0)