Logger.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "stdafx.h"
  2. #include "Logger.h"
  3. Logger* SSingleton<Logger>::ms_Singleton = NULL;
  4. Logger::Logger() {
  5. // 默认构造函数
  6. this->target = terminal;
  7. this->level = debug;
  8. cout << "[SProxy] " << __FILE__ << " " << currTime() << " : " << "=== Start logging ===" << endl;
  9. }
  10. void log_debug_message(const char* format, ...) {
  11. char logMessage[256];
  12. va_list args;
  13. va_start(args, format);
  14. vsnprintf(logMessage, sizeof(logMessage), format, args);
  15. va_end(args);
  16. HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
  17. SetConsoleTextAttribute(console, FOREGROUND_GREEN); // 设置文本颜色为绿色
  18. OutputDebugStringA(logMessage);
  19. SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); // 恢复文本颜色为默认值
  20. }
  21. void Logger::Init(log_target target, log_level level, string path)
  22. {
  23. this->target = target;
  24. if (path.empty())
  25. {
  26. this->path = std::filesystem::current_path().string() + "\\log\\log.txt";
  27. }
  28. this->level = level;
  29. string tmp = ""; // 双引号下的常量不能直接相加,所以用一个string类型做转换
  30. string welcome_dialog = tmp + "[SProxy] " + __FILE__ + " " + currTime() + " : " + "=== Start logging ===\n";
  31. if (target != terminal) {
  32. this->outfile.open(this->path, ios::out | ios::app); // 打开输出文件
  33. this->outfile << welcome_dialog;
  34. }
  35. if (target != file) {
  36. // 如果日志对象不是仅文件
  37. cout << welcome_dialog;
  38. }
  39. }
  40. void Logger::output(string text, log_level act_level) {
  41. string prefix;
  42. if (act_level == debug) prefix = "[DEBUG] ";
  43. else if (act_level == info) prefix = "[INFO] ";
  44. else if (act_level == warning) prefix = "[WARNING] ";
  45. else if (act_level == error) prefix = "[ERROR] ";
  46. else prefix = "";
  47. prefix += __FILE__;
  48. prefix += " ";
  49. string output_content = prefix + currTime() + " : " + text + "\n";
  50. if (this->level <= act_level && this->target != file) {
  51. // 当前等级设定的等级才会显示在终端,且不能是只文件模式
  52. cout << output_content;
  53. }
  54. if (this->target != terminal)
  55. outfile << output_content;
  56. #ifdef _DEBUG
  57. log_debug_message(output_content.c_str());
  58. #endif // _DEBUG
  59. }
  60. void Logger::DEBUG(string text) {
  61. #ifdef _DEBUG
  62. this->output(text, debug);
  63. #endif // _DEBUG
  64. }
  65. void Logger::INFO(string text) {
  66. this->output(text, info);
  67. }
  68. void Logger::WARNING(string text) {
  69. this->output(text, warning);
  70. }
  71. void Logger::LERROR(string text) {
  72. this->output(text, error);
  73. }