ctkErrorLogModel.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QDateTime>
  16. #include <QDebug>
  17. #include <QFile>
  18. #include <QMetaEnum>
  19. #include <QMetaType>
  20. #include <QMutexLocker>
  21. #include <QPointer>
  22. #include <QStandardItem>
  23. // CTK includes
  24. #include "ctkErrorLogModel.h"
  25. #include "ctkErrorLogAbstractMessageHandler.h"
  26. // --------------------------------------------------------------------------
  27. // ctkErrorLogModelPrivate
  28. // --------------------------------------------------------------------------
  29. class ctkErrorLogModelPrivate
  30. {
  31. Q_DECLARE_PUBLIC(ctkErrorLogModel);
  32. protected:
  33. ctkErrorLogModel* const q_ptr;
  34. public:
  35. ctkErrorLogModelPrivate(ctkErrorLogModel& object);
  36. ~ctkErrorLogModelPrivate();
  37. void init();
  38. /// Convenient method that could be used for debugging purposes.
  39. void appendToFile(const QString& fileName, const QString& text);
  40. void setMessageHandlerConnection(ctkErrorLogAbstractMessageHandler * msgHandler, bool asynchronous);
  41. QStandardItemModel StandardItemModel;
  42. QHash<QString, ctkErrorLogAbstractMessageHandler*> RegisteredHandlers;
  43. ctkErrorLogLevel::LogLevels CurrentLogLevelFilter;
  44. bool LogEntryGrouping;
  45. bool AsynchronousLogging;
  46. bool AddingEntry;
  47. ctkErrorLogLevel ErrorLogLevel;
  48. ctkErrorLogTerminalOutput StdErrTerminalOutput;
  49. ctkErrorLogTerminalOutput StdOutTerminalOutput;
  50. QMutex AppendToFileMutex;
  51. };
  52. // --------------------------------------------------------------------------
  53. // ctkErrorLogModelPrivate methods
  54. // --------------------------------------------------------------------------
  55. ctkErrorLogModelPrivate::ctkErrorLogModelPrivate(ctkErrorLogModel& object)
  56. : q_ptr(&object)
  57. {
  58. this->StandardItemModel.setColumnCount(ctkErrorLogModel::MaxColumn);
  59. this->LogEntryGrouping = false;
  60. this->AsynchronousLogging = true;
  61. this->AddingEntry = false;
  62. }
  63. // --------------------------------------------------------------------------
  64. ctkErrorLogModelPrivate::~ctkErrorLogModelPrivate()
  65. {
  66. foreach(const QString& handlerName, this->RegisteredHandlers.keys())
  67. {
  68. ctkErrorLogAbstractMessageHandler * msgHandler =
  69. this->RegisteredHandlers.value(handlerName);
  70. Q_ASSERT(msgHandler);
  71. msgHandler->setEnabled(false);
  72. delete msgHandler;
  73. }
  74. }
  75. // --------------------------------------------------------------------------
  76. void ctkErrorLogModelPrivate::init()
  77. {
  78. Q_Q(ctkErrorLogModel);
  79. q->setDynamicSortFilter(true);
  80. //
  81. // WARNING - Using a QSortFilterProxyModel slows down the insertion of rows by a factor 10
  82. //
  83. q->setSourceModel(&this->StandardItemModel);
  84. q->setFilterKeyColumn(ctkErrorLogModel::LogLevelColumn);
  85. }
  86. // --------------------------------------------------------------------------
  87. void ctkErrorLogModelPrivate::appendToFile(const QString& fileName, const QString& text)
  88. {
  89. QMutexLocker locker(&this->AppendToFileMutex);
  90. QFile f(fileName);
  91. f.open(QFile::Append);
  92. QTextStream s(&f);
  93. s << QDateTime::currentDateTime().toString() << " - " << text << "\n";
  94. f.close();
  95. }
  96. // --------------------------------------------------------------------------
  97. void ctkErrorLogModelPrivate::setMessageHandlerConnection(
  98. ctkErrorLogAbstractMessageHandler * msgHandler, bool asynchronous)
  99. {
  100. Q_Q(ctkErrorLogModel);
  101. msgHandler->disconnect();
  102. QObject::connect(msgHandler,
  103. SIGNAL(messageHandled(QDateTime,QString,ctkErrorLogLevel::LogLevel,QString,QString)),
  104. q, SLOT(addEntry(QDateTime,QString,ctkErrorLogLevel::LogLevel,QString,QString)),
  105. asynchronous ? Qt::QueuedConnection : Qt::BlockingQueuedConnection);
  106. }
  107. // --------------------------------------------------------------------------
  108. // ctkErrorLogModel methods
  109. //------------------------------------------------------------------------------
  110. ctkErrorLogModel::ctkErrorLogModel(QObject * parentObject)
  111. : Superclass(parentObject)
  112. , d_ptr(new ctkErrorLogModelPrivate(*this))
  113. {
  114. Q_D(ctkErrorLogModel);
  115. d->init();
  116. }
  117. //------------------------------------------------------------------------------
  118. ctkErrorLogModel::~ctkErrorLogModel()
  119. {
  120. }
  121. //------------------------------------------------------------------------------
  122. bool ctkErrorLogModel::registerMsgHandler(ctkErrorLogAbstractMessageHandler * msgHandler)
  123. {
  124. Q_D(ctkErrorLogModel);
  125. if (!msgHandler)
  126. {
  127. return false;
  128. }
  129. if (d->RegisteredHandlers.keys().contains(msgHandler->handlerName()))
  130. {
  131. return false;
  132. }
  133. d->setMessageHandlerConnection(msgHandler, d->AsynchronousLogging);
  134. msgHandler->setTerminalOutput(ctkErrorLogTerminalOutput::StandardError, &d->StdErrTerminalOutput);
  135. msgHandler->setTerminalOutput(ctkErrorLogTerminalOutput::StandardOutput, &d->StdOutTerminalOutput);
  136. d->RegisteredHandlers.insert(msgHandler->handlerName(), msgHandler);
  137. return true;
  138. }
  139. //------------------------------------------------------------------------------
  140. QStringList ctkErrorLogModel::msgHandlerNames()const
  141. {
  142. Q_D(const ctkErrorLogModel);
  143. return d->RegisteredHandlers.keys();
  144. }
  145. //------------------------------------------------------------------------------
  146. bool ctkErrorLogModel::msgHandlerEnabled(const QString& handlerName) const
  147. {
  148. Q_D(const ctkErrorLogModel);
  149. if (!d->RegisteredHandlers.keys().contains(handlerName))
  150. {
  151. return false;
  152. }
  153. return d->RegisteredHandlers.value(handlerName)->enabled();
  154. }
  155. //------------------------------------------------------------------------------
  156. void ctkErrorLogModel::setMsgHandlerEnabled(const QString& handlerName, bool enabled)
  157. {
  158. Q_D(ctkErrorLogModel);
  159. if (!d->RegisteredHandlers.keys().contains(handlerName))
  160. {
  161. // qCritical() << "Failed to enable/disable message handler " << handlerName
  162. // << "- Handler not registered !";
  163. return;
  164. }
  165. d->RegisteredHandlers.value(handlerName)->setEnabled(enabled);
  166. }
  167. //------------------------------------------------------------------------------
  168. QStringList ctkErrorLogModel::msgHandlerEnabled() const
  169. {
  170. Q_D(const ctkErrorLogModel);
  171. QStringList msgHandlers;
  172. foreach(const QString& handlerName, d->RegisteredHandlers.keys())
  173. {
  174. if (d->RegisteredHandlers.value(handlerName)->enabled())
  175. {
  176. msgHandlers << handlerName;
  177. }
  178. }
  179. return msgHandlers;
  180. }
  181. //------------------------------------------------------------------------------
  182. void ctkErrorLogModel::setMsgHandlerEnabled(const QStringList& handlerNames)
  183. {
  184. foreach(const QString& handlerName, handlerNames)
  185. {
  186. this->setMsgHandlerEnabled(handlerName, true);
  187. }
  188. }
  189. //------------------------------------------------------------------------------
  190. void ctkErrorLogModel::enableAllMsgHandler()
  191. {
  192. this->setAllMsgHandlerEnabled(true);
  193. }
  194. //------------------------------------------------------------------------------
  195. void ctkErrorLogModel::disableAllMsgHandler()
  196. {
  197. this->setAllMsgHandlerEnabled(false);
  198. }
  199. //------------------------------------------------------------------------------
  200. void ctkErrorLogModel::setAllMsgHandlerEnabled(bool enabled)
  201. {
  202. Q_D(ctkErrorLogModel);
  203. foreach(const QString& msgHandlerName, d->RegisteredHandlers.keys())
  204. {
  205. this->setMsgHandlerEnabled(msgHandlerName, enabled);
  206. }
  207. }
  208. //------------------------------------------------------------------------------
  209. ctkErrorLogTerminalOutput::TerminalOutputs ctkErrorLogModel::terminalOutputs()const
  210. {
  211. Q_D(const ctkErrorLogModel);
  212. ctkErrorLogTerminalOutput::TerminalOutputs currentTerminalOutputs;
  213. currentTerminalOutputs |= d->StdErrTerminalOutput.enabled() ? ctkErrorLogTerminalOutput::StandardError : ctkErrorLogTerminalOutput::None;
  214. currentTerminalOutputs |= d->StdOutTerminalOutput.enabled() ? ctkErrorLogTerminalOutput::StandardOutput : ctkErrorLogTerminalOutput::None;
  215. return currentTerminalOutputs;
  216. }
  217. //------------------------------------------------------------------------------
  218. void ctkErrorLogModel::setTerminalOutputs(
  219. const ctkErrorLogTerminalOutput::TerminalOutputs& terminalOutput)
  220. {
  221. Q_D(ctkErrorLogModel);
  222. d->StdErrTerminalOutput.setEnabled(terminalOutput & ctkErrorLogTerminalOutput::StandardOutput);
  223. d->StdOutTerminalOutput.setEnabled(terminalOutput & ctkErrorLogTerminalOutput::StandardError);
  224. }
  225. //------------------------------------------------------------------------------
  226. void ctkErrorLogModel::addEntry(const QDateTime& currentDateTime, const QString& threadId,
  227. ctkErrorLogLevel::LogLevel logLevel,
  228. const QString& origin, const QString& text)
  229. {
  230. Q_D(ctkErrorLogModel);
  231. // d->appendToFile("/tmp/ctkErrorLogModel-appendToFile.txt",
  232. // QString("addEntry: %1").arg(QThread::currentThreadId()));
  233. if (d->AddingEntry)
  234. {
  235. // QString str;
  236. // QTextStream s(&str);
  237. // s << "----------------------------------\n";
  238. // s << "text=>" << text << "\n";
  239. // s << "\tlogLevel:" << qPrintable(d->ErrorLogLevel(logLevel)) << "\n";
  240. // s << "\torigin:" << qPrintable(origin) << "\n";
  241. // d->appendToFile("/tmp/ctkErrorLogModel-AddingEntry-true.txt", str);
  242. return;
  243. }
  244. d->AddingEntry = true;
  245. QString timeFormat("dd.MM.yyyy hh:mm:ss");
  246. bool groupEntry = false;
  247. if (d->LogEntryGrouping)
  248. {
  249. int lastRowIndex = d->StandardItemModel.rowCount() - 1;
  250. QString lastRowThreadId = this->logEntryData(lastRowIndex, Self::ThreadIdColumn).toString();
  251. bool threadIdMatched = threadId == lastRowThreadId;
  252. QString lastRowLogLevel = this->logEntryData(lastRowIndex, Self::LogLevelColumn).toString();
  253. bool logLevelMatched = d->ErrorLogLevel(logLevel) == lastRowLogLevel;
  254. QString lastRowOrigin = this->logEntryData(lastRowIndex, Self::OriginColumn).toString();
  255. bool originMatched = origin == lastRowOrigin;
  256. QDateTime lastRowDateTime =
  257. QDateTime::fromString(this->logEntryData(lastRowIndex, Self::TimeColumn).toString(), timeFormat);
  258. int groupingIntervalInMsecs = 1000;
  259. bool withinGroupingInterval = lastRowDateTime.time().msecsTo(currentDateTime.time()) <= groupingIntervalInMsecs;
  260. groupEntry = threadIdMatched && logLevelMatched && originMatched && withinGroupingInterval;
  261. }
  262. if (!groupEntry)
  263. {
  264. QList<QStandardItem*> itemList;
  265. // Time item
  266. QStandardItem * timeItem = new QStandardItem(currentDateTime.toString(timeFormat));
  267. timeItem->setEditable(false);
  268. itemList << timeItem;
  269. // ThreadId item
  270. QStandardItem * threadIdItem = new QStandardItem(threadId);
  271. threadIdItem->setEditable(false);
  272. itemList << threadIdItem;
  273. // LogLevel item
  274. QStandardItem * logLevelItem = new QStandardItem(d->ErrorLogLevel(logLevel));
  275. logLevelItem->setEditable(false);
  276. itemList << logLevelItem;
  277. // Origin item
  278. QStandardItem * originItem = new QStandardItem(origin);
  279. originItem->setEditable(false);
  280. itemList << originItem;
  281. // Description item
  282. QStandardItem * descriptionItem = new QStandardItem();
  283. QString descriptionText(text);
  284. descriptionItem->setData(descriptionText.left(160).append((descriptionText.size() > 160) ? "..." : ""), Qt::DisplayRole);
  285. descriptionItem->setData(descriptionText, ctkErrorLogModel::DescriptionTextRole);
  286. descriptionItem->setEditable(false);
  287. itemList << descriptionItem;
  288. d->StandardItemModel.invisibleRootItem()->appendRow(itemList);
  289. }
  290. else
  291. {
  292. // Retrieve description associated with last row
  293. QModelIndex lastRowDescriptionIndex =
  294. d->StandardItemModel.index(d->StandardItemModel.rowCount() - 1, ctkErrorLogModel::DescriptionColumn);
  295. QStringList updatedDescription;
  296. updatedDescription << lastRowDescriptionIndex.data(ctkErrorLogModel::DescriptionTextRole).toString();
  297. updatedDescription << text;
  298. d->StandardItemModel.setData(lastRowDescriptionIndex, updatedDescription.join("\n"),
  299. ctkErrorLogModel::DescriptionTextRole);
  300. // Append '...' to displayText if needed
  301. QString displayText = lastRowDescriptionIndex.data().toString();
  302. if (!displayText.endsWith("..."))
  303. {
  304. d->StandardItemModel.setData(lastRowDescriptionIndex, displayText.append("..."), Qt::DisplayRole);
  305. }
  306. }
  307. d->AddingEntry = false;
  308. emit this->entryAdded(logLevel);
  309. }
  310. //------------------------------------------------------------------------------
  311. void ctkErrorLogModel::clear()
  312. {
  313. Q_D(ctkErrorLogModel);
  314. d->StandardItemModel.invisibleRootItem()->removeRows(0, d->StandardItemModel.rowCount());
  315. }
  316. //------------------------------------------------------------------------------
  317. void ctkErrorLogModel::filterEntry(const ctkErrorLogLevel::LogLevels& logLevel,
  318. bool disableFilter)
  319. {
  320. Q_D(ctkErrorLogModel);
  321. QStringList patterns;
  322. if (!this->filterRegExp().pattern().isEmpty())
  323. {
  324. patterns << this->filterRegExp().pattern().split("|");
  325. }
  326. patterns.removeAll(d->ErrorLogLevel(ctkErrorLogLevel::None));
  327. // foreach(QString s, patterns)
  328. // {
  329. // std::cout << "pattern:" << qPrintable(s) << std::endl;
  330. // }
  331. QMetaEnum logLevelEnum = d->ErrorLogLevel.metaObject()->enumerator(0);
  332. Q_ASSERT(QString("LogLevel").compare(logLevelEnum.name()) == 0);
  333. // Loop over enum values and append associated name to 'patterns' if
  334. // it has been specified within 'logLevel'
  335. for (int i = 1; i < logLevelEnum.keyCount(); ++i)
  336. {
  337. int aLogLevel = logLevelEnum.value(i);
  338. if (logLevel & aLogLevel)
  339. {
  340. QString logLevelAsString = d->ErrorLogLevel(static_cast<ctkErrorLogLevel::LogLevel>(aLogLevel));
  341. if (!disableFilter)
  342. {
  343. patterns << logLevelAsString;
  344. d->CurrentLogLevelFilter |= static_cast<ctkErrorLogLevel::LogLevels>(aLogLevel);
  345. }
  346. else
  347. {
  348. patterns.removeAll(logLevelAsString);
  349. d->CurrentLogLevelFilter ^= static_cast<ctkErrorLogLevel::LogLevels>(aLogLevel);
  350. }
  351. }
  352. }
  353. if (patterns.isEmpty())
  354. {
  355. // If there are no patterns, let's filter with the None level so that
  356. // all entries are filtered out.
  357. patterns << d->ErrorLogLevel(ctkErrorLogLevel::None);
  358. }
  359. bool filterChanged = true;
  360. QStringList currentPatterns = this->filterRegExp().pattern().split("|");
  361. if (currentPatterns.count() == patterns.count())
  362. {
  363. foreach(const QString& p, patterns)
  364. {
  365. currentPatterns.removeAll(p);
  366. }
  367. filterChanged = currentPatterns.count() > 0;
  368. }
  369. this->setFilterRegExp(patterns.join("|"));
  370. if (filterChanged)
  371. {
  372. emit this->logLevelFilterChanged();
  373. }
  374. }
  375. //------------------------------------------------------------------------------
  376. ctkErrorLogLevel::LogLevels ctkErrorLogModel::logLevelFilter()const
  377. {
  378. Q_D(const ctkErrorLogModel);
  379. QMetaEnum logLevelEnum = d->ErrorLogLevel.metaObject()->enumerator(0);
  380. Q_ASSERT(QString("LogLevel").compare(logLevelEnum.name()) == 0);
  381. ctkErrorLogLevel::LogLevels filter = ctkErrorLogLevel::Unknown;
  382. foreach(const QString& filterAsString, this->filterRegExp().pattern().split("|"))
  383. {
  384. filter |= static_cast<ctkErrorLogLevel::LogLevels>(logLevelEnum.keyToValue(filterAsString.toLatin1()));
  385. }
  386. return filter;
  387. }
  388. //------------------------------------------------------------------------------
  389. bool ctkErrorLogModel::logEntryGrouping()const
  390. {
  391. Q_D(const ctkErrorLogModel);
  392. return d->LogEntryGrouping;
  393. }
  394. //------------------------------------------------------------------------------
  395. void ctkErrorLogModel::setLogEntryGrouping(bool value)
  396. {
  397. Q_D(ctkErrorLogModel);
  398. d->LogEntryGrouping = value;
  399. }
  400. //------------------------------------------------------------------------------
  401. bool ctkErrorLogModel::asynchronousLogging()const
  402. {
  403. Q_D(const ctkErrorLogModel);
  404. return d->AsynchronousLogging;
  405. }
  406. //------------------------------------------------------------------------------
  407. void ctkErrorLogModel::setAsynchronousLogging(bool value)
  408. {
  409. Q_D(ctkErrorLogModel);
  410. if (d->AsynchronousLogging == value)
  411. {
  412. return;
  413. }
  414. foreach(const QString& handlerName, d->RegisteredHandlers.keys())
  415. {
  416. d->setMessageHandlerConnection(
  417. d->RegisteredHandlers.value(handlerName), value);
  418. }
  419. d->AsynchronousLogging = value;
  420. }
  421. // --------------------------------------------------------------------------
  422. QVariant ctkErrorLogModel::logEntryData(int row, int column, int role) const
  423. {
  424. Q_D(const ctkErrorLogModel);
  425. if (column < 0 || column > Self::MaxColumn
  426. || row < 0 || row > this->logEntryCount())
  427. {
  428. return QVariant();
  429. }
  430. QModelIndex rowDescriptionIndex = d->StandardItemModel.index(row, column);
  431. return rowDescriptionIndex.data(role);
  432. }
  433. // --------------------------------------------------------------------------
  434. QString ctkErrorLogModel::logEntryDescription(int row) const
  435. {
  436. return this->logEntryData(row, Self::DescriptionColumn, Self::DescriptionTextRole).toString();
  437. }
  438. // --------------------------------------------------------------------------
  439. int ctkErrorLogModel::logEntryCount()const
  440. {
  441. Q_D(const ctkErrorLogModel);
  442. return d->StandardItemModel.rowCount();
  443. }