Skip to content

Commit

Permalink
[EXPORTERS]: elastic search set timestamp within @timestamp instead of
Browse files Browse the repository at this point in the history
`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 open-telemetry#3091
  • Loading branch information
ShadowMaxLeb committed Oct 18, 2024
1 parent 958352a commit c6c19ef
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion exporters/elasticsearch/src/es_log_recordable.cc
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,37 @@ nlohmann::json ElasticSearchRecordable::GetJSON() noexcept
void ElasticSearchRecordable::SetTimestamp(
opentelemetry::common::SystemTimestamp timestamp) noexcept
{
json_["timestamp"] = timestamp.time_since_epoch().count();
// If built with with at least cpp 20 then use std::format
// Otherwise use the old style to format the timestamp in UTC
#if __cplusplus >= 202002L
const std::chrono::system_clock::time_point timePoint{timestamp};
const std::string dateStr = std::format("{:%FT%T%Ez}", timePoint);
#else
const static int dateToSecondsSize = 19;
const static int millisecondsSize = 6;
const static int timeZoneSize = 1;
const static int dateSize = dateToSecondsSize + millisecondsSize + timeZoneSize;

std::time_t time = std::chrono::system_clock::to_time_t(timestamp);
std::tm tm = *std::gmtime(&time);

char bufferDate[dateSize]; // example: 2024-10-18T07:26:00.123456Z
std::strftime(bufferDate, sizeof(buffer), "%Y-%m-%dT%H:%M:%S", &tm);
auto microseconds =
std::chrono::duration_cast<std::chrono::microseconds>(timestamp.time_since_epoch()) %
std::chrono::seconds(1);

char bufferMilliseconds[millisecondsSize];
std::snprintf(bufferMilliseconds, sizeof(bufferMilliseconds), ".%06ld",
static_cast<long>(microseconds.count()));

std::strcat(bufferDate, bufferMilliseconds);
std::strcat(buffer, "Z");

const std::string dateStr(buffer);
#endif

json_["@timestamp"] = dateStr;
}

void ElasticSearchRecordable::SetObservedTimestamp(
Expand Down

0 comments on commit c6c19ef

Please sign in to comment.