Logger.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 << "[WELCOME] " << __FILE__ << " " << currTime() << " : " << "=== Start logging ===" << endl;
  9. }
  10. void Logger::Init(log_target target, log_level level, string path)
  11. {
  12. this->target = target;
  13. if (path.empty())
  14. {
  15. this->path = std::filesystem::current_path().string() + "\\log\\log.log";
  16. }
  17. this->level = level;
  18. string tmp = ""; // 双引号下的常量不能直接相加,所以用一个string类型做转换
  19. string welcome_dialog = tmp + "[SProxy] " + __FILE__ + " " + currTime() + " : " + "=== Start logging ===\n";
  20. if (target != terminal) {
  21. this->outfile.open(path, ios::out | ios::app); // 打开输出文件
  22. this->outfile << welcome_dialog;
  23. }
  24. if (target != file) {
  25. // 如果日志对象不是仅文件
  26. cout << welcome_dialog;
  27. }
  28. }
  29. void Logger::output(string text, log_level act_level) {
  30. string prefix;
  31. if (act_level == debug) prefix = "[DEBUG] ";
  32. else if (act_level == info) prefix = "[INFO] ";
  33. else if (act_level == warning) prefix = "[WARNING] ";
  34. else if (act_level == error) prefix = "[ERROR] ";
  35. else prefix = "";
  36. prefix += __FILE__;
  37. prefix += " ";
  38. string output_content = prefix + currTime() + " : " + text + "\n";
  39. if (this->level <= act_level && this->target != file) {
  40. // 当前等级设定的等级才会显示在终端,且不能是只文件模式
  41. cout << output_content;
  42. }
  43. if (this->target != terminal)
  44. outfile << output_content;
  45. }
  46. void Logger::DEBUG(string text) {
  47. this->output(text, debug);
  48. }
  49. void Logger::INFO(string text) {
  50. this->output(text, info);
  51. }
  52. void Logger::WARNING(string text) {
  53. this->output(text, warning);
  54. }
  55. void Logger::LERROR(string text) {
  56. this->output(text, error);
  57. }