// // ****************************************************************** // // /\ /| @File loger.cc // // \ V/ @Brief // // | "") @Author lijinwen, ghz005@uni-trend.com.cn // // / | @Creation 2024-05-16 // // / \\ @Modified 2024-06-24 // // *(__\_\ // // ****************************************************************** #include "loger.h" namespace Protocol { std::mutex Loger::instanceMutex_ = std::mutex(); Loger Loger::instance_ = Loger(); Loger::Loger() { logPath_ = "./DecoderLogs/"; if (!Fs::exists(logPath_)) { Fs::create_directories(logPath_); } // Generate the log file name with the current date. time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); tm now_tm; localtime_s(&now_tm, &now); // 使用线程安全的localtime_s std::stringstream log_file_name_stream; log_file_name_stream << logPath_ << "2024." << std::put_time(&now_tm, "%m.%d") << ".log"; logFileName_ = log_file_name_stream.str(); logFile_.open(logFileName_, std::ios::out | std::ios::app); } void Loger::Log(const std::string& message) { std::lock_guard lock(instanceMutex_); // 锁定以保证线程安全 const time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); tm now_tm; localtime_s(&now_tm, &now); // 使用线程安全的localtime_s std::stringstream time_stream; time_stream << std::put_time(&now_tm, "%Y-%m-%d %X"); std::ofstream& logFile = instance_.logFile_; if (logFile.is_open()) { logFile << "[" << time_stream.str() << "] - " << message << std::endl; logFile.flush(); // 确保立即写入文件 } } Loger::~Loger() { if (logFile_.is_open()) { logFile_.close(); } } void WriteLog(const LogLevel level, const char* format, ...) { if (Loger::logLevel != LogLevel::All && (Loger::logLevel == LogLevel::Close || level > Loger::logLevel)) { return; } va_list args; va_start(args, format); char buffer[1024]; vsnprintf(buffer, sizeof(buffer), format, args); va_end(args); Loger::Log(buffer); } }