Skip to content

Commit 53d72bf

Browse files
committed
[EXPORTERS]: elastic search set timestamp within @timestamp instead of
`timestamp` Also changes the format to be a Date string. According to ECS logging reference https://www.elastic.co/guide/en/ecs/8.11/ecs-base.html#field-timestamp Refs #3091
1 parent 8be43d2 commit 53d72bf

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

exporters/elasticsearch/src/es_log_recordable.cc

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,38 @@ nlohmann::json ElasticSearchRecordable::GetJSON() noexcept
205205
void ElasticSearchRecordable::SetTimestamp(
206206
opentelemetry::common::SystemTimestamp timestamp) noexcept
207207
{
208-
json_["timestamp"] = timestamp.time_since_epoch().count();
208+
const std::chrono::system_clock::time_point timePoint{timestamp};
209+
210+
// If built with with at least cpp 20 then use std::format
211+
// Otherwise use the old style to format the timestamp in UTC
212+
#if __cplusplus >= 202002L
213+
const std::string dateStr = std::format("{:%FT%T%Ez}", timePoint);
214+
#else
215+
const static int dateToSecondsSize = 19;
216+
const static int millisecondsSize = 8;
217+
const static int timeZoneSize = 1;
218+
const static int dateSize = dateToSecondsSize + millisecondsSize + timeZoneSize;
219+
220+
std::time_t time = std::chrono::system_clock::to_time_t(timePoint);
221+
std::tm tm = *std::gmtime(&time);
222+
223+
char bufferDate[dateSize]; // example: 2024-10-18T07:26:00.123456Z
224+
std::strftime(bufferDate, sizeof(bufferDate), "%Y-%m-%dT%H:%M:%S", &tm);
225+
auto microseconds =
226+
std::chrono::duration_cast<std::chrono::microseconds>(timePoint.time_since_epoch()) %
227+
std::chrono::seconds(1);
228+
229+
char bufferMilliseconds[millisecondsSize];
230+
std::snprintf(bufferMilliseconds, sizeof(bufferMilliseconds), ".%06ld",
231+
static_cast<long>(microseconds.count()));
232+
233+
std::strcat(bufferDate, bufferMilliseconds);
234+
std::strcat(bufferDate, "Z");
235+
236+
const std::string dateStr(bufferDate);
237+
#endif
238+
239+
json_["@timestamp"] = dateStr;
209240
}
210241

211242
void ElasticSearchRecordable::SetObservedTimestamp(

0 commit comments

Comments
 (0)