Logger.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // // ******************************************************************
  2. // // /\ /| @File Logger.cpp
  3. // // \ V/ @Brief
  4. // // | "") @Author lijinwen, ghz005@uni-trend.com.cn
  5. // // / | @Creation 2024-05-16
  6. // // / \\ @Modified 2024-05-16
  7. // // *(__\_\
  8. // // ******************************************************************
  9. #include "Logger.h"
  10. namespace Protocol
  11. {
  12. std::mutex Logger::InstanceMutex_ = std::mutex();
  13. Logger Logger::Instance_ = Logger();
  14. Logger::Logger()
  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 nowTm;
  24. localtime_s(&nowTm, &now); // 使用线程安全的localtime_s
  25. std::stringstream logFileNameStream;
  26. logFileNameStream << LogPath_ << "2024." << std::put_time(&nowTm, "%m.%d") << ".log";
  27. LogFileName_ = logFileNameStream.str();
  28. LogFile_.open(LogFileName_, std::ios::out | std::ios::app);
  29. }
  30. void Logger::Log(const std::string& message)
  31. {
  32. std::lock_guard<std::mutex> lock(InstanceMutex_); // 锁定以保证线程安全
  33. time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  34. tm nowTm;
  35. localtime_s(&nowTm, &now); // 使用线程安全的localtime_s
  36. std::stringstream timeStream;
  37. timeStream << std::put_time(&nowTm, "%Y-%m-%d %X");
  38. std::ofstream& logFile = Instance_.LogFile_;
  39. if (logFile.is_open())
  40. {
  41. logFile << "[" << timeStream.str() << "] - " << message << std::endl;
  42. logFile.flush(); // 确保立即写入文件
  43. }
  44. }
  45. Logger::~Logger()
  46. {
  47. if (LogFile_.is_open())
  48. {
  49. LogFile_.close();
  50. }
  51. }
  52. void WriteLog(LogLevel level, const char* format, ...)
  53. {
  54. if (Logger::LogLevel != LogLevel::All
  55. && (Logger::LogLevel == LogLevel::Close || level > Logger::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. Logger::Log(buffer);
  65. }
  66. }