Logger.cpp 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include "Logger.h"
  3. #include <iostream>
  4. #include <ctime>
  5. #include <windows.h>
  6. std::unique_ptr<Logger> Logger::instance_ = nullptr;
  7. std::mutex Logger::mutex_;
  8. Logger::Logger(const std::string& log_file_path) : log_file_path_(log_file_path) {
  9. // 获取可执行文件所在目录
  10. char buffer[MAX_PATH];
  11. GetModuleFileNameA(NULL, buffer, MAX_PATH);
  12. std::string::size_type pos = std::string(buffer).find_last_of("\\");
  13. std::string exe_path = std::string(buffer).substr(0, pos);
  14. // 构建完整的日志文件路径
  15. std::string full_log_path = exe_path + "\\" + log_file_path;
  16. log_file_.open(full_log_path, std::ios::app);
  17. if (!log_file_.is_open()) {
  18. std::cerr << "Failed to open log file: " << full_log_path << std::endl;
  19. }
  20. }
  21. Logger::~Logger() {
  22. if (log_file_.is_open()) {
  23. log_file_.close();
  24. }
  25. }
  26. Logger* Logger::GetInstance(const std::string& log_file_path) {
  27. std::lock_guard<std::mutex> lock(mutex_);
  28. if (instance_ == nullptr) {
  29. std::string path = log_file_path.empty() ? "CommModifyService.log" : log_file_path;
  30. instance_ = std::unique_ptr<Logger>(new Logger(path));
  31. }
  32. return instance_.get();
  33. }
  34. void Logger::Log(LogLevel level, const std::string& message) {
  35. return;
  36. std::lock_guard<std::mutex> lock(file_mutex_);
  37. // 获取当前时间
  38. auto now = std::time(nullptr);
  39. auto tm = *std::localtime(&now);
  40. // 格式化时间字符串
  41. char time_buffer[100];
  42. std::strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%d %H:%M:%S", &tm);
  43. // 获取日志级别字符串
  44. std::string level_str;
  45. switch (level) {
  46. case LogLevel::LOG_LEVEL_INFO: level_str = "INFO"; break;
  47. case LogLevel::LOG_LEVEL_WARNING: level_str = "WARNING"; break;
  48. case LogLevel::LOG_LEVEL_ERROR: level_str = "ERROR"; break;
  49. case LogLevel::LOG_LEVEL_DEBUG: level_str = "DEBUG"; break;
  50. }
  51. // 构建日志消息
  52. std::string log_message = "[" + std::string(time_buffer) + "] [" + level_str + "] " + message;
  53. // 写入文件
  54. if (log_file_.is_open()) {
  55. log_file_ << log_message << std::endl;
  56. log_file_.flush();
  57. }
  58. // 输出到控制台
  59. std::cout << log_message << std::endl;
  60. }
  61. void Logger::LogInfo(const std::string& message) {
  62. Log(LogLevel::LOG_LEVEL_INFO, message);
  63. }
  64. void Logger::LogWarning(const std::string& message) {
  65. Log(LogLevel::LOG_LEVEL_WARNING, message);
  66. }
  67. void Logger::LogError(const std::string& message) {
  68. Log(LogLevel::LOG_LEVEL_ERROR, message);
  69. }
  70. void Logger::LogDebug(const std::string& message) {
  71. Log(LogLevel::LOG_LEVEL_DEBUG, message);
  72. }