├── .travis.yml ├── include ├── CuteLogger_global.h ├── AndroidAppender.h ├── OutputDebugAppender.h ├── ConsoleAppender.h ├── AbstractStringAppender.h ├── FileAppender.h ├── AbstractAppender.h ├── RollingFileAppender.h └── Logger.h ├── .gitignore ├── CuteLogger.qbs ├── CuteLogger.pro ├── src ├── AndroidAppender.cpp ├── OutputDebugAppender.cpp ├── ConsoleAppender.cpp ├── FileAppender.cpp ├── AbstractAppender.cpp ├── RollingFileAppender.cpp ├── AbstractStringAppender.cpp └── Logger.cpp ├── CMakeLists.txt ├── README.md ├── test └── basictest.cpp ├── LICENSE.LGPL └── Doxyfile /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | language: cpp 3 | compiler: gcc 4 | addons: 5 | apt: 6 | packages: 7 | - qt5-default 8 | 9 | script: 10 | - cmake ./ -DCMAKE_BUILD_TYPE=Debug -DENABLE_TESTS=ON 11 | - make -j4 12 | - ./basictest 13 | -------------------------------------------------------------------------------- /include/CuteLogger_global.h: -------------------------------------------------------------------------------- 1 | #ifndef CUTELOGGER_GLOBAL_H 2 | #define CUTELOGGER_GLOBAL_H 3 | 4 | #include 5 | 6 | #if defined(CUTELOGGER_LIBRARY) 7 | # define CUTELOGGERSHARED_EXPORT Q_DECL_EXPORT 8 | #else 9 | # define CUTELOGGERSHARED_EXPORT Q_DECL_IMPORT 10 | #endif 11 | 12 | #endif // CUTELOGGER_GLOBAL_H 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # C++ objects and libs 2 | 3 | *.slo 4 | *.lo 5 | *.o 6 | *.a 7 | *.la 8 | *.lai 9 | *.so 10 | *.so.* 11 | *.dll 12 | *.dylib 13 | 14 | # Temporary files 15 | 16 | *~ 17 | 18 | # Qt-es 19 | 20 | moc_*.cpp 21 | qrc_*.cpp 22 | *-build-* 23 | 24 | # CMake and qmake 25 | 26 | .qmake.stash 27 | CMakeFiles/ 28 | CMakeCache.txt 29 | cmake_install.cmake 30 | Makefile 31 | Makefile.Debug 32 | Makefile.Release 33 | 34 | # Generated doxygen documentation 35 | 36 | doc/ 37 | 38 | # IDE 39 | 40 | *.pro.user 41 | *.pro.user.* 42 | CMakeLists.txt.user 43 | -------------------------------------------------------------------------------- /include/AndroidAppender.h: -------------------------------------------------------------------------------- 1 | #ifndef ANDROIDAPPENDER_H 2 | #define ANDROIDAPPENDER_H 3 | 4 | // Local 5 | #include 6 | 7 | 8 | class AndroidAppender : public AbstractStringAppender 9 | { 10 | public: 11 | AndroidAppender(); 12 | 13 | static int androidLogPriority(Logger::LogLevel); 14 | 15 | protected: 16 | void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 17 | const char* function, const QString& category, const QString& message); 18 | 19 | }; 20 | 21 | #endif // ANDROIDAPPENDER_H 22 | -------------------------------------------------------------------------------- /CuteLogger.qbs: -------------------------------------------------------------------------------- 1 | import qbs 2 | 3 | DynamicLibrary { 4 | name: "CuteLogger" 5 | 6 | files: [ "src/*", "include/*" ] 7 | excludeFiles: [ "src/OutputDebugAppender.*", "src/AndroidAppender.*" ] 8 | 9 | Group { 10 | name: "windows-OutputDebugAppender" 11 | 12 | condition: qbs.targetOS == "windows" 13 | files: [ "src/OutputDebugAppender.cpp", "include/OutputDebugAppender.h" ] 14 | } 15 | 16 | Depends { name: "cpp" } 17 | cpp.includePaths: "include" 18 | cpp.defines: "CUTELOGGER_LIBRARY" 19 | 20 | Depends { name: "Qt.core" } 21 | 22 | Export { 23 | Depends { name: "cpp" } 24 | cpp.includePaths: "include" 25 | } 26 | 27 | Group { 28 | qbs.install: true 29 | qbs.installDir: "lib" 30 | fileTagsFilter: "dynamiclibrary" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /CuteLogger.pro: -------------------------------------------------------------------------------- 1 | QT -= gui 2 | 3 | TARGET = CuteLogger 4 | TEMPLATE = lib 5 | 6 | DEFINES += CUTELOGGER_LIBRARY 7 | 8 | INCLUDEPATH += ./include 9 | 10 | SOURCES += src/Logger.cpp \ 11 | src/AbstractAppender.cpp \ 12 | src/AbstractStringAppender.cpp \ 13 | src/ConsoleAppender.cpp \ 14 | src/FileAppender.cpp \ 15 | src/RollingFileAppender.cpp 16 | 17 | HEADERS += include/Logger.h \ 18 | include/CuteLogger_global.h \ 19 | include/AbstractAppender.h \ 20 | include/AbstractStringAppender.h \ 21 | include/ConsoleAppender.h \ 22 | include/FileAppender.h \ 23 | include/RollingFileAppender.h 24 | 25 | win32 { 26 | SOURCES += src/OutputDebugAppender.cpp 27 | HEADERS += include/OutputDebugAppender.h 28 | } 29 | 30 | android { 31 | SOURCES += src/AndroidAppender.cpp 32 | HEADERS += include/AndroidAppender.h 33 | } 34 | 35 | unix { 36 | target.path = /usr/lib 37 | INSTALLS += target 38 | } 39 | -------------------------------------------------------------------------------- /include/OutputDebugAppender.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 Karl-Heinz Reichel (khreichel at googlemail 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 | 15 | #ifndef OUTPUTDEBUGAPPENDER_H 16 | #define OUTPUTDEBUGAPPENDER_H 17 | 18 | #include "CuteLogger_global.h" 19 | #include 20 | 21 | 22 | class CUTELOGGERSHARED_EXPORT OutputDebugAppender : public AbstractStringAppender 23 | { 24 | protected: 25 | virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 26 | const char* function, const QString& category, const QString& message); 27 | }; 28 | 29 | #endif // OUTPUTDEBUGAPPENDER_H 30 | -------------------------------------------------------------------------------- /src/AndroidAppender.cpp: -------------------------------------------------------------------------------- 1 | // Local 2 | #include "AndroidAppender.h" 3 | 4 | // Android 5 | #include 6 | 7 | 8 | AndroidAppender::AndroidAppender() 9 | { 10 | setFormat(QLatin1String("<%{function}> %{message}\n")); 11 | } 12 | 13 | 14 | int AndroidAppender::androidLogPriority(Logger::LogLevel logLevel) 15 | { 16 | switch (logLevel) 17 | { 18 | case Logger::Trace: 19 | return ANDROID_LOG_VERBOSE; 20 | case Logger::Debug: 21 | return ANDROID_LOG_DEBUG; 22 | case Logger::Info: 23 | return ANDROID_LOG_INFO; 24 | case Logger::Warning: 25 | return ANDROID_LOG_WARN; 26 | case Logger::Error: 27 | return ANDROID_LOG_ERROR; 28 | case Logger::Fatal: 29 | return ANDROID_LOG_FATAL; 30 | } 31 | 32 | // Just in case 33 | return ANDROID_LOG_DEFAULT; 34 | } 35 | 36 | 37 | void AndroidAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 38 | const char* function, const QString& category, const QString& message) 39 | { 40 | QString msg = formattedString(timeStamp, logLevel, file, line, function, category, message); 41 | QString cat = category; 42 | if (cat.isEmpty()) 43 | cat = QLatin1String("Logger"); 44 | 45 | __android_log_write(androidLogPriority(logLevel), qPrintable(cat), qPrintable(msg)); 46 | } 47 | 48 | -------------------------------------------------------------------------------- /include/ConsoleAppender.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 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 | #ifndef CONSOLEAPPENDER_H 15 | #define CONSOLEAPPENDER_H 16 | 17 | #include "CuteLogger_global.h" 18 | #include 19 | 20 | 21 | class CUTELOGGERSHARED_EXPORT ConsoleAppender : public AbstractStringAppender 22 | { 23 | public: 24 | ConsoleAppender(); 25 | virtual QString format() const; 26 | void ignoreEnvironmentPattern(bool ignore); 27 | 28 | protected: 29 | virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 30 | const char* function, const QString& category, const QString& message); 31 | 32 | private: 33 | bool m_ignoreEnvPattern; 34 | }; 35 | 36 | #endif // CONSOLEAPPENDER_H 37 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 3.1) 2 | 3 | SET(CMAKE_CXX_STANDARD 11) 4 | SET(CMAKE_CXX_STANDARD_REQUIRED ON) 5 | 6 | PROJECT(CuteLogger) 7 | 8 | FIND_PACKAGE(Qt5Core REQUIRED) 9 | 10 | ADD_DEFINITIONS(-DCUTELOGGER_LIBRARY) 11 | 12 | INCLUDE_DIRECTORIES(BEFORE include) 13 | 14 | SET(sources 15 | src/Logger.cpp 16 | src/AbstractAppender.cpp 17 | src/AbstractStringAppender.cpp 18 | src/ConsoleAppender.cpp 19 | src/FileAppender.cpp 20 | src/RollingFileAppender.cpp 21 | ) 22 | 23 | SET(includes 24 | include/Logger.h 25 | include/FileAppender.h 26 | include/CuteLogger_global.h 27 | include/ConsoleAppender.h 28 | include/AbstractStringAppender.h 29 | include/AbstractAppender.h 30 | include/RollingFileAppender.h 31 | ) 32 | 33 | 34 | # OutputDebugAppender is only for Windows systems 35 | IF(WIN32) 36 | SET(sources ${sources} src/OutputDebugAppender.cpp) 37 | SET(includes ${includes} include/OutputDebugAppender.h) 38 | ENDIF(WIN32) 39 | 40 | 41 | SET(library_target CuteLogger) 42 | 43 | ADD_LIBRARY(${library_target} SHARED ${sources} ${includes}) 44 | TARGET_LINK_LIBRARIES(${library_target} Qt5::Core) 45 | TARGET_INCLUDE_DIRECTORIES(${library_target} PUBLIC include) 46 | 47 | INSTALL(TARGETS ${library_target} DESTINATION lib) 48 | 49 | SET(ENABLE_TESTS OFF CACHE BOOL "Enable building CuteLogger tests") 50 | IF (ENABLE_TESTS) 51 | SET(CMAKE_AUTOMOC ON) 52 | FIND_PACKAGE(Qt5Test REQUIRED) 53 | 54 | ADD_EXECUTABLE(basictest test/basictest.cpp) 55 | TARGET_LINK_LIBRARIES(basictest Qt5::Core Qt5::Test CuteLogger) 56 | ENDIF () 57 | -------------------------------------------------------------------------------- /src/OutputDebugAppender.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 Karl-Heinz Reichel (khreichel at googlemail 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 "OutputDebugAppender.h" 16 | 17 | // STL 18 | #include 19 | 20 | 21 | /** 22 | * \class OutputDebugAppender 23 | * 24 | * \brief Appender that writes the log records to the Microsoft Debug Log 25 | */ 26 | 27 | 28 | //! Writes the log record to the windows debug log. 29 | /** 30 | * \sa AbstractStringAppender::format() 31 | */ 32 | void OutputDebugAppender::append(const QDateTime& timeStamp, 33 | Logger::LogLevel logLevel, 34 | const char* file, 35 | int line, 36 | const char* function, 37 | const QString& category, 38 | const QString& message) 39 | { 40 | QString s = formattedString(timeStamp, logLevel, file, line, function, category, message); 41 | OutputDebugStringW((LPCWSTR) s.utf16()); 42 | } 43 | 44 | -------------------------------------------------------------------------------- /include/AbstractStringAppender.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 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 | #ifndef ABSTRACTSTRINGAPPENDER_H 15 | #define ABSTRACTSTRINGAPPENDER_H 16 | 17 | // Local 18 | #include "CuteLogger_global.h" 19 | #include 20 | 21 | // Qt 22 | #include 23 | 24 | 25 | class CUTELOGGERSHARED_EXPORT AbstractStringAppender : public AbstractAppender 26 | { 27 | public: 28 | AbstractStringAppender(); 29 | 30 | virtual QString format() const; 31 | void setFormat(const QString&); 32 | 33 | static QString stripFunctionName(const char*); 34 | 35 | protected: 36 | QString formattedString(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 37 | const char* function, const QString& category, const QString& message) const; 38 | 39 | private: 40 | static QByteArray qCleanupFuncinfo(const char*); 41 | 42 | QString m_format; 43 | mutable QReadWriteLock m_formatLock; 44 | }; 45 | 46 | #endif // ABSTRACTSTRINGAPPENDER_H 47 | -------------------------------------------------------------------------------- /include/FileAppender.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 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 | #ifndef FILEAPPENDER_H 15 | #define FILEAPPENDER_H 16 | 17 | // Logger 18 | #include "CuteLogger_global.h" 19 | #include 20 | 21 | // Qt 22 | #include 23 | #include 24 | 25 | 26 | class CUTELOGGERSHARED_EXPORT FileAppender : public AbstractStringAppender 27 | { 28 | public: 29 | FileAppender(const QString& fileName = QString()); 30 | ~FileAppender(); 31 | 32 | QString fileName() const; 33 | void setFileName(const QString&); 34 | 35 | bool flushOnWrite() const; 36 | void setFlushOnWrite(bool); 37 | 38 | bool flush(); 39 | 40 | bool reopenFile(); 41 | 42 | protected: 43 | virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 44 | const char* function, const QString& category, const QString& message); 45 | bool openFile(); 46 | void closeFile(); 47 | 48 | private: 49 | QFile m_logFile; 50 | bool m_flushOnWrite; 51 | QTextStream m_logStream; 52 | mutable QMutex m_logFileMutex; 53 | }; 54 | 55 | #endif // FILEAPPENDER_H 56 | -------------------------------------------------------------------------------- /include/AbstractAppender.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 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 | #ifndef ABSTRACTAPPENDER_H 15 | #define ABSTRACTAPPENDER_H 16 | 17 | // Local 18 | #include "CuteLogger_global.h" 19 | #include 20 | 21 | // Qt 22 | #include 23 | 24 | 25 | class CUTELOGGERSHARED_EXPORT AbstractAppender 26 | { 27 | public: 28 | AbstractAppender(); 29 | virtual ~AbstractAppender(); 30 | 31 | Logger::LogLevel detailsLevel() const; 32 | void setDetailsLevel(Logger::LogLevel level); 33 | void setDetailsLevel(const QString& level); 34 | 35 | void write(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, const char* function, 36 | const QString& category, const QString& message); 37 | 38 | protected: 39 | virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 40 | const char* function, const QString& category, const QString& message) = 0; 41 | 42 | private: 43 | QMutex m_writeMutex; 44 | 45 | Logger::LogLevel m_detailsLevel; 46 | mutable QMutex m_detailsLevelMutex; 47 | }; 48 | 49 | #endif // ABSTRACTAPPENDER_H 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CuteLogger 2 | [![Build Status](https://travis-ci.org/dept2/CuteLogger.svg?branch=master)](https://travis-ci.org/dept2/CuteLogger) 3 | 4 | Simple, convinient and thread safe logger for Qt-based C++ apps 5 | 6 | ## Features 7 | 8 | - Logs pretty much everything: file name, source line, function signature 9 | - Flexible appender system: log to [file](http://dept2.github.io/CuteLogger/class_file_appender.html), [console](http://dept2.github.io/CuteLogger/class_console_appender.html) or even Android logcat, add custom appenders, customize output format 10 | - Compatible with Qt builtin types. Can be used as a drop-in replacement for qDebug etc. 11 | - Supports [measuring timing](http://dept2.github.io/CuteLogger/_logger_8h.html#af018c228deac1e43b4428889b89dbd13) for an operations 12 | - Supports [log categories](http://dept2.github.io/CuteLogger/_logger_8h.html#a5a9579044777cb4de48b4dbb416b007d), able to log all messages from a class/namespace to custom category 13 | - Thread safe 14 | 15 | ## Documentation 16 | [Doxygen docs available](http://dept2.github.io/CuteLogger/) 17 | 18 | ## Short example 19 | 20 | ```cpp 21 | #include 22 | #include 23 | #include 24 | 25 | int main(int argc, char* argv[]) 26 | { 27 | QCoreApplication app(argc, argv); 28 | ... 29 | ConsoleAppender* consoleAppender = new ConsoleAppender; 30 | consoleAppender->setFormat("[%{type:-7}] <%{Function}> %{message}\n"); 31 | cuteLogger->registerAppender(consoleAppender); 32 | ... 33 | LOG_INFO("Starting the application"); 34 | int result = app.exec(); 35 | ... 36 | if (result) 37 | LOG_WARNING() << "Something went wrong." << "Result code is" << result; 38 | return result; 39 | } 40 | ``` 41 | 42 | ## Adding CuteLogger to your project 43 | 44 | Add this repo as a git submodule to your project. 45 | 46 | ```bash 47 | git submodule add git@github.com:dept2/CuteLogger.git CuteLogger 48 | ``` 49 | 50 | Include it to your CMakeLists.txt file: 51 | ```cmake 52 | ... 53 | ADD_SUBDIRECTORY(Logger) 54 | ... 55 | TARGET_LINK_LIBRARIES(${your_target} ... CuteLogger) 56 | ``` 57 | 58 | Include `Logger.h` and one or several appenders of your choice: 59 | ```cpp 60 | #include 61 | #include 62 | ``` 63 | -------------------------------------------------------------------------------- /src/ConsoleAppender.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 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 "ConsoleAppender.h" 16 | 17 | // STL 18 | #include 19 | 20 | 21 | /** 22 | * \class ConsoleAppender 23 | * 24 | * \brief ConsoleAppender is the simple appender that writes the log records to the std::cerr output stream. 25 | * 26 | * ConsoleAppender uses "[%{type:-7}] <%{function}> %{message}\n" as a default output format. It is similar to the 27 | * AbstractStringAppender but doesn't show a timestamp. 28 | * 29 | * You can modify ConsoleAppender output format without modifying your code by using \c QT_MESSAGE_PATTERN environment 30 | * variable. If you need your application to ignore this environment variable you can call 31 | * ConsoleAppender::ignoreEnvironmentPattern(true) 32 | */ 33 | 34 | 35 | ConsoleAppender::ConsoleAppender() 36 | : AbstractStringAppender() 37 | , m_ignoreEnvPattern(false) 38 | { 39 | setFormat("[%{type:-7}] <%{function}> %{message}\n"); 40 | } 41 | 42 | 43 | QString ConsoleAppender::format() const 44 | { 45 | const QString envPattern = QString::fromLocal8Bit(qgetenv("QT_MESSAGE_PATTERN")); 46 | return (m_ignoreEnvPattern || envPattern.isEmpty()) ? AbstractStringAppender::format() : (envPattern + "\n"); 47 | } 48 | 49 | 50 | void ConsoleAppender::ignoreEnvironmentPattern(bool ignore) 51 | { 52 | m_ignoreEnvPattern = ignore; 53 | } 54 | 55 | 56 | //! Writes the log record to the std::cerr stream. 57 | /** 58 | * \sa AbstractStringAppender::format() 59 | */ 60 | void ConsoleAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 61 | const char* function, const QString& category, const QString& message) 62 | { 63 | std::cerr << qPrintable(formattedString(timeStamp, logLevel, file, line, function, category, message)); 64 | } 65 | -------------------------------------------------------------------------------- /include/RollingFileAppender.h: -------------------------------------------------------------------------------- 1 | #ifndef ROLLINGFILEAPPENDER_H 2 | #define ROLLINGFILEAPPENDER_H 3 | 4 | #include 5 | 6 | #include 7 | 8 | /*! 9 | * \brief The RollingFileAppender class extends FileAppender so that the underlying file is rolled over at a user chosen frequency. 10 | * 11 | * The class is based on Log4Qt.DailyRollingFileAppender class (http://log4qt.sourceforge.net/) 12 | * and has the same date pattern format. 13 | * 14 | * For example, if the fileName is set to /foo/bar and the DatePattern set to the daily rollover ('.'yyyy-MM-dd'.log'), on 2014-02-16 at midnight, 15 | * the logging file /foo/bar.log will be copied to /foo/bar.2014-02-16.log and logging for 2014-02-17 will continue in /foo/bar 16 | * until it rolls over the next day. 17 | * 18 | * The logFilesLimit parameter is used to automatically delete the oldest log files in the directory during rollover 19 | * (so no more than logFilesLimit recent log files exist in the directory at any moment). 20 | * \sa setDatePattern(DatePattern), setLogFilesLimit(int) 21 | */ 22 | class CUTELOGGERSHARED_EXPORT RollingFileAppender : public FileAppender 23 | { 24 | public: 25 | /*! 26 | * The enum DatePattern defines constants for date patterns. 27 | * \sa setDatePattern(DatePattern) 28 | */ 29 | enum DatePattern 30 | { 31 | /*! The minutely date pattern string is "'.'yyyy-MM-dd-hh-mm". */ 32 | MinutelyRollover = 0, 33 | /*! The hourly date pattern string is "'.'yyyy-MM-dd-hh". */ 34 | HourlyRollover, 35 | /*! The half-daily date pattern string is "'.'yyyy-MM-dd-a". */ 36 | HalfDailyRollover, 37 | /*! The daily date pattern string is "'.'yyyy-MM-dd". */ 38 | DailyRollover, 39 | /*! The weekly date pattern string is "'.'yyyy-ww". */ 40 | WeeklyRollover, 41 | /*! The monthly date pattern string is "'.'yyyy-MM". */ 42 | MonthlyRollover 43 | }; 44 | Q_ENUMS(DatePattern) 45 | 46 | RollingFileAppender(const QString& fileName = QString()); 47 | 48 | DatePattern datePattern() const; 49 | void setDatePattern(DatePattern datePattern); 50 | void setDatePattern(const QString& datePattern); 51 | 52 | QString datePatternString() const; 53 | 54 | void setLogFilesLimit(int limit); 55 | int logFilesLimit() const; 56 | 57 | protected: 58 | virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 59 | const char* function, const QString& category, const QString& message); 60 | 61 | private: 62 | void rollOver(); 63 | void computeRollOverTime(); 64 | void computeFrequency(); 65 | void removeOldFiles(); 66 | void setDatePatternString(const QString& datePatternString); 67 | 68 | QString m_datePatternString; 69 | DatePattern m_frequency; 70 | 71 | QDateTime m_rollOverTime; 72 | QString m_rollOverSuffix; 73 | int m_logFilesLimit; 74 | mutable QMutex m_rollingMutex; 75 | }; 76 | 77 | #endif // ROLLINGFILEAPPENDER_H 78 | -------------------------------------------------------------------------------- /test/basictest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | class TestAppender : public AbstractAppender 7 | { 8 | protected: 9 | void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, const char* function, 10 | const QString& category, const QString& message) override; 11 | 12 | public: 13 | struct Record 14 | { 15 | QDateTime timeStamp; 16 | Logger::LogLevel logLevel; 17 | const char* file; 18 | int line; 19 | const char* function; 20 | QString category; 21 | QString message; 22 | }; 23 | QList records; 24 | 25 | void clear() { records.clear(); } 26 | }; 27 | 28 | 29 | void TestAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, const char* function, const QString& category, const QString& message) 30 | { 31 | records.append({ timeStamp, logLevel, file, line, function, category, message }); 32 | } 33 | 34 | 35 | class BasicTest : public QObject 36 | { 37 | Q_OBJECT 38 | 39 | private slots: 40 | void initTestCase(); 41 | 42 | void testCString(); 43 | void testQDebug(); 44 | void testRecursiveQDebug(); 45 | 46 | void cleanupTestCase(); 47 | 48 | private: 49 | TestAppender appender; 50 | 51 | int testQDebugInt(); 52 | }; 53 | 54 | 55 | void BasicTest::initTestCase() 56 | { 57 | cuteLogger->registerAppender(&appender); 58 | } 59 | 60 | 61 | void BasicTest::testCString() 62 | { 63 | LOG_DEBUG("Message"); 64 | 65 | QCOMPARE(appender.records.size(), 1); 66 | TestAppender::Record r = appender.records.last(); 67 | appender.clear(); 68 | 69 | QCOMPARE(r.logLevel, Logger::Debug); 70 | QCOMPARE(r.file, __FILE__); 71 | QVERIFY(r.line != 0); 72 | QCOMPARE(r.function, Q_FUNC_INFO); 73 | QCOMPARE(r.category, QString()); 74 | QCOMPARE(r.message, QStringLiteral("Message")); 75 | } 76 | 77 | 78 | void BasicTest::testQDebug() 79 | { 80 | LOG_DEBUG() << "Message" << 5; 81 | 82 | QCOMPARE(appender.records.size(), 1); 83 | TestAppender::Record r = appender.records.last(); 84 | appender.clear(); 85 | 86 | QCOMPARE(r.logLevel, Logger::Debug); 87 | QCOMPARE(r.file, __FILE__); 88 | QVERIFY(r.line != 0); 89 | QCOMPARE(r.function, Q_FUNC_INFO); 90 | QCOMPARE(r.category, QString()); 91 | QCOMPARE(r.message, QStringLiteral("Message 5 ")); 92 | } 93 | 94 | 95 | void BasicTest::testRecursiveQDebug() 96 | { 97 | LOG_DEBUG() << "Message" << testQDebugInt(); 98 | QCOMPARE(appender.records.size(), 2); 99 | 100 | auto r1 = appender.records.first(); 101 | auto r2 = appender.records.last(); 102 | appender.clear(); 103 | 104 | QCOMPARE(r2.function, Q_FUNC_INFO); 105 | QCOMPARE(r1.message, QStringLiteral("Test ")); 106 | QCOMPARE(r2.message, QStringLiteral("Message 0 ")); 107 | } 108 | 109 | 110 | void BasicTest::cleanupTestCase() 111 | { 112 | cuteLogger->removeAppender(&appender); 113 | } 114 | 115 | 116 | int BasicTest::testQDebugInt() 117 | { 118 | LOG_DEBUG() << "Test"; 119 | return 0; 120 | } 121 | 122 | 123 | QTEST_MAIN(BasicTest) 124 | #include "basictest.moc" 125 | -------------------------------------------------------------------------------- /src/FileAppender.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 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 "FileAppender.h" 16 | 17 | // STL 18 | #include 19 | 20 | /** 21 | * \class FileAppender 22 | * 23 | * \brief Simple appender that writes the log records to the plain text file. 24 | */ 25 | 26 | 27 | //! Constructs the new file appender assigned to file with the given name. 28 | FileAppender::FileAppender(const QString& fileName) 29 | : m_flushOnWrite(false) 30 | { 31 | setFileName(fileName); 32 | } 33 | 34 | 35 | FileAppender::~FileAppender() 36 | { 37 | closeFile(); 38 | } 39 | 40 | 41 | //! Returns the name set by setFileName() or to the FileAppender constructor. 42 | /** 43 | * \sa setFileName() 44 | */ 45 | QString FileAppender::fileName() const 46 | { 47 | QMutexLocker locker(&m_logFileMutex); 48 | return m_logFile.fileName(); 49 | } 50 | 51 | 52 | //! Sets the name of the file. The name can have no path, a relative path, or an absolute path. 53 | /** 54 | * \sa fileName() 55 | */ 56 | void FileAppender::setFileName(const QString& s) 57 | { 58 | if (s.isEmpty()) 59 | std::cerr << " File name is empty. The appender will do nothing" << std::endl; 60 | 61 | QMutexLocker locker(&m_logFileMutex); 62 | if (m_logFile.isOpen()) 63 | m_logFile.close(); 64 | 65 | m_logFile.setFileName(s); 66 | } 67 | 68 | 69 | bool FileAppender::flushOnWrite() const 70 | { 71 | return m_flushOnWrite; 72 | } 73 | 74 | 75 | //! Allows FileAppender to flush file immediately after writing a log record. 76 | /** 77 | * Default value is false. This could result in substantial app slowdown when writing massive amount of log records 78 | * with FileAppender on a rather slow file system due to FileAppender blocking until the data would be phisically 79 | * written. 80 | * 81 | * Leaving this as is may result in some log data not being written if the application crashes. 82 | */ 83 | void FileAppender::setFlushOnWrite(bool flush) 84 | { 85 | m_flushOnWrite = flush; 86 | } 87 | 88 | 89 | //! Force-flush any remaining buffers to file system. Returns true if successful, otherwise returns false. 90 | bool FileAppender::flush() 91 | { 92 | QMutexLocker locker(&m_logFileMutex); 93 | if (m_logFile.isOpen()) 94 | return m_logFile.flush(); 95 | else 96 | return true; 97 | } 98 | 99 | 100 | bool FileAppender::reopenFile() 101 | { 102 | closeFile(); 103 | return openFile(); 104 | } 105 | 106 | 107 | bool FileAppender::openFile() 108 | { 109 | if (m_logFile.fileName().isEmpty()) 110 | return false; 111 | 112 | bool isOpen = m_logFile.isOpen(); 113 | if (!isOpen) 114 | { 115 | isOpen = m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); 116 | if (isOpen) 117 | m_logStream.setDevice(&m_logFile); 118 | else 119 | std::cerr << " Cannot open the log file " << qPrintable(m_logFile.fileName()) << std::endl; 120 | } 121 | return isOpen; 122 | } 123 | 124 | 125 | //! Write the log record to the file. 126 | /** 127 | * \sa fileName() 128 | * \sa AbstractStringAppender::format() 129 | */ 130 | void FileAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 131 | const char* function, const QString& category, const QString& message) 132 | { 133 | QMutexLocker locker(&m_logFileMutex); 134 | 135 | if (openFile()) 136 | { 137 | m_logStream << formattedString(timeStamp, logLevel, file, line, function, category, message); 138 | m_logStream.flush(); 139 | if (m_flushOnWrite) 140 | m_logFile.flush(); 141 | } 142 | } 143 | 144 | 145 | void FileAppender::closeFile() 146 | { 147 | QMutexLocker locker(&m_logFileMutex); 148 | m_logFile.close(); 149 | } 150 | -------------------------------------------------------------------------------- /src/AbstractAppender.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 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 "AbstractAppender.h" 16 | 17 | // Qt 18 | #include 19 | 20 | 21 | /** 22 | * \class AbstractAppender 23 | * 24 | * \brief The AbstractAppender class provides an abstract base class for writing a log entries. 25 | * 26 | * The AbstractAppender class is the base interface class for all log appenders that could be used with Logger. 27 | * 28 | * AbstractAppender provides a common implementation for the thread safe, mutex-protected logging of application 29 | * messages, such as ConsoleAppender, FileAppender or something else. AbstractAppender is abstract and can not be 30 | * instantiated, but you can use any of its subclasses or create a custom log appender at your choice. 31 | * 32 | * Appenders are the logical devices that is aimed to be attached to Logger object by calling 33 | * Logger::registerAppender(). On each log record call from the application Logger object sequentially calls write() 34 | * function on all the appenders registered in it. 35 | * 36 | * You can subclass AbstractAppender to implement a logging target of any kind you like. It may be the external logging 37 | * subsystem (for example, syslog in *nix), XML file, SQL database entries, D-Bus messages or anything else you can 38 | * imagine. 39 | * 40 | * For the simple non-structured plain text logging (for example, to a plain text file or to the console output) you may 41 | * like to subclass the AbstractStringAppender instead of AbstractAppender, which will give you a more convinient way to 42 | * control the format of the log output. 43 | * 44 | * \sa AbstractStringAppender 45 | * \sa Logger::registerAppender() 46 | */ 47 | 48 | 49 | //! Constructs a AbstractAppender object. 50 | AbstractAppender::AbstractAppender() 51 | : m_detailsLevel(Logger::Debug) 52 | {} 53 | 54 | 55 | //! Destructs the AbstractAppender object. 56 | AbstractAppender::~AbstractAppender() 57 | {} 58 | 59 | 60 | //! Returns the current details level of appender. 61 | /** 62 | * Log records with a log level lower than a current detailsLevel() will be silently ignored by appender and would not 63 | * be sent to its append() function. 64 | * 65 | * It provides additional logging flexibility, allowing you to set the different severity levels for different types 66 | * of logs. 67 | * 68 | * \note This function is thread safe. 69 | * 70 | * \sa setDetailsLevel() 71 | * \sa Logger::LogLevel 72 | */ 73 | Logger::LogLevel AbstractAppender::detailsLevel() const 74 | { 75 | QMutexLocker locker(&m_detailsLevelMutex); 76 | return m_detailsLevel; 77 | } 78 | 79 | 80 | //! Sets the current details level of appender. 81 | /** 82 | * Default details level is Logger::Debug 83 | * 84 | * \note This function is thread safe. 85 | * 86 | * \sa detailsLevel() 87 | * \sa Logger::LogLevel 88 | */ 89 | void AbstractAppender::setDetailsLevel(Logger::LogLevel level) 90 | { 91 | QMutexLocker locker(&m_detailsLevelMutex); 92 | m_detailsLevel = level; 93 | } 94 | 95 | 96 | 97 | //! Sets the current details level of appender 98 | /** 99 | * This function is provided for convenience, it behaves like an above function. 100 | * 101 | * \sa detailsLevel() 102 | * \sa Logger::LogLevel 103 | */ 104 | void AbstractAppender::setDetailsLevel(const QString& level) 105 | { 106 | setDetailsLevel(Logger::levelFromString(level)); 107 | } 108 | 109 | 110 | //! Tries to write the log record to this logger 111 | /** 112 | * This is the function called by Logger object to write a log message to the appender. 113 | * 114 | * \note This function is thread safe. 115 | * 116 | * \sa Logger::write() 117 | * \sa detailsLevel() 118 | */ 119 | void AbstractAppender::write(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 120 | const char* function, const QString& category, const QString& message) 121 | { 122 | if (logLevel >= detailsLevel()) 123 | { 124 | QMutexLocker locker(&m_writeMutex); 125 | append(timeStamp, logLevel, file, line, function, category, message); 126 | } 127 | } 128 | 129 | 130 | /** 131 | * \fn virtual void AbstractAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, 132 | * int line, const char* function, const QString& message) 133 | * 134 | * \brief Writes the log record to the logger instance 135 | * 136 | * This function is called every time when user tries to write a message to this AbstractAppender instance using 137 | * the write() function. Write function works as proxy and transfers only the messages with log level more or equal 138 | * to the current logLevel(). 139 | * 140 | * Overload this function when you are implementing a custom appender. 141 | * 142 | * \note This function is not needed to be thread safe because it is never called directly by Logger object. The 143 | * write() function works as a proxy and protects this function from concurrent access. 144 | * 145 | * \sa Logger::write() 146 | */ 147 | 148 | -------------------------------------------------------------------------------- /src/RollingFileAppender.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "RollingFileAppender.h" 6 | 7 | 8 | RollingFileAppender::RollingFileAppender(const QString& fileName) 9 | : FileAppender(fileName) 10 | , m_frequency(DailyRollover) 11 | , m_logFilesLimit(0) 12 | {} 13 | 14 | 15 | void RollingFileAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, 16 | const char* function, const QString& category, const QString& message) 17 | { 18 | if (!m_rollOverTime.isNull() && QDateTime::currentDateTime() > m_rollOverTime) 19 | rollOver(); 20 | 21 | FileAppender::append(timeStamp, logLevel, file, line, function, category, message); 22 | } 23 | 24 | 25 | RollingFileAppender::DatePattern RollingFileAppender::datePattern() const 26 | { 27 | QMutexLocker locker(&m_rollingMutex); 28 | return m_frequency; 29 | } 30 | 31 | 32 | QString RollingFileAppender::datePatternString() const 33 | { 34 | QMutexLocker locker(&m_rollingMutex); 35 | return m_datePatternString; 36 | } 37 | 38 | 39 | void RollingFileAppender::setDatePattern(DatePattern datePattern) 40 | { 41 | switch (datePattern) 42 | { 43 | case MinutelyRollover: 44 | setDatePatternString(QLatin1String("'.'yyyy-MM-dd-hh-mm")); 45 | break; 46 | case HourlyRollover: 47 | setDatePatternString(QLatin1String("'.'yyyy-MM-dd-hh")); 48 | break; 49 | case HalfDailyRollover: 50 | setDatePatternString(QLatin1String("'.'yyyy-MM-dd-a")); 51 | break; 52 | case DailyRollover: 53 | setDatePatternString(QLatin1String("'.'yyyy-MM-dd")); 54 | break; 55 | case WeeklyRollover: 56 | setDatePatternString(QLatin1String("'.'yyyy-ww")); 57 | break; 58 | case MonthlyRollover: 59 | setDatePatternString(QLatin1String("'.'yyyy-MM")); 60 | break; 61 | default: 62 | Q_ASSERT_X(false, "DailyRollingFileAppender::setDatePattern()", "Invalid datePattern constant"); 63 | setDatePattern(DailyRollover); 64 | }; 65 | 66 | QMutexLocker locker(&m_rollingMutex); 67 | m_frequency = datePattern; 68 | 69 | computeRollOverTime(); 70 | } 71 | 72 | 73 | void RollingFileAppender::setDatePattern(const QString& datePattern) 74 | { 75 | setDatePatternString(datePattern); 76 | computeFrequency(); 77 | 78 | computeRollOverTime(); 79 | } 80 | 81 | 82 | void RollingFileAppender::setDatePatternString(const QString& datePatternString) 83 | { 84 | QMutexLocker locker(&m_rollingMutex); 85 | m_datePatternString = datePatternString; 86 | } 87 | 88 | 89 | void RollingFileAppender::computeFrequency() 90 | { 91 | QMutexLocker locker(&m_rollingMutex); 92 | 93 | const QDateTime startTime(QDate(1999, 1, 1), QTime(0, 0)); 94 | const QString startString = startTime.toString(m_datePatternString); 95 | 96 | if (startString != startTime.addSecs(60).toString(m_datePatternString)) 97 | m_frequency = MinutelyRollover; 98 | else if (startString != startTime.addSecs(60 * 60).toString(m_datePatternString)) 99 | m_frequency = HourlyRollover; 100 | else if (startString != startTime.addSecs(60 * 60 * 12).toString(m_datePatternString)) 101 | m_frequency = HalfDailyRollover; 102 | else if (startString != startTime.addDays(1).toString(m_datePatternString)) 103 | m_frequency = DailyRollover; 104 | else if (startString != startTime.addDays(7).toString(m_datePatternString)) 105 | m_frequency = WeeklyRollover; 106 | else if (startString != startTime.addMonths(1).toString(m_datePatternString)) 107 | m_frequency = MonthlyRollover; 108 | else 109 | { 110 | Q_ASSERT_X(false, "DailyRollingFileAppender::computeFrequency", "The pattern '%1' does not specify a frequency"); 111 | return; 112 | } 113 | } 114 | 115 | 116 | void RollingFileAppender::removeOldFiles() 117 | { 118 | if (m_logFilesLimit <= 1) 119 | return; 120 | 121 | QFileInfo fileInfo(fileName()); 122 | QDir logDirectory(fileInfo.absoluteDir()); 123 | logDirectory.setFilter(QDir::Files); 124 | logDirectory.setNameFilters(QStringList() << fileInfo.fileName() + "*"); 125 | QFileInfoList logFiles = logDirectory.entryInfoList(); 126 | 127 | QMap fileDates; 128 | for (int i = 0; i < logFiles.length(); ++i) 129 | { 130 | QString name = logFiles[i].fileName(); 131 | QString suffix = name.mid(name.indexOf(fileInfo.fileName()) + fileInfo.fileName().length()); 132 | QDateTime fileDateTime = QDateTime::fromString(suffix, datePatternString()); 133 | 134 | if (fileDateTime.isValid()) 135 | fileDates.insert(fileDateTime, logFiles[i].absoluteFilePath()); 136 | } 137 | 138 | QList fileDateNames = fileDates.values(); 139 | for (int i = 0; i < fileDateNames.length() - m_logFilesLimit + 1; ++i) 140 | QFile::remove(fileDateNames[i]); 141 | } 142 | 143 | 144 | void RollingFileAppender::computeRollOverTime() 145 | { 146 | Q_ASSERT_X(!m_datePatternString.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern"); 147 | 148 | QDateTime now = QDateTime::currentDateTime(); 149 | QDate nowDate = now.date(); 150 | QTime nowTime = now.time(); 151 | QDateTime start; 152 | 153 | switch (m_frequency) 154 | { 155 | case MinutelyRollover: 156 | { 157 | start = QDateTime(nowDate, QTime(nowTime.hour(), nowTime.minute(), 0, 0)); 158 | m_rollOverTime = start.addSecs(60); 159 | } 160 | break; 161 | case HourlyRollover: 162 | { 163 | start = QDateTime(nowDate, QTime(nowTime.hour(), 0, 0, 0)); 164 | m_rollOverTime = start.addSecs(60*60); 165 | } 166 | break; 167 | case HalfDailyRollover: 168 | { 169 | int hour = nowTime.hour(); 170 | if (hour >= 12) 171 | hour = 12; 172 | else 173 | hour = 0; 174 | start = QDateTime(nowDate, QTime(hour, 0, 0, 0)); 175 | m_rollOverTime = start.addSecs(60*60*12); 176 | } 177 | break; 178 | case DailyRollover: 179 | { 180 | start = QDateTime(nowDate, QTime(0, 0, 0, 0)); 181 | m_rollOverTime = start.addDays(1); 182 | } 183 | break; 184 | case WeeklyRollover: 185 | { 186 | // Qt numbers the week days 1..7. The week starts on Monday. 187 | // Change it to being numbered 0..6, starting with Sunday. 188 | int day = nowDate.dayOfWeek(); 189 | if (day == Qt::Sunday) 190 | day = 0; 191 | start = QDateTime(nowDate, QTime(0, 0, 0, 0)).addDays(-1 * day); 192 | m_rollOverTime = start.addDays(7); 193 | } 194 | break; 195 | case MonthlyRollover: 196 | { 197 | start = QDateTime(QDate(nowDate.year(), nowDate.month(), 1), QTime(0, 0, 0, 0)); 198 | m_rollOverTime = start.addMonths(1); 199 | } 200 | break; 201 | default: 202 | Q_ASSERT_X(false, "DailyRollingFileAppender::computeInterval()", "Invalid datePattern constant"); 203 | m_rollOverTime = QDateTime::fromTime_t(0); 204 | } 205 | 206 | m_rollOverSuffix = start.toString(m_datePatternString); 207 | Q_ASSERT_X(now.toString(m_datePatternString) == m_rollOverSuffix, 208 | "DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval"); 209 | Q_ASSERT_X(m_rollOverSuffix != m_rollOverTime.toString(m_datePatternString), 210 | "DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover"); 211 | } 212 | 213 | 214 | void RollingFileAppender::rollOver() 215 | { 216 | Q_ASSERT_X(!m_datePatternString.isEmpty(), "DailyRollingFileAppender::rollOver()", "No active date pattern"); 217 | 218 | QString rollOverSuffix = m_rollOverSuffix; 219 | computeRollOverTime(); 220 | if (rollOverSuffix == m_rollOverSuffix) 221 | return; 222 | 223 | closeFile(); 224 | 225 | QString targetFileName = fileName() + rollOverSuffix; 226 | QFile f(targetFileName); 227 | if (f.exists() && !f.remove()) 228 | return; 229 | f.setFileName(fileName()); 230 | if (!f.rename(targetFileName)) 231 | return; 232 | 233 | openFile(); 234 | removeOldFiles(); 235 | } 236 | 237 | 238 | void RollingFileAppender::setLogFilesLimit(int limit) 239 | { 240 | QMutexLocker locker(&m_rollingMutex); 241 | m_logFilesLimit = limit; 242 | } 243 | 244 | 245 | int RollingFileAppender::logFilesLimit() const 246 | { 247 | QMutexLocker locker(&m_rollingMutex); 248 | return m_logFilesLimit; 249 | } 250 | -------------------------------------------------------------------------------- /include/Logger.h: -------------------------------------------------------------------------------- 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 | #ifndef LOGGER_H 15 | #define LOGGER_H 16 | 17 | // Qt 18 | #include 19 | #include 20 | #include 21 | 22 | // Local 23 | #include "CuteLogger_global.h" 24 | class AbstractAppender; 25 | 26 | 27 | class Logger; 28 | CUTELOGGERSHARED_EXPORT Logger* cuteLoggerInstance(); 29 | #define cuteLogger cuteLoggerInstance() 30 | 31 | 32 | #define LOG_TRACE CuteMessageLogger(cuteLoggerInstance(), Logger::Trace, __FILE__, __LINE__, Q_FUNC_INFO).write 33 | #define LOG_DEBUG CuteMessageLogger(cuteLoggerInstance(), Logger::Debug, __FILE__, __LINE__, Q_FUNC_INFO).write 34 | #define LOG_INFO CuteMessageLogger(cuteLoggerInstance(), Logger::Info, __FILE__, __LINE__, Q_FUNC_INFO).write 35 | #define LOG_WARNING CuteMessageLogger(cuteLoggerInstance(), Logger::Warning, __FILE__, __LINE__, Q_FUNC_INFO).write 36 | #define LOG_ERROR CuteMessageLogger(cuteLoggerInstance(), Logger::Error, __FILE__, __LINE__, Q_FUNC_INFO).write 37 | #define LOG_FATAL CuteMessageLogger(cuteLoggerInstance(), Logger::Fatal, __FILE__, __LINE__, Q_FUNC_INFO).write 38 | 39 | #define LOG_CTRACE(category) CuteMessageLogger(cuteLoggerInstance(), Logger::Trace, __FILE__, __LINE__, Q_FUNC_INFO, category).write() 40 | #define LOG_CDEBUG(category) CuteMessageLogger(cuteLoggerInstance(), Logger::Debug, __FILE__, __LINE__, Q_FUNC_INFO, category).write() 41 | #define LOG_CINFO(category) CuteMessageLogger(cuteLoggerInstance(), Logger::Info, __FILE__, __LINE__, Q_FUNC_INFO, category).write() 42 | #define LOG_CWARNING(category) CuteMessageLogger(cuteLoggerInstance(), Logger::Warning, __FILE__, __LINE__, Q_FUNC_INFO, category).write() 43 | #define LOG_CERROR(category) CuteMessageLogger(cuteLoggerInstance(), Logger::Error, __FILE__, __LINE__, Q_FUNC_INFO, category).write() 44 | #define LOG_CFATAL(category) CuteMessageLogger(cuteLoggerInstance(), Logger::Fatal, __FILE__, __LINE__, Q_FUNC_INFO, category).write() 45 | 46 | #define LOG_TRACE_TIME LoggerTimingHelper loggerTimingHelper(cuteLoggerInstance(), Logger::Trace, __FILE__, __LINE__, Q_FUNC_INFO); loggerTimingHelper.start 47 | #define LOG_DEBUG_TIME LoggerTimingHelper loggerTimingHelper(cuteLoggerInstance(), Logger::Debug, __FILE__, __LINE__, Q_FUNC_INFO); loggerTimingHelper.start 48 | #define LOG_INFO_TIME LoggerTimingHelper loggerTimingHelper(cuteLoggerInstance(), Logger::Info, __FILE__, __LINE__, Q_FUNC_INFO); loggerTimingHelper.start 49 | 50 | #define LOG_ASSERT(cond) ((!(cond)) ? cuteLoggerInstance()->writeAssert(__FILE__, __LINE__, Q_FUNC_INFO, #cond) : qt_noop()) 51 | #define LOG_ASSERT_X(cond, msg) ((!(cond)) ? cuteLoggerInstance()->writeAssert(__FILE__, __LINE__, Q_FUNC_INFO, msg) : qt_noop()) 52 | 53 | #if (__cplusplus >= 201103L) 54 | #include 55 | 56 | #define LOG_CATEGORY(category) \ 57 | Logger customCuteLoggerInstance{category};\ 58 | std::function cuteLoggerInstance = [&customCuteLoggerInstance]() {\ 59 | return &customCuteLoggerInstance;\ 60 | };\ 61 | 62 | #define LOG_GLOBAL_CATEGORY(category) \ 63 | Logger customCuteLoggerInstance{category, true};\ 64 | std::function cuteLoggerInstance = [&customCuteLoggerInstance]() {\ 65 | return &customCuteLoggerInstance;\ 66 | };\ 67 | 68 | #else 69 | 70 | #define LOG_CATEGORY(category) \ 71 | Logger* cuteLoggerInstance()\ 72 | {\ 73 | static Logger customCuteLoggerInstance(category);\ 74 | return &customCuteLoggerInstance;\ 75 | }\ 76 | 77 | #define LOG_GLOBAL_CATEGORY(category) \ 78 | Logger* cuteLoggerInstance()\ 79 | {\ 80 | static Logger customCuteLoggerInstance(category);\ 81 | customCuteLoggerInstance.logToGlobalInstance(category, true);\ 82 | return &customCuteLoggerInstance;\ 83 | }\ 84 | 85 | #endif 86 | 87 | 88 | class LoggerPrivate; 89 | class CUTELOGGERSHARED_EXPORT Logger 90 | { 91 | Q_DISABLE_COPY(Logger) 92 | 93 | public: 94 | Logger(); 95 | Logger(const QString& defaultCategory, bool writeToGlobalInstance = false); 96 | ~Logger(); 97 | 98 | //! Describes the possible severity levels of the log records 99 | enum LogLevel 100 | { 101 | Trace, //!< Trace level. Can be used for mostly unneeded records used for internal code tracing. 102 | Debug, //!< Debug level. Useful for non-necessary records used for the debugging of the software. 103 | Info, //!< Info level. Can be used for informational records, which may be interesting for not only developers. 104 | Warning, //!< Warning. May be used to log some non-fatal warnings detected by your application. 105 | Error, //!< Error. May be used for a big problems making your application work wrong but not crashing. 106 | Fatal //!< Fatal. Used for unrecoverable errors, crashes the application right after the log record is written. 107 | }; 108 | 109 | //! Sets the timing display mode for the LOG_TRACE_TIME, LOG_DEBUG_TIME and LOG_INFO_TIME macros 110 | enum TimingMode 111 | { 112 | TimingAuto, //!< Show time in seconds, if it exceeds 10s (default) 113 | TimingMs //!< Always use milliseconds to display 114 | }; 115 | 116 | static QString levelToString(LogLevel logLevel); 117 | static LogLevel levelFromString(const QString& s); 118 | 119 | static Logger* globalInstance(); 120 | 121 | void registerAppender(AbstractAppender* appender); 122 | void registerCategoryAppender(const QString& category, AbstractAppender* appender); 123 | 124 | void removeAppender(AbstractAppender* appender); 125 | 126 | void logToGlobalInstance(const QString& category, bool logToGlobal = false); 127 | 128 | void setDefaultCategory(const QString& category); 129 | QString defaultCategory() const; 130 | 131 | void write(const QDateTime& timeStamp, LogLevel logLevel, const char* file, int line, const char* function, const char* category, 132 | const QString& message); 133 | void write(LogLevel logLevel, const char* file, int line, const char* function, const char* category, const QString& message); 134 | 135 | void writeAssert(const char* file, int line, const char* function, const char* condition); 136 | 137 | private: 138 | void write(const QDateTime& timeStamp, LogLevel logLevel, const char* file, int line, const char* function, const char* category, 139 | const QString& message, bool fromLocalInstance); 140 | Q_DECLARE_PRIVATE(Logger) 141 | LoggerPrivate* d_ptr; 142 | }; 143 | 144 | 145 | class CUTELOGGERSHARED_EXPORT CuteMessageLogger 146 | { 147 | Q_DISABLE_COPY(CuteMessageLogger) 148 | 149 | public: 150 | CuteMessageLogger(Logger* l, Logger::LogLevel level, const char* file, int line, const char* function) 151 | : m_l(l), 152 | m_level(level), 153 | m_file(file), 154 | m_line(line), 155 | m_function(function), 156 | m_category(nullptr) 157 | {} 158 | 159 | CuteMessageLogger(Logger* l, Logger::LogLevel level, const char* file, int line, const char* function, const char* category) 160 | : m_l(l), 161 | m_level(level), 162 | m_file(file), 163 | m_line(line), 164 | m_function(function), 165 | m_category(category) 166 | {} 167 | 168 | ~CuteMessageLogger(); 169 | 170 | void write(const char* msg, ...) 171 | #if defined(Q_CC_GNU) && !defined(__INSURE__) 172 | # if defined(Q_CC_MINGW) && !defined(Q_CC_CLANG) 173 | __attribute__ ((format (gnu_printf, 2, 3))) 174 | # else 175 | __attribute__ ((format (printf, 2, 3))) 176 | # endif 177 | #endif 178 | ; 179 | 180 | void write(const QString& msg); 181 | 182 | QDebug write(); 183 | 184 | private: 185 | Logger* m_l; 186 | Logger::LogLevel m_level; 187 | const char* m_file; 188 | int m_line; 189 | const char* m_function; 190 | const char* m_category; 191 | QString m_message; 192 | }; 193 | 194 | 195 | class CUTELOGGERSHARED_EXPORT LoggerTimingHelper 196 | { 197 | Q_DISABLE_COPY(LoggerTimingHelper) 198 | 199 | public: 200 | inline explicit LoggerTimingHelper(Logger* l, Logger::LogLevel logLevel, const char* file, int line, 201 | const char* function) 202 | : m_logger(l), 203 | m_logLevel(logLevel), 204 | m_timingMode(Logger::TimingAuto), 205 | m_file(file), 206 | m_line(line), 207 | m_function(function) 208 | {} 209 | 210 | void start(const char* msg, ...) 211 | #if defined(Q_CC_GNU) && !defined(__INSURE__) 212 | # if defined(Q_CC_MINGW) && !defined(Q_CC_CLANG) 213 | __attribute__ ((format (gnu_printf, 2, 3))) 214 | # else 215 | __attribute__ ((format (printf, 2, 3))) 216 | # endif 217 | #endif 218 | ; 219 | 220 | void start(const QString& msg = QString()); 221 | void start(Logger::TimingMode mode, const QString& msg); 222 | 223 | ~LoggerTimingHelper(); 224 | 225 | private: 226 | Logger* m_logger; 227 | QTime m_time; 228 | Logger::LogLevel m_logLevel; 229 | Logger::TimingMode m_timingMode; 230 | const char* m_file; 231 | int m_line; 232 | const char* m_function; 233 | QString m_block; 234 | }; 235 | 236 | 237 | #endif // LOGGER_H 238 | -------------------------------------------------------------------------------- /src/AbstractStringAppender.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) Nikolay Matyunin (matyunin.n at gmail dot com) 3 | 4 | Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU Lesser General Public License version 2.1 8 | as published by the Free Software Foundation and appearing in the file 9 | LICENSE.LGPL included in the packaging of this file. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU Lesser General Public License for more details. 15 | */ 16 | // Local 17 | #include "AbstractStringAppender.h" 18 | 19 | // Qt 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | 28 | /** 29 | * \class AbstractStringAppender 30 | * 31 | * \brief The AbstractStringAppender class provides a convinient base for appenders working with plain text formatted 32 | * logs. 33 | * 34 | * AbstractSringAppender is the simple extension of the AbstractAppender class providing the convinient way to create 35 | * custom log appenders working with a plain text formatted log targets. 36 | * 37 | * It have the formattedString() protected function that formats the logging arguments according to a format set with 38 | * setFormat(). 39 | * 40 | * This class can not be directly instantiated because it contains pure virtual function inherited from AbstractAppender 41 | * class. 42 | * 43 | * For more detailed description of customizing the log output format see the documentation on the setFormat() function. 44 | */ 45 | 46 | 47 | const char formattingMarker = '%'; 48 | 49 | 50 | //! Constructs a new string appender object 51 | AbstractStringAppender::AbstractStringAppender() 52 | : m_format(QLatin1String("%{time}{yyyy-MM-ddTHH:mm:ss.zzz} [%{type:-7}] <%{function}> %{message}\n")) 53 | {} 54 | 55 | 56 | //! Returns the current log format string. 57 | /** 58 | * The default format is set to "%{time}{yyyy-MM-ddTHH:mm:ss.zzz} [%{type:-7}] <%{function}> %{message}\n". You can set a different log record 59 | * format using the setFormat() function. 60 | * 61 | * \sa setFormat(const QString&) 62 | */ 63 | QString AbstractStringAppender::format() const 64 | { 65 | QReadLocker locker(&m_formatLock); 66 | return m_format; 67 | } 68 | 69 | 70 | //! Sets the logging format for writing strings to the log target with this appender. 71 | /** 72 | * The string format seems to be very common to those developers who have used a standart sprintf function. 73 | * 74 | * Log output format is a simple QString with the special markers (starting with % sign) which will be replaced with 75 | * it's internal meaning when writing a log record. 76 | * 77 | * Controlling marker begins with the percent sign (%) which is followed by the command inside {} brackets 78 | * (the command describes, what will be put to log record instead of marker). 79 | * Optional field width argument may be specified right after the command (through the colon symbol before the closing bracket) 80 | * Some commands requires an additional formatting argument (in the second {} brackets). 81 | * 82 | * Field width argument works almost identically to the \c QString::arg() \c fieldWidth argument (and uses it 83 | * internally). For example, \c "%{type:-7}" will be replaced with the left padded debug level of the message 84 | * (\c "Debug ") or something. For the more detailed description of it you may consider to look to the Qt 85 | * Reference Documentation. 86 | * 87 | * Supported marker commands are: 88 | * \arg \c %{time} - timestamp. You may specify your custom timestamp format using the second {} brackets after the marker, 89 | * timestamp format here will be similiar to those used in QDateTime::toString() function. For example, 90 | * "%{time}{dd-MM-yyyy, HH:mm}" may be replaced with "17-12-2010, 20:17" depending on current date and time. 91 | * The default format used here is "HH:mm:ss.zzz". 92 | * \arg \c %{type} - Log level. Possible log levels are shown in the Logger::LogLevel enumerator. 93 | * \arg \c %{Type} - Uppercased log level. 94 | * \arg \c %{typeOne} - One letter log level. 95 | * \arg \c %{TypeOne} - One uppercase letter log level. 96 | * \arg \c %{File} - Full source file name (with path) of the file that requested log recording. Uses the \c __FILE__ 97 | * preprocessor macro. 98 | * \arg \c %{file} - Short file name (with stripped path). 99 | * \arg \c %{line} - Line number in the source file. Uses the \c __LINE__ preprocessor macro. 100 | * \arg \c %{Function} - Name of function that called on of the LOG_* macros. Uses the \c Q_FUNC_INFO macro provided with 101 | * Qt. 102 | * \arg \c %{function} - Similiar to the %{Function}, but the function name is stripped using stripFunctionName 103 | * \arg \c %{message} - The log message sent by the caller. 104 | * \arg \c %{category} - The log category. 105 | * \arg \c %{appname} - Application name (returned by QCoreApplication::applicationName() function). 106 | * \arg \c %{pid} - Application pid (returned by QCoreApplication::applicationPid() function). 107 | * \arg \c %{threadid} - ID of current thread. 108 | * \arg \c %% - Convinient marker that is replaced with the single \c % mark. 109 | * 110 | * \note Format doesn't add \c '\\n' to the end of the format line. Please consider adding it manually. 111 | * 112 | * \sa format() 113 | * \sa stripFunctionName() 114 | * \sa Logger::LogLevel 115 | */ 116 | void AbstractStringAppender::setFormat(const QString& format) 117 | { 118 | QWriteLocker locker(&m_formatLock); 119 | m_format = format; 120 | } 121 | 122 | 123 | //! Strips the long function signature (as added by Q_FUNC_INFO macro) 124 | /** 125 | * The string processing drops the returning type, arguments and template parameters of function. It is definitely 126 | * useful for enchancing the log output readability. 127 | * \return stripped function name 128 | */ 129 | QString AbstractStringAppender::stripFunctionName(const char* name) 130 | { 131 | return QString::fromLatin1(qCleanupFuncinfo(name)); 132 | } 133 | 134 | 135 | // The function was backported from Qt5 sources (qlogging.h) 136 | QByteArray AbstractStringAppender::qCleanupFuncinfo(const char* name) 137 | { 138 | QByteArray info(name); 139 | 140 | // Strip the function info down to the base function name 141 | // note that this throws away the template definitions, 142 | // the parameter types (overloads) and any const/volatile qualifiers. 143 | if (info.isEmpty()) 144 | return info; 145 | 146 | int pos; 147 | 148 | // skip trailing [with XXX] for templates (gcc) 149 | pos = info.size() - 1; 150 | if (info.endsWith(']')) { 151 | while (--pos) { 152 | if (info.at(pos) == '[') 153 | info.truncate(pos); 154 | } 155 | } 156 | 157 | bool hasLambda = false; 158 | QRegExp lambdaRegex("::"); 159 | int lambdaIndex = lambdaRegex.indexIn(QString::fromLatin1(info)); 160 | if (lambdaIndex != -1) 161 | { 162 | hasLambda = true; 163 | info.remove(lambdaIndex, lambdaRegex.matchedLength()); 164 | } 165 | 166 | // operator names with '(', ')', '<', '>' in it 167 | static const char operator_call[] = "operator()"; 168 | static const char operator_lessThan[] = "operator<"; 169 | static const char operator_greaterThan[] = "operator>"; 170 | static const char operator_lessThanEqual[] = "operator<="; 171 | static const char operator_greaterThanEqual[] = "operator>="; 172 | 173 | // canonize operator names 174 | info.replace("operator ", "operator"); 175 | 176 | // remove argument list 177 | forever { 178 | int parencount = 0; 179 | pos = info.lastIndexOf(')'); 180 | if (pos == -1) { 181 | // Don't know how to parse this function name 182 | return info; 183 | } 184 | 185 | // find the beginning of the argument list 186 | --pos; 187 | ++parencount; 188 | while (pos && parencount) { 189 | if (info.at(pos) == ')') 190 | ++parencount; 191 | else if (info.at(pos) == '(') 192 | --parencount; 193 | --pos; 194 | } 195 | if (parencount != 0) 196 | return info; 197 | 198 | info.truncate(++pos); 199 | 200 | if (info.at(pos - 1) == ')') { 201 | if (info.indexOf(operator_call) == pos - (int)strlen(operator_call)) 202 | break; 203 | 204 | // this function returns a pointer to a function 205 | // and we matched the arguments of the return type's parameter list 206 | // try again 207 | info.remove(0, info.indexOf('(')); 208 | info.chop(1); 209 | continue; 210 | } else { 211 | break; 212 | } 213 | } 214 | 215 | if (hasLambda) 216 | info.append("::lambda"); 217 | 218 | // find the beginning of the function name 219 | int parencount = 0; 220 | int templatecount = 0; 221 | --pos; 222 | 223 | // make sure special characters in operator names are kept 224 | if (pos > -1) { 225 | switch (info.at(pos)) { 226 | case ')': 227 | if (info.indexOf(operator_call) == pos - (int)strlen(operator_call) + 1) 228 | pos -= 2; 229 | break; 230 | case '<': 231 | if (info.indexOf(operator_lessThan) == pos - (int)strlen(operator_lessThan) + 1) 232 | --pos; 233 | break; 234 | case '>': 235 | if (info.indexOf(operator_greaterThan) == pos - (int)strlen(operator_greaterThan) + 1) 236 | --pos; 237 | break; 238 | case '=': { 239 | int operatorLength = (int)strlen(operator_lessThanEqual); 240 | if (info.indexOf(operator_lessThanEqual) == pos - operatorLength + 1) 241 | pos -= 2; 242 | else if (info.indexOf(operator_greaterThanEqual) == pos - operatorLength + 1) 243 | pos -= 2; 244 | break; 245 | } 246 | default: 247 | break; 248 | } 249 | } 250 | 251 | while (pos > -1) { 252 | if (parencount < 0 || templatecount < 0) 253 | return info; 254 | 255 | char c = info.at(pos); 256 | if (c == ')') 257 | ++parencount; 258 | else if (c == '(') 259 | --parencount; 260 | else if (c == '>') 261 | ++templatecount; 262 | else if (c == '<') 263 | --templatecount; 264 | else if (c == ' ' && templatecount == 0 && parencount == 0) 265 | break; 266 | 267 | --pos; 268 | } 269 | info = info.mid(pos + 1); 270 | 271 | // remove trailing '*', '&' that are part of the return argument 272 | while ((info.at(0) == '*') 273 | || (info.at(0) == '&')) 274 | info = info.mid(1); 275 | 276 | // we have the full function name now. 277 | // clean up the templates 278 | while ((pos = info.lastIndexOf('>')) != -1) { 279 | if (!info.contains('<')) 280 | break; 281 | 282 | // find the matching close 283 | int end = pos; 284 | templatecount = 1; 285 | --pos; 286 | while (pos && templatecount) { 287 | char c = info.at(pos); 288 | if (c == '>') 289 | ++templatecount; 290 | else if (c == '<') 291 | --templatecount; 292 | --pos; 293 | } 294 | ++pos; 295 | info.remove(pos, end - pos + 1); 296 | } 297 | 298 | return info; 299 | } 300 | 301 | 302 | //! Returns the string to record to the logging target, formatted according to the format(). 303 | /** 304 | * \sa format() 305 | * \sa setFormat(const QString&) 306 | */ 307 | QString AbstractStringAppender::formattedString(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, 308 | int line, const char* function, const QString& category, const QString& message) const 309 | { 310 | QString f = format(); 311 | const int size = f.size(); 312 | 313 | QString result; 314 | 315 | int i = 0; 316 | while (i < f.size()) 317 | { 318 | QChar c = f.at(i); 319 | 320 | // We will silently ignore the broken % marker at the end of string 321 | if (c != QLatin1Char(formattingMarker) || (i + 2) >= size) 322 | { 323 | result.append(c); 324 | } 325 | else 326 | { 327 | i += 2; 328 | QChar currentChar = f.at(i); 329 | QString command; 330 | int fieldWidth = 0; 331 | 332 | if (currentChar.isLetter()) 333 | { 334 | command.append(currentChar); 335 | int j = 1; 336 | while ((i + j) < size && f.at(i + j).isLetter()) 337 | { 338 | command.append(f.at(i+j)); 339 | j++; 340 | } 341 | 342 | i+=j; 343 | currentChar = f.at(i); 344 | 345 | // Check for the padding instruction 346 | if (currentChar == QLatin1Char(':')) 347 | { 348 | currentChar = f.at(++i); 349 | if (currentChar.isDigit() || currentChar.category() == QChar::Punctuation_Dash) 350 | { 351 | int j = 1; 352 | while ((i + j) < size && f.at(i + j).isDigit()) 353 | j++; 354 | fieldWidth = f.mid(i, j).toInt(); 355 | 356 | i += j; 357 | } 358 | } 359 | } 360 | 361 | // Log record chunk to insert instead of formatting instruction 362 | QString chunk; 363 | 364 | // Time stamp 365 | if (command == QLatin1String("time")) 366 | { 367 | if (f.at(i + 1) == QLatin1Char('{')) 368 | { 369 | int j = 1; 370 | while ((i + 2 + j) < size && f.at(i + 2 + j) != QLatin1Char('}')) 371 | j++; 372 | 373 | if ((i + 2 + j) < size) 374 | { 375 | chunk = timeStamp.toString(f.mid(i + 2, j)); 376 | 377 | i += j; 378 | i += 2; 379 | } 380 | } 381 | 382 | if (chunk.isNull()) 383 | chunk = timeStamp.toString(QLatin1String("HH:mm:ss.zzz")); 384 | } 385 | 386 | // Log level 387 | else if (command == QLatin1String("type")) 388 | chunk = Logger::levelToString(logLevel); 389 | 390 | // Uppercased log level 391 | else if (command == QLatin1String("Type")) 392 | chunk = Logger::levelToString(logLevel).toUpper(); 393 | 394 | // One letter log level 395 | else if (command == QLatin1String("typeOne")) 396 | chunk = Logger::levelToString(logLevel).left(1).toLower(); 397 | 398 | // One uppercase letter log level 399 | else if (command == QLatin1String("TypeOne")) 400 | chunk = Logger::levelToString(logLevel).left(1).toUpper(); 401 | 402 | // Filename 403 | else if (command == QLatin1String("File")) 404 | chunk = QLatin1String(file); 405 | 406 | // Filename without a path 407 | else if (command == QLatin1String("file")) 408 | chunk = QString(QLatin1String(file)).section(QRegExp("[/\\\\]"), -1); 409 | 410 | // Source line number 411 | else if (command == QLatin1String("line")) 412 | chunk = QString::number(line); 413 | 414 | // Function name, as returned by Q_FUNC_INFO 415 | else if (command == QLatin1String("Function")) 416 | chunk = QString::fromLatin1(function); 417 | 418 | // Stripped function name 419 | else if (command == QLatin1String("function")) 420 | chunk = stripFunctionName(function); 421 | 422 | // Log message 423 | else if (command == QLatin1String("message")) 424 | chunk = message; 425 | 426 | else if (command == QLatin1String("category")) 427 | chunk = category; 428 | 429 | // Application pid 430 | else if (command == QLatin1String("pid")) 431 | chunk = QString::number(QCoreApplication::applicationPid()); 432 | 433 | // Appplication name 434 | else if (command == QLatin1String("appname")) 435 | chunk = QCoreApplication::applicationName(); 436 | 437 | // Thread ID (duplicates Qt5 threadid debbuging way) 438 | else if (command == QLatin1String("threadid")) 439 | chunk = QLatin1String("0x") + QString::number(qlonglong(QThread::currentThread()->currentThread()), 16); 440 | 441 | // We simply replace the double formatting marker (%) with one 442 | else if (command == QString(formattingMarker)) 443 | chunk = QLatin1Char(formattingMarker); 444 | 445 | // Do not process any unknown commands 446 | else 447 | { 448 | chunk = QString(formattingMarker); 449 | chunk.append(command); 450 | } 451 | 452 | result.append(QString(QLatin1String("%1")).arg(chunk, fieldWidth)); 453 | } 454 | 455 | ++i; 456 | } 457 | 458 | return result; 459 | } 460 | -------------------------------------------------------------------------------- /LICENSE.LGPL: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | 504 | 505 | -------------------------------------------------------------------------------- /src/Logger.cpp: -------------------------------------------------------------------------------- 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 | // Qt 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | #if defined(Q_OS_ANDROID) 28 | # include 29 | # include 30 | #endif 31 | 32 | // STL 33 | #include 34 | 35 | 36 | /** 37 | * \file Logger.h 38 | * \brief A file containing the description of Logger class and and additional useful macros for logging 39 | */ 40 | 41 | 42 | /** 43 | * \mainpage 44 | * 45 | * Logger is a simple way to write the history of your application lifecycle to any target logging device (which is 46 | * called Appender and may write to any target you will implement with it: console, text file, XML or something - you 47 | * choose) and to map logging message to a class, function, source file and line of code which it is called from. 48 | * 49 | * Some simple appenders (which may be considered an examples) are provided with the Logger itself: see ConsoleAppender 50 | * and FileAppender documentation. 51 | * 52 | * It supports using it in a multithreaded applications, so all of its functions are thread safe. 53 | * 54 | * Simple usage example: 55 | * \code 56 | * #include 57 | * 58 | * #include 59 | * #include 60 | * 61 | * int main(int argc, char* argv[]) 62 | * { 63 | * QCoreApplication app(argc, argv); 64 | * ... 65 | * ConsoleAppender* consoleAppender = new ConsoleAppender; 66 | * consoleAppender->setFormat("[%{type:-7}] <%{Function}> %{message}\n"); 67 | * cuteLogger->registerAppender(consoleAppender); 68 | * ... 69 | * LOG_INFO("Starting the application"); 70 | * int result = app.exec(); 71 | * ... 72 | * if (result) 73 | * LOG_WARNING() << "Something went wrong." << "Result code is" << result; 74 | * 75 | * return result; 76 | * } 77 | * \endcode 78 | * 79 | * Logger internally uses the lazy-initialized singleton object and needs no definite initialization, but you may 80 | * consider registering a log appender before calling any log recording functions or macros. 81 | * 82 | * The library design of Logger allows you to simply mass-replace all occurrences of qDebug and similar calls with 83 | * similar Logger macros (e.g. LOG_DEBUG()) 84 | * 85 | * \note Logger uses a singleton global instance which lives through all the application life cycle and self-destroys 86 | * destruction of the QCoreApplication (or QApplication) instance. It needs a QCoreApplication instance to be 87 | * created before any of the Logger's functions are called. 88 | * 89 | * \sa cuteLogger 90 | * \sa LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_FATAL 91 | * \sa LOG_CTRACE, LOG_CDEBUG, LOG_CINFO, LOG_CWARNING, LOG_CERROR, LOG_CFATAL 92 | * \sa LOG_ASSERT 93 | * \sa LOG_TRACE_TIME, LOG_DEBUG_TIME, LOG_INFO_TIME 94 | * \sa AbstractAppender 95 | */ 96 | 97 | 98 | /** 99 | * \def cuteLogger 100 | * 101 | * \brief Macro returning the current instance of Logger object 102 | * 103 | * If you haven't created a local Logger object it returns the same value as the Logger::globalInstance() functions. 104 | * This macro is a recommended way to get an access to the Logger instance used in current class. 105 | * 106 | * Example: 107 | * \code 108 | * ConsoleAppender* consoleAppender = new ConsoleAppender; 109 | * cuteLogger->registerAppender(consoleAppender); 110 | * \endcode 111 | * 112 | * \sa Logger::globalInstance() 113 | */ 114 | 115 | 116 | /** 117 | * \def LOG_TRACE 118 | * 119 | * \brief Writes the trace log record 120 | * 121 | * This macro is the convinient way to call Logger::write(). It uses the common preprocessor macros \c __FILE__, 122 | * \c __LINE__ and the standart Qt \c Q_FUNC_INFO macros to automatically determine the needed parameters to call 123 | * Logger::write(). 124 | * 125 | * \note This and other (LOG_INFO() etc...) macros uses the variadic macro arguments to give convinient usage form for 126 | * the different versions of Logger::write() (using the QString or const char* argument or returning the QDebug class 127 | * instance). Not all compilers will support this. Please, consider reviewing your compiler documentation to ensure 128 | * it support __VA_ARGS__ macro. 129 | * 130 | * \sa Logger::LogLevel 131 | * \sa Logger::write() 132 | */ 133 | 134 | 135 | /** 136 | * \def LOG_DEBUG 137 | * 138 | * \brief Writes the debug log record 139 | * 140 | * This macro records the debug log record using the Logger::write() function. It works similar to the LOG_TRACE() 141 | * macro. 142 | * 143 | * \sa LOG_TRACE() 144 | * \sa Logger::LogLevel 145 | * \sa Logger::write() 146 | */ 147 | 148 | 149 | /** 150 | * \def LOG_INFO 151 | * 152 | * \brief Writes the info log record 153 | * 154 | * This macro records the info log record using the Logger::write() function. It works similar to the LOG_TRACE() 155 | * macro. 156 | * 157 | * \sa LOG_TRACE() 158 | * \sa Logger::LogLevel 159 | * \sa Logger::write() 160 | */ 161 | 162 | 163 | /** 164 | * \def LOG_WARNING 165 | * 166 | * \brief Write the warning log record 167 | * 168 | * This macro records the warning log record using the Logger::write() function. It works similar to the LOG_TRACE() 169 | * macro. 170 | * 171 | * \sa LOG_TRACE() 172 | * \sa Logger::LogLevel 173 | * \sa Logger::write() 174 | */ 175 | 176 | 177 | /** 178 | * \def LOG_ERROR 179 | * 180 | * \brief Write the error log record 181 | * This macro records the error log record using the Logger::write() function. It works similar to the LOG_TRACE() 182 | * macro. 183 | * 184 | * \sa LOG_TRACE() 185 | * \sa Logger::LogLevel 186 | * \sa Logger::write() 187 | */ 188 | 189 | 190 | /** 191 | * \def LOG_FATAL 192 | * 193 | * \brief Write the fatal log record 194 | * 195 | * This macro records the fatal log record using the Logger::write() function. It works similar to the LOG_TRACE() 196 | * macro. 197 | * 198 | * \note Recording of the log record using the Logger::Fatal log level will lead to calling the STL abort() 199 | * function, which will interrupt the running of your software and begin the writing of the core dump. 200 | * 201 | * \sa LOG_TRACE() 202 | * \sa Logger::LogLevel 203 | * \sa Logger::write() 204 | */ 205 | 206 | 207 | /** 208 | * \def LOG_CTRACE(category) 209 | * 210 | * \brief Writes the trace log record to the specific category 211 | * 212 | * This macro is the similar to the LOG_TRACE() macro, but has a category parameter 213 | * to write only to the category appenders (registered using Logger::registerCategoryAppender() method). 214 | * 215 | * \param category category name string 216 | * 217 | * \sa LOG_TRACE() 218 | * \sa Logger::LogLevel 219 | * \sa Logger::registerCategoryAppender() 220 | * \sa Logger::write() 221 | * \sa LOG_CATEGORY(), LOG_GLOBAL_CATEGORY() 222 | */ 223 | 224 | 225 | /** 226 | * \def LOG_CDEBUG 227 | * 228 | * \brief Writes the debug log record to the specific category 229 | * 230 | * This macro records the debug log record using the Logger::write() function. It works similar to the LOG_CTRACE() 231 | * macro. 232 | * 233 | * \sa LOG_CTRACE() 234 | */ 235 | 236 | 237 | /** 238 | * \def LOG_CINFO 239 | * 240 | * \brief Writes the info log record to the specific category 241 | * 242 | * This macro records the info log record using the Logger::write() function. It works similar to the LOG_CTRACE() 243 | * macro. 244 | * 245 | * \sa LOG_CTRACE() 246 | */ 247 | 248 | 249 | /** 250 | * \def LOG_CWARNING 251 | * 252 | * \brief Writes the warning log record to the specific category 253 | * 254 | * This macro records the warning log record using the Logger::write() function. It works similar to the LOG_CTRACE() 255 | * macro. 256 | * 257 | * \sa LOG_CTRACE() 258 | */ 259 | 260 | 261 | /** 262 | * \def LOG_CERROR 263 | * 264 | * \brief Writes the error log record to the specific category 265 | * 266 | * This macro records the error log record using the Logger::write() function. It works similar to the LOG_CTRACE() 267 | * macro. 268 | * 269 | * \sa LOG_CTRACE() 270 | */ 271 | 272 | 273 | /** 274 | * \def LOG_CFATAL 275 | * 276 | * \brief Write the fatal log record to the specific category 277 | * 278 | * This macro records the fatal log record using the Logger::write() function. It works similar to the LOG_CTRACE() 279 | * macro. 280 | * 281 | * \note Recording of the log record using the Logger::Fatal log level will lead to calling the STL abort() 282 | * function, which will interrupt the running of your software and begin the writing of the core dump. 283 | * 284 | * \sa LOG_CTRACE() 285 | */ 286 | 287 | 288 | /** 289 | * \def LOG_CATEGORY(category) 290 | * 291 | * \brief Create logger instance inside your custom class to log all messages to the specified category 292 | * 293 | * This macro is used to pass all log messages inside your custom class to the specific category. 294 | * You must include this macro inside your class declaration (similarly to the Q_OBJECT macro). 295 | * Internally, this macro redefines cuteLoggerInstance() function, creates the local Logger object inside your class and 296 | * sets the default category to the specified parameter. 297 | * 298 | * Thus, any call to cuteLoggerInstance() (for example, inside LOG_TRACE() macro) will return the local Logger object, 299 | * so any logging message will be directed to the default category. 300 | * 301 | * \note This macro does not register any appender to the newly created logger instance. You should register 302 | * logger appenders manually, inside your class. 303 | * 304 | * Usage example: 305 | * \code 306 | * class CustomClass : public QObject 307 | * { 308 | * Q_OBJECT 309 | * LOG_CATEGORY("custom_category") 310 | * ... 311 | * }; 312 | * 313 | * CustomClass::CustomClass(QObject* parent) : QObject(parent) 314 | * { 315 | * cuteLogger->registerAppender(new FileAppender("custom_category_log")); 316 | * LOG_TRACE() << "Trace to the custom category log"; 317 | * } 318 | * \endcode 319 | * 320 | * If used compiler supports C++11 standard, LOG_CATEGORY and LOG_GLOBAL_CATEGORY macros would also work when added 321 | * inside of any scope. It could be useful, for example, to log every single run of a method to a different file. 322 | * 323 | * \code 324 | * void foo() 325 | * { 326 | * QString categoryName = QDateTime::currentDateTime().toString("yyyy-MM-ddThh-mm-ss-zzz"); 327 | * LOG_CATEGORY(categoryName); 328 | * cuteLogger->registerAppender(new FileAppender(categoryName + ".log")); 329 | * ... 330 | * } 331 | * \endcode 332 | * 333 | * \sa Logger::write() 334 | * \sa LOG_TRACE 335 | * \sa Logger::registerCategoryAppender() 336 | * \sa Logger::setDefaultCategory() 337 | * \sa LOG_GLOBAL_CATEGORY 338 | */ 339 | 340 | 341 | /** 342 | * \def LOG_GLOBAL_CATEGORY(category) 343 | * 344 | * \brief Create logger instance inside your custom class to log all messages both to the specified category and to 345 | * the global logger instance. 346 | * 347 | * This macro is similar to LOG_CATEGORY(), but also passes all log messages to the global logger instance appenders. 348 | * It is equal to defining the local category logger using LOG_CATEGORY macro and calling: 349 | * \code cuteLogger->logToGlobalInstance(cuteLogger->defaultCategory(), true); \endcode 350 | * 351 | * \sa LOG_CATEGORY 352 | * \sa Logger::logToGlobalInstance() 353 | * \sa Logger::defaultCategory() 354 | * \sa Logger::registerCategoryAppender() 355 | * \sa Logger::write() 356 | */ 357 | 358 | 359 | 360 | /** 361 | * \def LOG_ASSERT 362 | * 363 | * \brief Check the assertion 364 | * 365 | * This macro is a convinient and recommended to use way to call Logger::writeAssert() function. It uses the 366 | * preprocessor macros (as the LOG_DEBUG() does) to fill the necessary arguments of the Logger::writeAssert() call. It 367 | * also uses undocumented but rather mature and stable \c qt_noop() function (which does nothing) when the assertion 368 | * is true. 369 | * 370 | * Example: 371 | * \code 372 | * bool b = checkSomething(); 373 | * ... 374 | * LOG_ASSERT(b == true); 375 | * \endcode 376 | * 377 | * \sa Logger::writeAssert() 378 | */ 379 | 380 | 381 | /** 382 | * \def LOG_TRACE_TIME 383 | * 384 | * \brief Logs the processing time of current function / code block 385 | * 386 | * This macro automagically measures the function or code of block execution time and outputs it as a Logger::Trace 387 | * level log record. 388 | * 389 | * Example: 390 | * \code 391 | * int foo() 392 | * { 393 | * LOG_TRACE_TIME(); 394 | * ... // Do some long operations 395 | * return 0; 396 | * } // Outputs: Function foo finished in