Skip to content

Commit c6c19ef

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 c6c19ef

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

exporters/elasticsearch/src/es_log_recordable.cc

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,37 @@ 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 = 6;
216+
const static int timeZoneSize = 1;
217+
const static int dateSize = dateToSecondsSize + millisecondsSize + timeZoneSize;
218+
219+
std::time_t time = std::chrono::system_clock::to_time_t(timestamp);
220+
std::tm tm = *std::gmtime(&time);
221+
222+
char bufferDate[dateSize]; // example: 2024-10-18T07:26:00.123456Z
223+
std::strftime(bufferDate, sizeof(buffer), "%Y-%m-%dT%H:%M:%S", &tm);
224+
auto microseconds =
225+
std::chrono::duration_cast<std::chrono::microseconds>(timestamp.time_since_epoch()) %
226+
std::chrono::seconds(1);
227+
228+
char bufferMilliseconds[millisecondsSize];
229+
std::snprintf(bufferMilliseconds, sizeof(bufferMilliseconds), ".%06ld",
230+
static_cast<long>(microseconds.count()));
231+
232+
std::strcat(bufferDate, bufferMilliseconds);
233+
std::strcat(buffer, "Z");
234+
235+
const std::string dateStr(buffer);
236+
#endif
237+
238+
json_["@timestamp"] = dateStr;
209239
}
210240

211241
void ElasticSearchRecordable::SetObservedTimestamp(

0 commit comments

Comments
 (0)