FileLogger.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #ifndef FILELOGGER_H
  2. #define FILELOGGER_H
  3. #include <string>
  4. #include <stdexcept>
  5. #include <QDir>
  6. #include <QString>
  7. // 跨平台路径分隔符:Windows用\,Linux/macOS用/
  8. #ifdef _WIN32
  9. #define PATH_SEPARATOR "\\"
  10. #else
  11. #define PATH_SEPARATOR "/"
  12. #endif
  13. /**
  14. * @brief 文件文本写入工具类
  15. * 支持:跨平台写入、自动创建多级目录、覆盖/追加模式、char*兼容(需先转string)
  16. */
  17. class FileLogger {
  18. public:
  19. // 写入模式枚举
  20. enum class WriteMode {
  21. OVERWRITE, // 覆盖模式:清空现有内容
  22. APPEND // 追加模式:在文件末尾添加(默认)
  23. };
  24. public:
  25. /**
  26. * @brief 写入文本到文件(核心接口)
  27. * @param relativePath 相对路径(如 "log"、"data/logs")
  28. * @param fileName 文件名(如 "app.log"、"20240916.txt")
  29. * @param data 待写入的文本(std::string类型,char*需先转string)
  30. * @param mode 写入模式(默认APPEND)
  31. * @throw std::runtime_error 路径创建失败/文件打开失败时抛出异常
  32. */
  33. static void writeToFile(const std::string& relativePath,
  34. const std::string& fileName,
  35. const std::string& data,
  36. WriteMode mode = WriteMode::APPEND);
  37. private:
  38. /**
  39. * @brief 辅助函数:拼接路径与文件名(处理分隔符)
  40. */
  41. static std::string joinPath(const std::string& path, const std::string& fileName);
  42. /**
  43. * @brief 辅助函数:自动创建多级目录
  44. */
  45. static void createDirectory(const std::string& relativePath);
  46. /**
  47. * @brief 辅助函数:获取当前时间戳(格式:YYYY-MM-DD HH:MM:SS)
  48. */
  49. static std::string getCurrentTime();
  50. };
  51. #endif // FILELOGGER_H