loger.cc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // // ******************************************************************
  2. // // /\ /| @File loger.cc
  3. // // \ V/ @Brief
  4. // // | "") @Author lijinwen, ghz005@uni-trend.com.cn
  5. // // / | @Creation 2024-05-16
  6. // // / \\ @Modified 2024-06-24
  7. // // *(__\_\
  8. // // ******************************************************************
  9. #include "loger.h"
  10. namespace Protocol
  11. {
  12. std::mutex Loger::instanceMutex_ = std::mutex();
  13. Loger Loger::instance_ = Loger();
  14. Loger::Loger()
  15. {
  16. logPath_ = "./DecoderLogs/";
  17. if (!Fs::exists(logPath_))
  18. {
  19. Fs::create_directories(logPath_);
  20. }
  21. // Generate the log file name with the current date.
  22. time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  23. tm now_tm;
  24. localtime_s(&now_tm, &now); // 使用线程安全的localtime_s
  25. std::stringstream log_file_name_stream;
  26. log_file_name_stream << logPath_ << "2024." << std::put_time(&now_tm, "%m.%d") << ".log";
  27. logFileName_ = log_file_name_stream.str();
  28. logFile_.open(logFileName_, std::ios::out | std::ios::app);
  29. }
  30. void Loger::Log(const std::string& message)
  31. {
  32. std::lock_guard<std::mutex> lock(instanceMutex_); // 锁定以保证线程安全
  33. const time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  34. tm now_tm;
  35. localtime_s(&now_tm, &now); // 使用线程安全的localtime_s
  36. std::stringstream time_stream;
  37. time_stream << std::put_time(&now_tm, "%Y-%m-%d %X");
  38. std::ofstream& logFile = instance_.logFile_;
  39. if (logFile.is_open())
  40. {
  41. logFile << "[" << time_stream.str() << "] - " << message << std::endl;
  42. logFile.flush(); // 确保立即写入文件
  43. }
  44. }
  45. Loger::~Loger()
  46. {
  47. if (logFile_.is_open())
  48. {
  49. logFile_.close();
  50. }
  51. }
  52. void WriteLog(const LogLevel level, const char* format, ...)
  53. {
  54. if (Loger::logLevel != LogLevel::All
  55. && (Loger::logLevel == LogLevel::Close || level > Loger::logLevel))
  56. {
  57. return;
  58. }
  59. va_list args;
  60. va_start(args, format);
  61. char buffer[1024];
  62. vsnprintf(buffer, sizeof(buffer), format, args);
  63. va_end(args);
  64. Loger::Log(buffer);
  65. }
  66. }