'Overwrite the StartTime and EndTime of a span with Golang opentelemetry (otel)

I am producing traces for data that was collected before I am doing the tracing. This means that the span creation time does not match up with the real start time.

I have been able to do this in the past using opentracing:

span := tracer.StartSpan(
    name,
    opentracing.StartTime(startTime),
)

I have been unable to find an equivalent in the golang otel libraries. I get the impression that it should be possible based on this quote from the spec:

Start timestamp, default to current time. This argument SHOULD only be set when span creation time has already passed. If API is called at a moment of a Span logical start, API user MUST NOT explicitly set this argument.

The word "default" implies that it should be possible to change this timestamp after span creation.

I have tried using span.SetAttributes:

span.SetAttributes(attribute.Int64("StartTime", 0))

But this (unsurprisingly) sets an attribute:

{
        // ...
        "StartTime": "2022-04-09T12:28:57.271375+10:00",
        "EndTime": "2022-04-09T12:28:57.271417375+10:00",
        "Attributes": [
                {
                        "Key": "StartTime",
                        "Value": {
                                "Type": "INT64",
                                "Value": 0
                        }
                },
         // ...
}


Solution 1:[1]

You need to use WithTimestamp.

startTime := time.Now()
ctx, span := tracer.Start(ctx, "foo", trace.WithTimestamp(startTime))

// do your work

span.End(trace.WithTimestamp(time.Now()))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Srikanth Chekuri