Debian Codegraph @

src/Logger.cpp

raw
1 /*
2 Copyright (c) 2012 Boris Moiseev (cyberbobs at gmail dot com)
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License version 2.1
6 as published by the Free Software Foundation and appearing in the file
7 LICENSE.LGPL included in the packaging of this file.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
13 */
14 // Local
15 #include "Logger.h"
16 #include "AbstractAppender.h"
17 #include "AbstractStringAppender.h"
18
19 #include <QCoreApplication>
20 #include <QReadWriteLock>
21 #include <QSemaphore>
22 #include <QMutex>
23 #include <QDateTime>
24 #include <QIODevice>
25
26 #include <iostream>
27 #include <spdlog/spdlog.h>
28
29 DLOG_CORE_BEGIN_NAMESPACE
30
31 /*!
32 @~english
33 \headerfile <Logger.h>
34 \inmodule dtkcore
35 @brief A file containing the description of Logger class and and additional useful macros for logging.
36 */
37
38 /*!
39 @~english
40 \macro Dtk::Core::dlogger
41 \relates Dtk::Core::Logger
42 \keyword Dtk::Core::dlogger
43
44 @brief Macro returning the current instance of Logger object
45
46 If you haven't created a local Logger object it returns the same value as the Logger::globalInstance() functions.
47 This macro is a recommended way to get an access to the Logger instance used in current class.
48
49 Example:
50 \code
51 ConsoleAppender* consoleAppender = new ConsoleAppender;
52 dlogger->registerAppender(consoleAppender);
53 \endcode
54
55 @sa Dtk::Core::Logger::globalInstance()
56 */
57
58 /*!
59 @~english
60 \macro Dtk::Core::dTrace
61 \relates Dtk::Core::Logger
62 \keyword Dtk::Core::dTrace
63
64 @brief Writes the trace log record
65
66 This macro is the convenient way to call Logger::write(). It uses the common preprocessor macros \c __FILE__,
67 \c __LINE__ and the standard Qt \c Q_FUNC_INFO macros to automatically determine the needed parameters to call
68 Logger::write().
69
70 @note This and other (dInfo() etc...) macros uses the variadic macro arguments to give convenient usage form for
71 the different versions of Logger::write() (using the QString or const char *argument or returning the QDebug class
72 instance). Not all compilers will support this. Please, consider reviewing your compiler documentation to ensure
73 it support __VA_ARGS__ macro.
74
75 @sa Dtk::Core::dInfo Dtk::Core::dDebug Dtk::Core::dWarning Dtk::Core::dError
76 @sa Dtk::Core::Logger::LogLevel
77 @sa Dtk::Core::Logger::write()
78 */
79
80 /*!
81 @~english
82 \macro Dtk::Core::dDebug
83 \relates Dtk::Core::Logger
84 \keyword Dtk::Core::dDebug
85
86 @brief Writes the debug log record
87
88 This macro records the debug log record using the Logger::write() function. It works similar to the dTrace()
89 macro.
90
91 @sa Dtk::Core::dTrace Dtk::Core::dInfo Dtk::Core::dWarning Dtk::Core::dError
92 @sa Dtk::Core::Logger::LogLevel
93 @sa Dtk::Core::Logger::write()
94 */
95
96 /*!
97 @~english
98 \macro Dtk::Core::dInfo
99 \relates Dtk::Core::Logger
100 \keyword Dtk::Core::dInfo
101
102 @brief Writes the info log record
103
104 This macro records the info log record using the Logger::write() function. It works similar to the dTrace()
105 macro.
106
107 @sa Dtk::Core::dTrace Dtk::Core::dDebug Dtk::Core::dWarning Dtk::Core::dError
108 @sa Dtk::Core::Logger::LogLevel
109 @sa Dtk::Core::Logger::write()
110 */
111
112 /*!
113 @~english
114 \macro Dtk::Core::dWarning
115 \relates Dtk::Core::Logger
116 \keyword Dtk::Core::dWarning
117
118 @brief Write the warning log record
119
120 This macro records the warning log record using the Logger::write() function. It works similar to the dTrace()
121 macro.
122
123 @sa Dtk::Core::dTrace Dtk::Core::dInfo Dtk::Core::dDebug Dtk::Core::dError
124 @sa Dtk::Core::Logger::LogLevel
125 @sa Dtk::Core::Logger::write()
126 */
127
128 /*!
129 @~english
130 \macro Dtk::Core::dError
131 \relates Dtk::Core::Logger
132 \keyword Dtk::Core::dError
133
134 @brief Write the error log record
135 This macro records the error log record using the Logger::write() function. It works similar to the dTrace()
136 macro.
137
138 @sa Dtk::Core::dTrace
139 @sa Dtk::Core::Logger::LogLevel
140 @sa Dtk::Core::Logger::write()
141 */
142
143 /*!
144 @~english
145 \macro Dtk::Core::dFatal
146 \relates Dtk::Core::Logger
147 \keyword Dtk::Core::dFatal
148
149 @brief Write the fatal log record
150
151 This macro records the fatal log record using the Logger::write() function. It works similar to the dTrace()
152 macro.
153
154 @note Recording of the log record using the Logger::Fatal log level will lead to calling the STL abort()
155 function, which will interrupt the running of your software and begin the writing of the core dump.
156
157 @sa Dtk::Core::dTrace
158 @sa Dtk::Core::Logger::LogLevel
159 @sa Dtk::Core::Logger::write()
160 */
161
162 /*!
163 @~english
164 \macro Dtk::Core::dCTrace(category)
165 \relates Dtk::Core::Logger
166 \keyword Dtk::Core::dCTrace()
167
168 @brief Writes the trace log record to the specific category
169
170 This macro is the similar to the dTrace() macro, but has a category parameter
171 to write only to the category appenders (registered using Logger::registerCategoryAppender() method).
172
173 @param[in] category category name string
174
175 @sa Dtk::Core::dTrace
176 @sa Dtk::Core::Logger::LogLevel
177 @sa Dtk::Core::Logger::registerCategoryAppender()
178 @sa Dtk::Core::Logger::write()
179 @sa Dtk::Core::dCategory(), Dtk::Core::dGlobalCategory()
180 */
181
182 /*!
183 @~english
184 \macro Dtk::Core::dCDebug
185 \relates Dtk::Core::Logger
186 \keyword Dtk::Core::dCDebug
187
188 @brief Writes the debug log record to the specific category
189
190 This macro records the debug log record using the Logger::write() function. It works similar to the dCTrace()
191 macro.
192
193 @sa Dtk::Core::dCTrace()
194 */
195
196 /*!
197 @~english
198 \macro Dtk::Core::dCInfo
199 \relates Dtk::Core::Logger
200 \keyword Dtk::Core::dCInfo
201
202 @brief Writes the info log record to the specific category
203
204 This macro records the info log record using the Logger::write() function. It works similar to the dCTrace()
205 macro.
206
207 @sa Dtk::Core::dCTrace()
208 */
209
210 /*!
211 @~english
212 \macro Dtk::Core::dCWarning
213 \relates Dtk::Core::Logger
214 \keyword Dtk::Core::dCWarning
215
216 @brief Writes the warning log record to the specific category
217
218 This macro records the warning log record using the Logger::write() function. It works similar to the dCTrace()
219 macro.
220
221 @sa Dtk::Core::dCTrace()
222 */
223
224 /*!
225 @~english
226 \macro Dtk::Core::dCError
227 \relates Dtk::Core::Logger
228 \keyword Dtk::Core::dCError
229
230 @brief Writes the error log record to the specific category
231
232 This macro records the error log record using the Logger::write() function. It works similar to the dCTrace()
233 macro.
234
235 @sa Dtk::Core::dCTrace()
236 */
237
238 /*!
239 @~english
240 \macro Dtk::Core::dCFatal
241 \relates Dtk::Core::Logger
242 \keyword Dtk::Core::dCFatal
243
244 @brief Write the fatal log record to the specific category
245
246 This macro records the fatal log record using the Logger::write() function. It works similar to the dCTrace()
247 macro.
248
249 @note Recording of the log record using the Logger::Fatal log level will lead to calling the STL abort()
250 function, which will interrupt the running of your software and begin the writing of the core dump.
251
252 @sa Dtk::Core::dCTrace()
253 */
254
255 /*!
256 @~english
257 \macro Dtk::Core::dCategory(category)
258 \relates Dtk::Core::Logger
259 \keyword Dtk::Core::dCategory()
260
261 @brief Create dlogger instance inside your custom class to log all messages to the specified \a category
262
263 This macro is used to pass all log messages inside your custom class to the specific \a category.
264 You must include this macro inside your class declaration (similarly to the Q_OBJECT macro).
265 Internally, this macro redefines loggerInstance() function, creates the local Logger object inside your class and
266 sets the default category to the specified parameter.
267
268 Thus, any call to loggerInstance() (for example, inside dTrace() macro) will return the local Logger object,
269 so any logging message will be directed to the default category.
270
271 @note This macro does not register any appender to the newly created dlogger instance. You should register
272 dlogger appenders manually, inside your class.
273
274 Usage example:
275 \code
276 class CustomClass : public QObject
277 {
278 Q_OBJECT
279 dCategory("custom_category")
280 ...
281 };
282
283 CustomClass::CustomClass(QObject* parent) : QObject(parent)
284 {
285 dlogger->registerAppender(new FileAppender("custom_category_log"));
286 dTrace() << "Trace to the custom category log";
287 }
288 \endcode
289
290 @sa Dtk::Core::Logger::write()
291 @sa Dtk::Core::dTrace()
292 @sa Dtk::Core::Logger::registerCategoryAppender()
293 @sa Dtk::Core::Logger::setDefaultCategory()
294 */
295
296 /*!
297 @~english
298 \macro Dtk::Core::dGlobalCategory(category)
299 \relates Dtk::Core::Logger
300 \keyword Dtk::Core::dGlobalCategory()
301
302 @brief Create dlogger instance inside your custom class to log all messages both to the specified \a category and to
303 the global dlogger instance.
304
305 This macro is similar to dCategory(), but also passes all log messages to the global dlogger instance appenders.
306 It is equal to defining the local \a category dlogger using dCategory macro and calling:
307 \code
308 dlogger->logToGlobalInstance(dlogger->defaultCategory(), true);
309 \endcode
310
311 @sa Dtk::Core::dCategory
312 @sa Dtk::Core::Logger::logToGlobalInstance()
313 @sa Dtk::Core::Logger::defaultCategory()
314 @sa Dtk::Core::Logger::registerCategoryAppender()
315 @sa Dtk::Core::Logger::write()
316 */
317
318 /*!
319 @~english
320 \macro Dtk::Core::dAssert
321 \relates Dtk::Core::Logger
322 \keyword Dtk::Core::dAssert
323
324 @brief Check the assertion
325
326 This macro is a convenient and recommended to use way to call Logger::writeAssert() function. It uses the
327 preprocessor macros (as the dDebug() does) to fill the necessary arguments of the Logger::writeAssert() call. It
328 also uses undocumented but rather mature and stable \c qt_noop() function (which does nothing) when the assertion
329 is true.
330
331 Example:
332 \code
333 bool b = checkSomething();
334 ...
335 dAssert(b == true);
336 \endcode
337
338 @sa Dtk::Core::Logger::writeAssert()
339 */
340
341 /*!
342 @~english
343 \macro Dtk::Core::dTraceTime
344 \relates Dtk::Core::Logger
345 \keyword Dtk::Core::dTraceTime
346
347 @brief Logs the processing time of current function / code block
348
349 This macro automagically measures the function or code of block execution time and outputs it as a Logger::Trace
350 level log record.
351
352 Example:
353 \code
354 int foo()
355 {
356 dTraceTime();
357 ... // Do some long operations
358 return 0;
359 } // Outputs: Function foo finished in <time> ms.
360 \endcode
361
362 If you are measuring a code of block execution time you may also add a name of block to the macro:
363 \code
364 int bar(bool doFoo)
365 {
366 dTraceTime();
367
368 if (doFoo)
369 {
370 dTraceTime("Foo");
371 ...
372 }
373
374 ...
375 }
376 // Outputs:
377 // "Foo" finished in <time1> ms.
378 // Function bar finished in <time2> ms.
379 \endcode
380
381 @note Macro switches to logging the seconds instead of milliseconds when the execution time reaches 10000 ms.
382 @sa Dtk::Core::dDebugTime, Dtk::Core::dInfoTime
383 */
384
385 /*!
386 \macro Dtk::Core::dDebugTime
387 \relates Dtk::Core::Logger
388 \keyword Dtk::Core::dDebugTime
389
390 @brief Logs the processing time of current function / code block
391
392 This macro automagically measures the function or code of block execution time and outputs it as a Logger::Debug
393 level log record. It works similar to dTraceTime() macro.
394
395 @sa Dtk::Core::dTraceTime
396 */
397
398 /*!
399 @~english
400 \macro Dtk::Core::dInfoTime
401 \relates Dtk::Core::Logger
402 \keyword Dtk::Core::dInfoTime
403
404 @brief Logs the processing time of current function / code block
405
406 This macro automagically measures the function or code of block execution time and outputs it as a Logger::Info
407 level log record. It works similar to dTraceTime() macro.
408
409 @sa Dtk::Core::dTraceTime
410 */
411
412 /*!
413 @~english
414 \enum Dtk::Core::Logger::LogLevel
415 \value Trace
416 Can be used for mostly unneeded records used for internal code tracing.
417 \value Debug
418 Useful for non-necessary records used for the debugging of the software.
419 \value Info
420 Can be used for informational records, which may be interesting for not only developers.
421 \value Warning
422 May be used to log some non-fatal warnings detected by your application.
423 \value Error
424 May be used for a big problems making your application work wrong but not crashing.
425 \value Fatal
426 Used for unrecoverable errors, crashes the application right after the log record is written.
427 */
428
429 /*!
430 @~english
431 \class Dtk::Core::Logger
432 \inmodule dtkcore
433
434 @brief Very simple but rather powerful component which may be used for logging your application activities.
435
436 Global dlogger instance created on a first access to it (e.g. registering appenders, calling a dDebug() macro
437 etc.) registers itself as a Qt default message handler and captures all the qDebug/dWarning/qCritical output.
438
439 @note Qt 4 qDebug set of macro doesn't support capturing source function name, file name or line number so we
440 recommend to use dDebug() and other Logger macros instead.
441
442 @sa Dtk::Core::dlogger
443 */
444
445 class LogDevice : public QIODevice
446 {
447 public:
448 LogDevice(Logger *l)
449 : m_logger(l),
450 m_semaphore(1)
451 {
452 }
453
454 void lock(Logger::LogLevel level, const char *file, int line,
455 const char *func, const char *category)
456 {
457 m_semaphore.acquire();
458
459 if (!isOpen())
460 open(QIODevice::WriteOnly);
461
462 m_logLevel = level;
463 m_file = file;
464 m_line = line;
465 m_function = func;
466 m_category = category;
467 }
468
469 protected:
470 qint64 readData(char *, qint64)
471 {
472 return 0;
473 }
474
475 qint64 writeData(const char *data, qint64 maxSize)
476 {
477 if (maxSize > 0)
478 {
479 const QString &msg = QString::fromLocal8Bit(QByteArray(data, int(maxSize)));
480 m_logger->write(m_logLevel, m_file, m_line,
481 m_function, m_category, msg);
482 }
483
484 m_semaphore.release();
485 return maxSize;
486 }
487
488 private:
489 Logger *m_logger;
490 QSemaphore m_semaphore;
491 Logger::LogLevel m_logLevel;
492 const char *m_file;
493 int m_line;
494 const char *m_function;
495 const char *m_category;
496 };
497
498 /*!
499 @~english
500 \internal
501
502 LoggerPrivate class implements the Singleton pattern in a thread-safe way. It contains a static pointer to the
503 global dlogger instance protected by QReadWriteLock
504 */
505 class LoggerPrivate
506 {
507 public:
508 static Logger *globalInstance;
509 static QReadWriteLock globalInstanceLock;
510
511 QList<AbstractAppender *> appenders;
512 mutable QMutex loggerMutex;
513
514 QMultiMap<QString, AbstractAppender *> categoryAppenders;
515 QString defaultCategory;
516
517 LogDevice *logDevice;
518 };
519
520 Logger *LoggerPrivate::globalInstance = nullptr;
521 QReadWriteLock LoggerPrivate::globalInstanceLock;
522
523 static void cleanupLoggerGlobalInstance()
524 {
525 QWriteLocker locker(&LoggerPrivate::globalInstanceLock);
526
527 delete LoggerPrivate::globalInstance;
528 LoggerPrivate::globalInstance = nullptr;
529 }
530
531 #if QT_VERSION >= 0x050000
532 static void qtLoggerMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
533 {
534 Logger::LogLevel level = Logger::Warning;
535 switch (type)
536 {
537 case QtDebugMsg:
538 level = Logger::Debug;
539 break;
540 #if QT_VERSION >= 0x050500
541 case QtInfoMsg:
542 level = Logger::Info;
543 break;
544 #endif
545 case QtWarningMsg:
546 level = Logger::Warning;
547 break;
548 case QtCriticalMsg:
549 level = Logger::Error;
550 break;
551 case QtFatalMsg:
552 level = Logger::Fatal;
553 break;
554 }
555
556 bool isDefaultCategory = QString::fromLatin1(context.category) == "default";
557 Logger::globalInstance()->write(level, context.file, context.line, context.function,
558 isDefaultCategory ? nullptr : context.category, msg);
559 }
560
561 #else
562
563 static void qtLoggerMessageHandler(QtMsgType type, const char *msg)
564 {
565 switch (type)
566 {
567 case QtDebugMsg:
568 loggerInstance()->write(Logger::Debug, "", 0, "qDebug", 0, msg);
569 break;
570 case QtWarningMsg:
571 loggerInstance()->write(Logger::Warning, "", 0, "qDebug", 0, msg);
572 break;
573 case QtCriticalMsg:
574 loggerInstance()->write(Logger::Error, "", 0, "qDebug", 0, msg);
575 break;
576 case QtFatalMsg:
577 loggerInstance()->write(Logger::Fatal, "", 0, "qDebug", 0, msg);
578 break;
579 }
580 }
581 #endif
582
583 /*!
584 @~english
585 @brief Construct the instance of Logger.
586
587 If you're only using one global instance of dlogger you wouldn't probably need to use this constructor manually.
588 Consider using [dlogger](@ref dlogger) macro instead to access the dlogger instance
589 */
590 Logger::Logger()
591 : d_ptr(new LoggerPrivate)
592 {
593 Q_D(Logger);
594 d->logDevice = new LogDevice(this);
595 }
596
597 /*!
598 @~english
599 @brief Construct the instance of Logger and set dlogger default category.
600
601 If you're only using one global instance of dlogger you wouldn't probably need to use this constructor manually.
602 Consider using dlogger macro instead to access the dlogger instance and call setDefaultCategory method.
603
604 @sa Logger()
605 @sa setDefaultCategory()
606 */
607 Logger::Logger(const QString &defaultCategory)
608 : Logger()
609 {
610 setDefaultCategory(defaultCategory);
611 }
612
613 /*!
614 @~english
615 @brief Destroy the instance of Logger.
616
617 You probably wouldn't need to use this function directly. Global instance of dlogger will be destroyed automatically
618 at the end of your QCoreApplication execution
619 */
620 Logger::~Logger()
621 {
622 Q_D(Logger);
623
624 QMutexLocker appendersLocker(&d->loggerMutex);
625
626 #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
627 QSet<AbstractAppender *> appenderList{d->appenders.begin(), d->appenders.end()};
628 for (const auto v : d->categoryAppenders.values())
629 {
630 appenderList.insert(v);
631 }
632 #else
633 QSet<AbstractAppender *> appenderList;
634 appenderList += d->appenders.toSet() += d->categoryAppenders.values().toSet();
635 #endif
636 qDeleteAll(appenderList);
637
638 delete d->logDevice;
639 appendersLocker.unlock();
640
641 delete d_ptr;
642 if (!LoggerPrivate::globalInstance ||
643 LoggerPrivate::globalInstance == this)
644 {
645 spdlog::shutdown();
646 }
647 }
648
649 /*!
650 @~english
651 @brief Returns the global instance of Logger.
652
653 In a most cases you shouldn't use this function directly. Consider using [dlogger](@ref dlogger) macro instead.
654
655 @sa Dtk::Core::dlogger
656 */
657 Logger *Logger::globalInstance()
658 {
659 Logger *result = nullptr;
660 {
661 QReadLocker locker(&LoggerPrivate::globalInstanceLock);
662 result = LoggerPrivate::globalInstance;
663 }
664
665 if (!result)
666 {
667 QWriteLocker locker(&LoggerPrivate::globalInstanceLock);
668 LoggerPrivate::globalInstance = new Logger;
669
670 #if QT_VERSION >= 0x050000
671 qInstallMessageHandler(qtLoggerMessageHandler);
672 #else
673 qInstallMsgHandler(qtLoggerMessageHandler);
674 #endif
675 qAddPostRoutine(cleanupLoggerGlobalInstance);
676 result = LoggerPrivate::globalInstance;
677
678 spdlog::set_automatic_registration(true);
679 spdlog::set_pattern("%v");
680 }
681
682 return result;
683 }
684
685 /*!
686 @~english
687 @brief Converts the LogLevel enum value to its string representation.
688
689 \a logLevel Log level to convert
690
691 @sa LogLevel
692 @sa levelFromString()
693 */
694 QString Logger::levelToString(Logger::LogLevel level)
695 {
696 switch (level)
697 {
698 case Trace:
699 return QLatin1String("Trace");
700 case Debug:
701 return QLatin1String("Debug");
702 case Info:
703 return QLatin1String("Info");
704 case Warning:
705 return QLatin1String("Warning");
706 case Error:
707 return QLatin1String("Error");
708 case Fatal:
709 return QLatin1String("Fatal");
710 }
711
712 return QString();
713 }
714
715 /*!
716 @~english
717 @brief Converts the LogLevel string representation to enum value.
718
719 Comparation of the strings is case independent. If the log level string provided cannot be understood
720 Logger::Debug is returned.
721
722 \a s String to be decoded
723
724 @sa LogLevel
725 @sa levelToString()
726 */
727 Logger::LogLevel Logger::levelFromString(const QString &str)
728 {
729 const QString &s = str.trimmed().toLower();
730
731 LogLevel result = Debug;
732
733 if (s == QLatin1String("trace"))
734 result = Trace;
735 else if (s == QLatin1String("debug"))
736 result = Debug;
737 else if (s == QLatin1String("info"))
738 result = Info;
739 else if (s == QLatin1String("warning"))
740 result = Warning;
741 else if (s == QLatin1String("error"))
742 result = Error;
743 else if (s == QLatin1String("fatal"))
744 result = Fatal;
745
746 return result;
747 }
748
749 /*!
750 @~english
751 @brief Registers the appender to write the log records to.
752
753 On the log writing call (using one of the macros or the write() function) Logger traverses through the list of
754 the appenders and writes a log records to the each of them. Please, look through the AbstractAppender
755 documentation to understand the concept of appenders.
756
757 If no appenders was added to Logger, it falls back to logging into the \c std::cerr STL stream.
758
759 \a appender Appender to register in the Logger
760
761 @note Logger takes ownership on the appender and it will delete it on the application exit. According to this,
762 appenders must be created on heap to prevent double destruction of the appender.
763
764 @sa registerCategoryAppender
765 @sa AbstractAppender
766 */
767 void Logger::registerAppender(AbstractAppender *appender)
768 {
769 Q_D(Logger);
770 QMutexLocker locker(&d->loggerMutex);
771
772 if (!d->appenders.contains(appender))
773 d->appenders.append(appender);
774 else
775 std::cerr << "Trying to register appender that was already registered" << std::endl;
776 }
777
778 /*!
779 @~english
780 @brief Registers the appender to write the log records to the specific category.
781
782 Calling this method, you can link some appender with the named category.
783 On the log writing call to the specific category (calling write() with category parameter directly,
784 writing to the default category, or using special dCDebug(), dCWarning() etc. macros),
785 Logger writes the log message only to the list of registered category appenders.
786
787 You can call logToGlobalInstance() to pass all category log messages to the global dlogger instance appenders
788 (registered using registerAppender()).
789 If no category appenders with specific name was registered to the Logger,
790 it falls back to logging into the \c std::cerr STL stream, both with simple warning message.
791
792 @param[in] category Category name
793 @param[in] appender Appender to register in the Logger
794
795 @note Logger takes ownership on the appender and it will delete it on the application exit. According to this,
796 appenders must be created on heap to prevent double destruction of the appender.
797
798 @sa registerAppender
799 @sa Dtk::Core::dCTrace(), Dtk::Core::dCDebug(), Dtk::Core::dCInfo(), Dtk::Core::dCWarning(), Dtk::Core::dCError(), Dtk::Core::dCFatal()
800 @sa Dtk::Core::dCategory(), Dtk::Core::dGlobalCategory()
801 @sa logToGlobalInstance()
802 @sa setDefaultCategory()
803 */
804 void Logger::registerCategoryAppender(const QString &category, AbstractAppender *appender)
805 {
806 Q_D(Logger);
807 QMutexLocker locker(&d->loggerMutex);
808
809 if (!d->categoryAppenders.contains(category, appender))
810 d->categoryAppenders.insert(category, appender);
811 else
812 std::cerr << "Trying to register category [" << qPrintable(category) << "] appender that was already registered" << std::endl;
813 }
814
815 /*!
816 @~english
817 @brief Links some logging category with the global dlogger instance appenders.
818
819 If set to true, all log messages to the specified category appenders will also be written to the global dlogger instance appenders,
820 registered using registerAppender().
821
822 By default, all messages to the specific category are written only to the specific category appenders
823 (registered using registerCategoryAppender()).
824
825 @param category Category name
826 @param logToGlobal Link or onlink the category from global dlogger instance appender
827
828 @sa globalInstance
829 @sa registerAppender
830 @sa registerCategoryAppender
831 */
832 void Logger::logToGlobalInstance(const QString &category, bool logToGlobal)
833 {
834 Q_UNUSED(category)
835 Q_UNUSED(logToGlobal)
836 std::cerr << "DEPRECATED! no longer take effect" << std::endl;
837 }
838
839 /*!
840 @~english
841 @brief Sets default logging category.
842
843 All log messages to this category appenders will also be written to general dlogger instance appenders (registered
844 using [registerAppender](@ref registerAppender) method), and vice versa.
845 In particular, any calls to the dDebug() macro will be treated as category logging,
846 so you needn't to specify category name using dCDebug() macro.
847
848 To unset the default category, pass a null string as a parameter.
849
850 @param[in] category Category name
851
852 @note "category" format marker will be set to the category name for all of these messages
853 (see [AbstractStringAppender::setFormat](@ref AbstractStringAppender::setFormat)).
854
855 @sa defaultCategory()
856 @sa registerCategoryAppender()
857 @sa logToGlobalInstance()
858 */
859 void Logger::setDefaultCategory(const QString &category)
860 {
861 Q_D(Logger);
862 QMutexLocker locker(&d->loggerMutex);
863 d->defaultCategory = category;
864 }
865
866 /*!
867 @~english
868 @sa setDefaultCategory
869 @brief Returns default logging category name
870 */
871 QString Logger::defaultCategory() const
872 {
873 Q_D(const Logger);
874 QMutexLocker locker(&d->loggerMutex);
875 return d->defaultCategory;
876 }
877
878 /*!
879 @~english
880 @brief Writes the log record.
881
882 Writes the log records with the supplied arguments to all the registered appenders.
883
884 @note It is not recommended to call this function directly. Instead of this you can just call one of the macros
885 (dTrace, dTrac, dInfo, dWarning, dError, dFatal) that will supply all the needed
886 information to this function.
887
888 @param[in] time - the time stamp of the record
889 @param[in] logLevel - the log level of the record
890 @param[in] file - the name of the source file that requested the log record
891 @param[in] line - the line of the code of source file that requested the log record
892 @param[in] function - name of the function that requested the log record
893 @param[in] category - logging category (0 for default category)
894 @param[in] message - log message
895
896 @note Recording of the log record using the Logger::Fatal log level will lead to calling the STL abort()
897 function, which will interrupt the running of your software and begin the writing of the core dump.
898
899 @sa LogLevel
900 @sa Dtk::Core::dTrace(), Dtk::Core::dDebug(), Dtk::Core::dInfo(), Dtk::Core::dWarning(), Dtk::Core::dError(), Dtk::Core::dFatal()
901 @sa AbstractAppender
902 */
903 void Logger::write(const QDateTime &time, Logger::LogLevel level, const char *file, int line,
904 const char *func, const char *category, const QString &msg)
905 {
906 write(time, level, file, line, func, category, msg, /* fromLocalInstance = */ false);
907 }
908
909 /*!
910 @~english
911 This is the overloaded function provided for the convenience. It behaves similar to the above function.
912
913 This function uses the current timestamp obtained with @sa QDateTime::currentDateTime().
914
915 @sa write()
916 */
917 void Logger::write(Logger::LogLevel level, const char *file, int line,
918 const char *func, const char *category, const QString &msg)
919 {
920 write(QDateTime::currentDateTime(), level, file, line, func, category, msg);
921 }
922
923 /*!
924 @~english
925 This is the overloaded function provided for the convenience. It behaves similar to the above function.
926
927 This function doesn't accept any log message as argument. It returns the \c QDebug object that can be written
928 using the stream functions. For example, you may like to write:
929 \code
930 dDebug() << "This is the size" << size << "of the element" << elementName;
931 \endcode
932 instead of writing
933 \code
934 dDebug(QString(QLatin1String("This is the size %1x%2 of the element %3"))
935 .arg(size.x()).arg(size.y()).arg(elementName));
936 \endcode
937
938 Please consider reading the Qt Reference Documentation for the description of the QDebug class usage syntax.
939
940 @note This overload is definitely more pleasant to use than the first write() overload, but it behaves definitely
941 slower than all the above overloads.
942
943 @sa write()
944 */
945 QDebug Logger::write(Logger::LogLevel level, const char *file, int line,
946 const char *func, const char *category)
947 {
948 Q_D(Logger);
949
950 d->logDevice->lock(level, file, line, func, category);
951 return QDebug(d->logDevice);
952 }
953
954 /*!
955 @~english
956 @brief Writes the assertion.
957
958 This function writes the assertion record using the write() function.
959
960 The assertion record is always written using the Logger::Fatal log level which leads to the abortation of the
961 program and generation of the core dump (if supported).
962
963 The message written to the appenders will be identical to the \a condition argument prefixed with the
964 <tt>ASSERT:</tt> notification.
965
966 The @param[in] file parameter is the current file name.
967 The @param[in] line parameter indicates the number of lines to output.
968 The @param[in] func parameter indicates the function name to output.
969
970 @note It is not recommended to call this function directly. Instead of this you can just call the LOG_ASSERT
971 macro that will supply all the needed information to this function.
972
973 @sa write()
974 */
975 void Logger::writeAssert(const char *file, int line,
976 const char *func, const char *condition)
977 {
978 write(Logger::Fatal, file, line, func, nullptr, QString("ASSERT: \"%1\"").arg(condition));
979 }
980
981 void Logger::write(const QDateTime &time, Logger::LogLevel level, const char *file, int line,
982 const char *func, const char *category, const QString &msg, bool fromLocalInstance)
983 {
984 Q_D(Logger);
985 QMutexLocker locker(&d->loggerMutex);
986
987 QString logCategory = QString::fromLatin1(category);
988 if (logCategory.isNull() && !d->defaultCategory.isNull())
989 logCategory = d->defaultCategory;
990
991 bool wasWritten = false;
992 bool isGlobalInstance = this == globalInstance();
993
994 if (!logCategory.isNull())
995 {
996 QList<AbstractAppender *> appenders = d->categoryAppenders.values(logCategory);
997
998 for (AbstractAppender *appender : appenders)
999 appender->write(time, level, file, line, func, logCategory, msg);
1000 if (!appenders.isEmpty())
1001 wasWritten = true;
1002 }
1003
1004 // if we can't find the corresponding category, log will be appended to all Appenders.
1005 if (!wasWritten)
1006 {
1007 if (!d->appenders.isEmpty())
1008 {
1009 for (AbstractAppender *appender : d->appenders)
1010 appender->write(time, level, file, line, func, logCategory, msg);
1011
1012 wasWritten = true;
1013 }
1014 else
1015 {
1016 static bool noAppendersWarningShown = false;
1017 if (!noAppendersWarningShown)
1018 {
1019 std::cerr << "No appenders registered with dlogger" << std::endl;
1020 noAppendersWarningShown = true;
1021 }
1022 }
1023 }
1024
1025 // local dlogger instances send category messages to the global instance
1026 if (!logCategory.isNull() && !isGlobalInstance)
1027 globalInstance()->write(time, level, file, line, func, logCategory.toLatin1(), msg, true);
1028
1029 if (!wasWritten && !fromLocalInstance)
1030 {
1031 QString result = QString(QLatin1String("[%1] <%2> %3")).arg(levelToString(level), -7).arg(AbstractStringAppender::stripFunctionName(func)).arg(msg);
1032 std::cerr << qPrintable(result) << std::endl;
1033 }
1034
1035 if (level == Logger::Fatal)
1036 {
1037 std::cerr << "fatal level error occured, the program will abort!";
1038 abort();
1039 }
1040 }
1041
1042 Logger *loggerInstance()
1043 {
1044 return Logger::globalInstance();
1045 }
1046
1047 class DLOG_DECL_DEPRECATED CuteMessageLogger
1048 {
1049 Q_DISABLE_COPY(CuteMessageLogger)
1050 public:
1051 Q_DECL_CONSTEXPR CuteMessageLogger(Logger *, Logger::LogLevel,
1052 const char *, int, const char *)
1053 {
1054 }
1055
1056 Q_DECL_CONSTEXPR CuteMessageLogger(Logger *l, Logger::LogLevel, const char *,
1057 int, const char *, const char *)
1058 {
1059 }
1060 void write(const char *msg, ...) const;
1061 void write(const QString &msg) const;
1062 QDebug write() const;
1063 };
1064
1065 void CuteMessageLogger::write(const char * /*msg*/, ...) const
1066 {
1067 write();
1068 }
1069
1070 void CuteMessageLogger::write(const QString & /*msg*/) const
1071 {
1072 write();
1073 }
1074
1075 QDebug CuteMessageLogger::write() const
1076 {
1077 return QDebug(QtWarningMsg) << "DEPRECATED! rebuild your application with lastest DtkCore";
1078 }
1079
1080 DLOG_CORE_END_NAMESPACE
1081 #include "Logger.moc"