logmessage.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. @file
  3. @author Stefan Frings
  4. */
  5. #include "logmessage.h"
  6. #include <QThread>
  7. using namespace stefanfrings;
  8. LogMessage::LogMessage(const QtMsgType type, const QString& message, const QHash<QString, QString> *logVars, const QString &file, const QString &function, const int line)
  9. {
  10. this->type=type;
  11. this->message=message;
  12. this->file=file;
  13. this->function=function;
  14. this->line=line;
  15. timestamp=QDateTime::currentDateTime();
  16. threadId=QThread::currentThreadId();
  17. // Copy the logVars if not null,
  18. // so that later changes in the original do not affect the copy
  19. if (logVars)
  20. {
  21. this->logVars=*logVars;
  22. }
  23. }
  24. QString LogMessage::toString(const QString& msgFormat, const QString& timestampFormat) const
  25. {
  26. QString decorated=msgFormat+"\n";
  27. decorated.replace("{msg}",message);
  28. if (decorated.contains("{timestamp}"))
  29. {
  30. decorated.replace("{timestamp}",timestamp.toString(timestampFormat));
  31. }
  32. QString typeNr;
  33. typeNr.setNum(type);
  34. decorated.replace("{typeNr}",typeNr);
  35. switch (type)
  36. {
  37. case QtDebugMsg:
  38. decorated.replace("{type}","DEBUG ");
  39. break;
  40. case QtWarningMsg:
  41. decorated.replace("{type}","WARNING ");
  42. break;
  43. case QtCriticalMsg:
  44. decorated.replace("{type}","CRITICAL");
  45. break;
  46. case QtFatalMsg: // or QtSystemMsg which has the same int value
  47. decorated.replace("{type}","FATAL ");
  48. break;
  49. #if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
  50. case QtInfoMsg:
  51. decorated.replace("{type}","INFO ");
  52. break;
  53. #endif
  54. }
  55. decorated.replace("{file}",file);
  56. decorated.replace("{function}",function);
  57. decorated.replace("{line}",QString::number(line));
  58. QString threadId = QString("0x%1").arg(qulonglong(QThread::currentThreadId()), 8, 16, QLatin1Char('0'));
  59. decorated.replace("{thread}",threadId);
  60. // Fill in variables
  61. if (decorated.contains("{") && !logVars.isEmpty())
  62. {
  63. QList<QString> keys=logVars.keys();
  64. foreach (QString key, keys)
  65. {
  66. decorated.replace("{"+key+"}",logVars.value(key));
  67. }
  68. }
  69. return decorated;
  70. }
  71. QtMsgType LogMessage::getType() const
  72. {
  73. return type;
  74. }