Skip to content

Commit aae2397

Browse files
jamestaylrJames Taylor
authored andcommitted
Avoid microsecond format string parsing
Fixes a bug in the implementation of #680. Log creation uses [`std::strftime`](https://en.cppreference.com/w/cpp/chrono/c/strftime) which does not support the `%f` format string. Instead, build the microseconds outside of `strftime` and append it after. After the fix, the file names are now correclty appending microseconds (after testing): ``` test_prefix-2025-08-03_21-37-11.810495 test_prefix-stderr-2025-08-03_21-37-11.810495 ```
1 parent 581c48a commit aae2397

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

src/base/LogHandler.cpp

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,22 @@ void LogHandler::setupLogFiles(el::Configurations *defaultConf,
2828
const string &path, const string &filenamePrefix,
2929
bool logToStdout, bool redirectStderrToFile,
3030
bool appendPid, string maxlogsize) {
31-
time_t rawtime;
32-
struct tm *timeinfo;
31+
auto now = std::chrono::system_clock::now();
32+
time_t rawtime = std::chrono::system_clock::to_time_t(now);
33+
struct tm *timeinfo = std::localtime(&rawtime);
34+
3335
char buffer[80];
34-
time(&rawtime);
35-
timeinfo = localtime(&rawtime);
36-
strftime(buffer, sizeof(buffer), "%Y-%m-%d_%H-%M-%S.%f", timeinfo);
36+
strftime(buffer, sizeof(buffer), "%Y-%m-%d_%H-%M-%S", timeinfo);
3737
string current_time(buffer);
38+
39+
auto duration = now.time_since_epoch();
40+
auto microseconds =
41+
std::chrono::duration_cast<std::chrono::microseconds>(duration) %
42+
std::chrono::seconds(1);
43+
std::stringstream ss;
44+
ss << std::setw(6) << std::setfill('0') << microseconds.count();
45+
current_time += "." + ss.str();
46+
3847
string logFilename = filenamePrefix + "-" + current_time;
3948
string stderrFilename = filenamePrefix + "-stderr-" + current_time;
4049
if (appendPid) {

0 commit comments

Comments
 (0)