log.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #include "log.h"
  2. #include "qtextcodec.h"
  3. #include <Windows.h>
  4. #define BUFF_LEN (1024)
  5. #ifdef UNICODE
  6. void Output(LPCWSTR szFormat, ...)
  7. #else
  8. void Output(const char* szFormat, ...)
  9. #endif
  10. {
  11. #ifdef UNICODE
  12. WCHAR szBuff[BUFF_LEN + 1];
  13. va_list arg;
  14. va_start(arg, szFormat);
  15. _vsnwprintf_s(szBuff, _countof(szBuff), _TRUNCATE, szFormat, arg);
  16. //_vsnwprintf(szBuff, BUFF_LEN, szFormat, arg);
  17. va_end(arg);
  18. #else
  19. char szBuff[BUFF_LEN];
  20. va_list arg;
  21. va_start(arg, szFormat);
  22. _vsnprintf(szBuff, BUFF_LEN, szFormat, arg);
  23. va_end(arg);
  24. #endif
  25. OutputDebugString(szBuff);
  26. }
  27. void logOutput(const QtMsgType type, const QMessageLogContext& context, const QString& msg)
  28. {
  29. QString txt, type_str;
  30. QString time = QDateTime::currentDateTime().toString("dd/MM/yy hh:mm:ss.zzz"); //"hh:mm:ss.zzz"
  31. QFileInfo file(context.file);
  32. switch (type) {
  33. case QtDebugMsg:
  34. type_str = "Debug";
  35. break;
  36. case QtInfoMsg:
  37. type_str = "Info";
  38. break;
  39. case QtWarningMsg:
  40. type_str = "Warning";
  41. break;
  42. case QtCriticalMsg:
  43. type_str = "Critical";
  44. break;
  45. case QtFatalMsg:
  46. type_str = "Fatal";
  47. abort();
  48. default:
  49. break;
  50. }
  51. if (msg.startsWith("QObject::startTimer:") || msg.startsWith("QObject::killTimer:"))
  52. return;
  53. #if !NDEBUG // log to debug window with debug version
  54. txt = QString("[%1][%2]%3 (file:%4:%5, fun:%6)\n")
  55. .arg(time)
  56. .arg(type_str)
  57. .arg(msg)
  58. .arg(file.fileName())
  59. .arg(context.line)
  60. .arg(context.function);
  61. Output(txt.toStdWString().c_str());
  62. #else // log to file
  63. if (type <= QtDebugMsg)
  64. return;
  65. txt = QString("[%1][%2]%3").arg(time).arg(type_str).arg(msg);
  66. Logger& logger = Logger::instance();
  67. logger.log(txt);
  68. #endif
  69. }
  70. Logger::Logger(const QString& file)
  71. : m_logfile(nullptr)
  72. , m_ts(nullptr)
  73. {
  74. m_logfile = std::make_unique<QFile>(file);
  75. if (m_logfile) {
  76. if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)) {
  77. m_ts = std::make_unique<QTextStream>(m_logfile.get());
  78. m_ts->setCodec(QTextCodec::codecForName("UTF8"));
  79. }
  80. }
  81. }
  82. Logger::~Logger()
  83. {
  84. if (m_logfile)
  85. m_logfile->close();
  86. }
  87. void Logger::log(const QString& str)
  88. {
  89. if (m_ts)
  90. (*m_ts) << str << Qt::endl;
  91. }