log.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. #ifdef UNICODE
  62. Output(reinterpret_cast<LPCWSTR>(txt.toStdWString().c_str()));
  63. #else
  64. Output(txt.toLocal8Bit().constData());
  65. #endif
  66. #else // log to file
  67. if (type <= QtDebugMsg)
  68. return;
  69. txt = QString("[%1][%2]%3").arg(time).arg(type_str).arg(msg);
  70. Logger& logger = Logger::instance();
  71. logger.log(txt);
  72. #endif
  73. }
  74. Logger::Logger(const QString& file)
  75. : m_logfile(nullptr)
  76. , m_ts(nullptr)
  77. {
  78. m_logfile = std::make_unique<QFile>(file);
  79. if (m_logfile) {
  80. if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)) {
  81. m_ts = std::make_unique<QTextStream>(m_logfile.get());
  82. m_ts->setCodec(QTextCodec::codecForName("UTF8"));
  83. }
  84. }
  85. }
  86. Logger::~Logger()
  87. {
  88. if (m_logfile)
  89. m_logfile->close();
  90. }
  91. void Logger::log(const QString& str)
  92. {
  93. if (m_ts)
  94. (*m_ts) << str << Qt::endl;
  95. }