From b84f94f6a3b9b5fa36ec8169408317d928925265 Mon Sep 17 00:00:00 2001 From: "Edward Z. Yang" Date: Thu, 7 Mar 2024 13:32:26 -0800 Subject: [PATCH] Restore timestamps on C++ logs without glog (#121384) It looks like it was commented out because the original implementation was not sufficiently portable. I had to do some rewrites to the innards to make it no portable. No Windows nanoseconds support because I'm lazy. I tested by running `build/bin/TCPStoreTest` and observing the log messages there. I am actually not sure how to look at the log messages from Python though. Signed-off-by: Edward Z. Yang Pull Request resolved: https://github.com/pytorch/pytorch/pull/121384 Approved by: https://github.com/Skylion007, https://github.com/malfet --- c10/util/Logging.cpp | 48 ++++++++++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 17 deletions(-) diff --git a/c10/util/Logging.cpp b/c10/util/Logging.cpp index f4eef35b147..e9c9e9c2f30 100644 --- a/c10/util/Logging.cpp +++ b/c10/util/Logging.cpp @@ -5,6 +5,10 @@ #include #endif +#ifndef _WIN32 +#include +#endif + #include #include #include @@ -351,27 +355,37 @@ MessageLogger::MessageLogger(const char* file, int line, int severity) #else // !ANDROID tag_ = ""; #endif // ANDROID - /* - time_t rawtime; - struct tm * timeinfo; + + time_t rawtime = 0; time(&rawtime); - timeinfo = localtime(&rawtime); - std::chrono::nanoseconds ns = - std::chrono::duration_cast( - std::chrono::high_resolution_clock::now().time_since_epoch()); - */ + +#ifndef _WIN32 + struct tm raw_timeinfo = {0}; + struct tm* timeinfo = &raw_timeinfo; + localtime_r(&rawtime, timeinfo); +#else + // is thread safe on Windows + struct tm* timeinfo = localtime(&rawtime); +#endif + +#ifndef _WIN32 + // Get the current nanoseconds since epoch + struct timespec ts = {0}; + clock_gettime(CLOCK_MONOTONIC, &ts); + long ns = ts.tv_nsec; +#else + long ns = 0; +#endif + if (GLOBAL_RANK != -1) { stream_ << "[rank" << GLOBAL_RANK << "]:"; } - stream_ << "[" - << CAFFE2_SEVERITY_PREFIX[std::min(4, GLOG_FATAL - severity_)] - //<< (timeinfo->tm_mon + 1) * 100 + timeinfo->tm_mday - //<< std::setfill('0') - //<< " " << std::setw(2) << timeinfo->tm_hour - //<< ":" << std::setw(2) << timeinfo->tm_min - //<< ":" << std::setw(2) << timeinfo->tm_sec - //<< "." << std::setw(9) << ns.count() % 1000000000 - << " " << c10::detail::StripBasename(std::string(file)) << ":" << line + stream_ << "[" << CAFFE2_SEVERITY_PREFIX[std::min(4, GLOG_FATAL - severity_)] + << (timeinfo->tm_mon + 1) * 100 + timeinfo->tm_mday + << std::setfill('0') << " " << std::setw(2) << timeinfo->tm_hour + << ":" << std::setw(2) << timeinfo->tm_min << ":" << std::setw(2) + << timeinfo->tm_sec << "." << std::setw(9) << ns << " " + << c10::detail::StripBasename(std::string(file)) << ":" << line << "] "; }