Skip to content

Commit 9a28a01

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 958352a commit 9a28a01

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+
// If built with with at least cpp 20 then use std::format
209+
// Otherwise use the old style to format the timestamp in UTC
210+
#if __cplusplus >= 202002L
211+
const std::chrono::system_clock::time_point timePoint{timestamp};
212+
const std::string dateStr = std::format("{:%FT%T%Ez}", timePoint);
213+
#else
214+
const static int dateToSecondsSize = 19;
215+
const static int millisecondsSize = 8;
216+
const static int timeZoneSize = 1;
217+
const static int dateSize = dateToSecondsSize + millisecondsSize + timeZoneSize;
218+
219+
std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now();
220+
std::time_t time = std::chrono::system_clock::to_time_t(timestamp);
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>(timestamp.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)