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