forked from sonic-net/sonic-buildimage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimestamp_formatter.cpp
More file actions
77 lines (72 loc) · 2.23 KB
/
timestamp_formatter.cpp
File metadata and controls
77 lines (72 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include "timestamp_formatter.h"
#include "logger.h"
#include "events.h"
using namespace std;
/***
*
* Formats given string into string needed by YANG model
*
* @param timestamp parsed from syslog message
* @return formatted timestamp that conforms to YANG model
*
*/
static const unordered_map<string, string> g_monthDict {
{ "Jan", "01" },
{ "Feb", "02" },
{ "Mar", "03" },
{ "Apr", "04" },
{ "May", "05" },
{ "Jun", "06" },
{ "Jul", "07" },
{ "Aug", "08" },
{ "Sep", "09" },
{ "Oct", "10" },
{ "Nov", "11" },
{ "Dec", "12" }
};
string TimestampFormatter::getYear(string timestamp) {
if(!m_storedTimestamp.empty()) {
if(m_storedTimestamp.compare(timestamp) <= 0) {
m_storedTimestamp = timestamp;
return m_storedYear;
}
}
// no last timestamp or year change
// Use thread-safe localtime_r instead of localtime
// On 64-bit systems, time_t is already 64-bit and Y2038-safe
time_t currentTime = time(nullptr);
struct tm tm_result;
localtime_r(¤tTime, &tm_result);
stringstream ss;
auto currentYear = 1900 + tm_result.tm_year;
ss << currentYear; // get current year
string year = ss.str();
m_storedTimestamp = timestamp;
m_storedYear = year;
return year;
}
string TimestampFormatter::changeTimestampFormat(vector<string> dateComponents) {
if(dateComponents.size() < 3) {
SWSS_LOG_ERROR("Timestamp formatter unable to format due to invalid input");
return "";
}
string formattedTimestamp; // need to change format of Mmm dd hh:mm:ss.SSSSSS to YYYY-mm-ddThh:mm:ss.SSSSSSZ
string month;
auto it = g_monthDict.find(dateComponents[0]);
if(it != g_monthDict.end()) {
month = it->second;
} else {
SWSS_LOG_ERROR("Timestamp month was given in wrong format.\n");
return "";
}
string day = dateComponents[1];
if(day.size() == 1) { // convert 1 -> 01
day.insert(day.begin(), '0');
}
string time = dateComponents[2];
string currentTimestamp = month + day + time;
string year = getYear(currentTimestamp);
formattedTimestamp = year + "-" + month + "-" + day + "T" + time + "Z";
return formattedTimestamp;
}