logger.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /**
  2. @file
  3. @author Stefan Frings
  4. */
  5. #include "logger.h"
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <QDateTime>
  9. #include <QThread>
  10. #include <QObject>
  11. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  12. #include <QRecursiveMutex>
  13. #endif
  14. using namespace stefanfrings;
  15. Logger* Logger::defaultLogger=nullptr;
  16. QThreadStorage<QHash<QString,QString>*> Logger::logVars;
  17. QMutex Logger::mutex;
  18. Logger::Logger(QObject* parent)
  19. : QObject(parent),
  20. msgFormat("{timestamp} {type} {msg}"),
  21. timestampFormat("dd.MM.yyyy hh:mm:ss.zzz"),
  22. minLevel(QtDebugMsg),
  23. bufferSize(0)
  24. {}
  25. Logger::Logger(const QString msgFormat, const QString timestampFormat, const QtMsgType minLevel, const int bufferSize, QObject* parent)
  26. :QObject(parent)
  27. {
  28. this->msgFormat=msgFormat;
  29. this->timestampFormat=timestampFormat;
  30. this->minLevel=minLevel;
  31. this->bufferSize=bufferSize;
  32. }
  33. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  34. static QRecursiveMutex recursiveMutex;
  35. static QMutex nonRecursiveMutex;
  36. #else
  37. static QMutex recursiveMutex(QMutex::Recursive);
  38. static QMutex nonRecursiveMutex(QMutex::NonRecursive);
  39. #endif
  40. void Logger::msgHandler(const QtMsgType type, const QString &message, const QString &file, const QString &function, const int line)
  41. {
  42. // Prevent multiple threads from calling this method simultaneoulsy.
  43. // But allow recursive calls, which is required to prevent a deadlock
  44. // if the logger itself produces an error message.
  45. recursiveMutex.lock();
  46. // Fall back to stderr when this method has been called recursively.
  47. if (defaultLogger && nonRecursiveMutex.tryLock())
  48. {
  49. defaultLogger->log(type, message, file, function, line);
  50. nonRecursiveMutex.unlock();
  51. }
  52. else
  53. {
  54. fputs(qPrintable(message),stderr);
  55. fflush(stderr);
  56. }
  57. // Abort the program after logging a fatal message
  58. if (type==QtFatalMsg)
  59. {
  60. abort();
  61. }
  62. recursiveMutex.unlock();
  63. }
  64. #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
  65. void Logger::msgHandler5(const QtMsgType type, const QMessageLogContext &context, const QString &message)
  66. {
  67. (void)(context); // suppress "unused parameter" warning
  68. msgHandler(type,message,context.file,context.function,context.line);
  69. }
  70. #else
  71. void Logger::msgHandler4(const QtMsgType type, const char* message)
  72. {
  73. msgHandler(type,message);
  74. }
  75. #endif
  76. Logger::~Logger()
  77. {
  78. if (defaultLogger==this)
  79. {
  80. #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
  81. qInstallMessageHandler(nullptr);
  82. #else
  83. qInstallMsgHandler(nullptr);
  84. #endif
  85. defaultLogger=nullptr;
  86. }
  87. }
  88. void Logger::write(const LogMessage* logMessage)
  89. {
  90. fputs(qPrintable(logMessage->toString(msgFormat,timestampFormat)),stderr);
  91. fflush(stderr);
  92. }
  93. void Logger::installMsgHandler()
  94. {
  95. defaultLogger=this;
  96. #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
  97. qInstallMessageHandler(msgHandler5);
  98. #else
  99. qInstallMsgHandler(msgHandler4);
  100. #endif
  101. }
  102. void Logger::set(const QString& name, const QString& value)
  103. {
  104. mutex.lock();
  105. if (!logVars.hasLocalData())
  106. {
  107. logVars.setLocalData(new QHash<QString,QString>);
  108. }
  109. logVars.localData()->insert(name,value);
  110. mutex.unlock();
  111. }
  112. void Logger::clear(const bool buffer, const bool variables)
  113. {
  114. mutex.lock();
  115. if (buffer && buffers.hasLocalData())
  116. {
  117. QList<LogMessage*>* buffer=buffers.localData();
  118. while (buffer && !buffer->isEmpty())
  119. {
  120. LogMessage* logMessage=buffer->takeLast();
  121. delete logMessage;
  122. }
  123. }
  124. if (variables && logVars.hasLocalData())
  125. {
  126. logVars.localData()->clear();
  127. }
  128. mutex.unlock();
  129. }
  130. void Logger::log(const QtMsgType type, const QString& message, const QString &file, const QString &function, const int line)
  131. {
  132. // Check if the type of the message reached the configured minLevel in the order
  133. // DEBUG, INFO, WARNING, CRITICAL, FATAL
  134. // Since Qt 5.5: INFO messages are between DEBUG and WARNING
  135. bool toPrint=false;
  136. switch (type)
  137. {
  138. case QtDebugMsg:
  139. if (minLevel==QtDebugMsg)
  140. {
  141. toPrint=true;
  142. }
  143. break;
  144. #if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
  145. case QtInfoMsg:
  146. if (minLevel==QtDebugMsg ||
  147. minLevel==QtInfoMsg)
  148. {
  149. toPrint=true;
  150. }
  151. break;
  152. #endif
  153. case QtWarningMsg:
  154. if (minLevel==QtDebugMsg ||
  155. #if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
  156. minLevel==QtInfoMsg ||
  157. #endif
  158. minLevel==QtWarningMsg)
  159. {
  160. toPrint=true;
  161. }
  162. break;
  163. case QtCriticalMsg: // or QtSystemMsg which has the same int value
  164. if (minLevel==QtDebugMsg ||
  165. #if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
  166. minLevel==QtInfoMsg ||
  167. #endif
  168. minLevel==QtWarningMsg ||
  169. minLevel==QtCriticalMsg)
  170. {
  171. toPrint=true;
  172. }
  173. break;
  174. case QtFatalMsg:
  175. toPrint=true;
  176. break;
  177. default: // For additional type that might get introduced in future
  178. toPrint=true;
  179. }
  180. mutex.lock();
  181. // If the buffer is enabled, write the message into it
  182. if (bufferSize>0)
  183. {
  184. // Create new thread local buffer, if necessary
  185. if (!buffers.hasLocalData())
  186. {
  187. buffers.setLocalData(new QList<LogMessage*>());
  188. }
  189. QList<LogMessage*>* buffer=buffers.localData();
  190. // Append the decorated log message to the buffer
  191. LogMessage* logMessage=new LogMessage(type,message,logVars.localData(),file,function,line);
  192. buffer->append(logMessage);
  193. // Delete oldest message if the buffer became too large
  194. if (buffer->size()>bufferSize)
  195. {
  196. delete buffer->takeFirst();
  197. }
  198. // Print the whole buffer if the type is high enough
  199. if (toPrint)
  200. {
  201. // Print the whole buffer content
  202. while (!buffer->isEmpty())
  203. {
  204. LogMessage* logMessage=buffer->takeFirst();
  205. write(logMessage);
  206. delete logMessage;
  207. }
  208. }
  209. }
  210. // Buffer is disabled, print the message if the type is high enough
  211. else
  212. {
  213. if (toPrint)
  214. {
  215. LogMessage logMessage(type,message,logVars.localData(),file,function,line);
  216. write(&logMessage);
  217. }
  218. }
  219. mutex.unlock();
  220. }