Logger.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #pragma once
  2. #include <string>
  3. #include <fstream>
  4. #include <mutex>
  5. #include <memory>
  6. enum class LogLevel {
  7. LOG_LEVEL_INFO,
  8. LOG_LEVEL_WARNING,
  9. LOG_LEVEL_ERROR,
  10. LOG_LEVEL_DEBUG
  11. };
  12. class Logger {
  13. private:
  14. static std::unique_ptr<Logger> instance_;
  15. static std::mutex mutex_;
  16. std::ofstream log_file_;
  17. std::mutex file_mutex_;
  18. std::string log_file_path_;
  19. Logger(const std::string& log_file_path);
  20. public:
  21. static Logger* GetInstance(const std::string& log_file_path = "");
  22. void Log(LogLevel level, const std::string& message);
  23. void LogInfo(const std::string& message);
  24. void LogWarning(const std::string& message);
  25. void LogError(const std::string& message);
  26. void LogDebug(const std::string& message);
  27. ~Logger();
  28. // 禁用拷贝构造和赋值
  29. Logger(const Logger&) = delete;
  30. Logger& operator=(const Logger&) = delete;
  31. };
  32. // 便利宏
  33. #define LOG_INFO(msg) Logger::GetInstance()->LogInfo(msg)
  34. #define LOG_WARNING(msg) Logger::GetInstance()->LogWarning(msg)
  35. #define LOG_ERROR(msg) Logger::GetInstance()->LogError(msg)
  36. #define LOG_DEBUG(msg) Logger::GetInstance()->LogDebug(msg)