diff --git a/include/logger.hpp b/include/logger.hpp index d4e34ee..0eef0e9 100644 --- a/include/logger.hpp +++ b/include/logger.hpp @@ -23,6 +23,8 @@ public: static void log(LogLevel level, const std::string &msg); + static std::string get_current_time_utc8(); + private: static std::ofstream log_file; static std::string current_log_filename; diff --git a/src/logger.cpp b/src/logger.cpp index 2d53b37..ca54e1e 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -38,6 +38,25 @@ std::string Logger::get_time_string() return oss.str(); } +std::string Logger::get_current_time_utc8() +{ + using namespace std::chrono; + + auto now = system_clock::now(); + now += hours(8); // UTC+8 + + std::time_t t = system_clock::to_time_t(now); + auto millis = duration_cast(now.time_since_epoch()) % 1000; + + std::tm tm_now = *std::localtime(&t); + + std::ostringstream ss; + ss << std::put_time(&tm_now, "%Y%m%d%H%M%S") + << std::setw(3) << std::setfill('0') << millis.count(); + + return ss.str(); +} + void Logger::log(LogLevel level, const std::string &msg) { std::string level_str; @@ -54,7 +73,7 @@ void Logger::log(LogLevel level, const std::string &msg) break; } - std::string full_msg = get_time_string() + " " + level_str + " " + msg; + std::string full_msg = get_current_time_utc8() + " " + level_str + " " + msg; std::cout << full_msg << std::endl; diff --git a/src/mqtt_client_wrapper.cpp b/src/mqtt_client_wrapper.cpp index afe4a88..062fd58 100644 --- a/src/mqtt_client_wrapper.cpp +++ b/src/mqtt_client_wrapper.cpp @@ -79,16 +79,11 @@ static void on_mqtt_message_received(const std::string &topic, const std::string success = false; } - // 获取当前时间 yyyyMMddHHmmssSSS - auto now = std::chrono::system_clock::now(); - auto millis = std::chrono::duration_cast(now.time_since_epoch()) % 1000; - std::time_t t = std::chrono::system_clock::to_time_t(now); - std::tm tm_now = *std::localtime(&t); - std::ostringstream time_ss; - time_ss << std::put_time(&tm_now, "%Y%m%d%H%M%S") << std::setw(3) << std::setfill('0') << millis.count(); + // 获取当前时间 yyyyMMddHHmmssSSS (UTC+8) + std::string time_str = Logger::get_current_time_utc8(); nlohmann::json reply; - reply["time"] = time_ss.str(); + reply["time"] = time_str; reply["result"] = success ? 0 : 1; reply["seqNo"] = seqNo;