ctkErrorLogModel.cpp 18 KB

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