Logger.cpp 1.6 KB

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