http://gitorious.org/log4qt/log4qt/archive-tarball/master
git clone git://gitorious.org/log4qt/log4qt.git
cd log4qtcmake -DQT_USE_QTSQL=TRUE -DCMAKE_BUILD_TYPE=Release .makemake install
cd log4qtcmake -DQT_USE_QTSQL=TRUE -DCMAKE_BUILD_TYPE=Release -G "MinGW Makefiles" .mingw32-makemingw32-make install
CONFIG += log4qt
find_package(log4qt PATHS ${QT_MKSPECS_DIR}/cmake NO_DEFAULT_PATH)include_directories(${LOG4QT_INCLUDE_DIRS}) target_link_libraries(main ${QT_LIBRARIES} log4qt)
#include <Log4Qt/logmanager.h>#include <Log4Qt/simplelayout.h>#include <Log4Qt/consoleappender.h>#include <Log4Qt/databaselayout.h>#include <Log4Qt/databaseappender.h>#include <Log4Qt/ttcclayout.h>#include <Log4Qt/consoleappender.h>
using namespace Log4Qt;
QTranslator trans;trans.load("log4qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));app.installTranslator(&trans);
LogManager::rootLogger();
LogManager::setHandleQtMessages(true);
simpleLayout = new SimpleLayout();simpleLayout->setName(QLatin1String("SimpleLayout"));
simpleLayout->activateOptions();
TTCCLayout *ttccLayout = new TTCCLayout(TTCCLayout::ISO8601);ttccLayout->setName(QLatin1String("TtccLayout"));ttccLayout->activateOptions();
ConsoleAppender *consoleAppender = new ConsoleAppender(simpleLayout, ConsoleAppender::STDOUT_TARGET);consoleAppender->setName(QLatin1String("ConsoleAppender"));consoleAppender->activateOptions();
SignalAppender *signalAppeder = new SignalAppender();signalAppeder->setName("SignalAppender");
signalAppeder->setLayout(ttccLayout);signalAppeder->activateOptions();
LogManager::rootLogger()->addAppender(d->signalAppeder);LogManager::rootLogger()->addAppender(d->consoleAppender);
LogManager::logger("SimpleLogger");
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");db.setDatabaseName("postgres");db.open("postgres", "postgres"));db.exec("CREATE TABLE log_table( time_stamp timestamp without time zone, logger text, thread text, _level text, message text)WITH ( OIDS=FALSE);");
DatabaseLayout *dbLayout = new DatabaseLayout();
dbLayout->setTimeStampColumn("time_stamp");dbLayout->setLoggerNameColumn("logger");dbLayout->setThreadNameColumn("thread");dbLayout->setLevelColumn("_level");dbLayout->setMessageColumn("message");
DatabaseAppender *dbAppender = new DatabaseAppender(dbLayout, "log_table", db.connectionName());dbAppender->setName(QLatin1String("DatabaseAppender"));dbAppender->activateOptions();
LogManager::logger("Database")->addAppender(dbAppender);LogManager::logger("Database")->addAppender(consoleAppender);
LogManager::logger("Database")->info("Message from " + Q_FUNC_INFO);
RollingFileAppender *dbFileAppender = new RollingFileAppender(ttccLayout,"myapp.log", true);d->dbFileAppender->setName("FileAppender");d->dbFileAppender->activateOptions();d->dbFileAppender->setMaximumFileSize(1024*1024*10); // max file size 10 mbLogManager::logger("FileLogger")->addAppender(dbFileAppender);
Log4Qt::DatabaseLayout::set*Column(columnName);
Log4Qt::DatabaseAppender::setConnection(connectionName);Log4Qt::DatabaseAppender::setTable(tableName);
Log4Qt::LogManager::logger(loggerName)::addAppender()
Log4Qt::LogManager::rootLogger()::addAppender()
Log4Qt::LogManager::logger("Имя подпроекта")->debug(QString("%1 - %2").arg(Q_FUNC_INFO,"исходное сообщение"))
Log4Qt::LogManager::logger("Имя подпроекта")->warn(QString("%1 - %2").arg(Q_FUNC_INFO,"исходное сообщение"))
C++ (Qt)Log4Qt::LogManager::logger("Имя подпроекта")->debug(QString("%1 - %2").arg(Q_FUNC_INFO,"исходное сообщение"))
Log4Qt::LogManager::setHandleQtMessages(true);
Log4Qt::LogManager::qtLogger()
ColorConsoleAppender::ColorMap colorMap;colorMap[".*Qt.*"] = QPair<int,int>(ColorConsoleAppender::ForegroundLightGreen, ColorConsoleAppender::BackgroundBlue);colorMap[".*INFO.*Logger - .*"] = QPair<int,int>(ColorConsoleAppender::ForegroundLightGreen, ColorConsoleAppender::BackgroundBlue);colorMap[".*WARN.*Logger.*"] = QPair<int,int>(ColorConsoleAppender::ForegroundLightRed, ColorConsoleAppender::BackgroundBlue);
Log4Qt::ColorConsoleAppender::setColorMap()
Log4Qt::LogManager::logger()::addAppender()
/****************************************************************************** * * package: log4qt * file: colorconsoleappender.h * created: March 2010 * author: Filonenko Michael * * * Copyright 2010 Filonenko Michael * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/#ifndef _COLORCONSOLEAPPENDER_H#define _COLORCONSOLEAPPENDER_H/****************************************************************************** * Dependencies ******************************************************************************/#include "consoleappender.h"#include <QtCore/QHash>#include <QtCore/QPair>#include <QtCore/QRegExp>/****************************************************************************** * Declarations ******************************************************************************/class QFile;class QTextStream;namespace Log4Qt{ /*! * \brief The class ConsoleAppender appends to stdout or stderr. * * \note All the functions declared in this class are thread-safe. * * \note The ownership and lifetime of objects of this class are managed. * See \ref Ownership "Object ownership" for more details. */ class LOG4QT_EXPORT ColorConsoleAppender : public ConsoleAppender { Q_OBJECT Q_ENUMS(ForegroundColor BackgroundColor Colors) public: typedef QHash<QString, QPair<int, int> > ColorMap;#if defined(linux) || defined(__linux) || defined(__linux__) || defined(Q_OS_UNIX) enum ForegroundColor { ForegroundLightBlack = 30 , ForegroundLightRed = 31 , ForegroundLightGreen = 32 , ForegroundLightYellow = 33 , ForegroundLightBlue = 34 , ForegroundLightPurple = 35 , ForegroundLightCyan = 36 , ForegroundLightWhite = 37 }; enum BackgroundColor { BackgroundBlack = 40 , BackgroundRed = 41 , BackgroundGreen = 42 , BackgroundYellow = 43 , BackgroundBlue = 44 , BackgroundPurple = 45 , BackgroundCyan = 46 , BackgroundWhite = 47 }; enum Colors { Default = 0 , Bright = 1 , Blink = 5 };#endif#if defined(__WIN32__) || defined(WIN) || defined(WIN32) || defined(Q_OS_WIN32) enum ForegroundColor { ForegroundLightBlack = 0 , ForegroundLightRed = 4 , ForegroundLightGreen = 2 , ForegroundLightYellow = 14 , ForegroundLightBlue = 1 , ForegroundLightPurple = 5 , ForegroundLightCyan = 11 , ForegroundLightWhite = 15 }; enum BackgroundColor { BackgroundBlack = 0 , BackgroundRed = 4 , BackgroundGreen = 2 , BackgroundYellow = 14 , BackgroundBlue = 1 , BackgroundPurple = 5 , BackgroundCyan = 11 , BackgroundWhite = 15 }; enum Colors { Default = 0 , Bright = +8 , Blink = 6 };#endif ColorConsoleAppender(QObject *pParent = 0); ColorConsoleAppender(Layout *pLayout, QObject *pParent = 0); ColorConsoleAppender(Layout *pLayout, const QString &rTarget, QObject *pParent = 0); /*! * Creates a ConsoleAppender with the layout \a pLayout, the target * value specified by the \a target constant and the parent * \a pParent. */ ColorConsoleAppender(Layout *pLayout, Target target, QObject *pParent = 0); void setColorMap(const ColorMap& map); protected: virtual void append(const LoggingEvent& rEvent); private: ColorMap colorMap; }; /************************************************************************** * Operators, Helper **************************************************************************/ /************************************************************************** * Inline **************************************************************************/} // namespace Log4Qt// Q_DECLARE_TYPEINFO(::ConsoleAppender, Q_COMPLEX_TYPE); // Use default#endif // _COLORCONSOLEAPPENDER_H
/****************************************************************************** * * package: log4qt * file: colorconsoleappender.cpp * created: March 2010 * author: Filonenko Michael * * * Copyright 2010 Filonenko Michael * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************//****************************************************************************** * Dependencies ******************************************************************************/#include "colorconsoleappender.h"#include <QtCore/QTextStream>#include <Log4Qt/loggingevent.h>#include <Log4Qt/layout.h>#include <Log4Qt/helpers/datetime.h>#if defined(__WIN32__) || defined(WIN) || defined(WIN32) || defined(Q_OS_WIN32) #include <windows.h>#endifnamespace Log4Qt{ /************************************************************************** * Declarations **************************************************************************/ /************************************************************************** * C helper functions **************************************************************************/ /************************************************************************** * Class implementation: ColorConsoleAppender **************************************************************************/ ColorConsoleAppender::ColorConsoleAppender(QObject *pParent) : ConsoleAppender(pParent) { } ColorConsoleAppender::ColorConsoleAppender(Layout *pLayout, QObject *pParent) : ConsoleAppender(pLayout, pParent) { } ColorConsoleAppender::ColorConsoleAppender(Layout *pLayout, const QString &rTarget, QObject *pParent) : ConsoleAppender(pLayout, rTarget, pParent) {} ColorConsoleAppender::ColorConsoleAppender(Layout *pLayout, Target target, QObject *pParent) : ConsoleAppender(pLayout, target, pParent) { } void ColorConsoleAppender::append(const LoggingEvent &rEvent) { // форматируем собщение QString message = layout()->format(rEvent); QRegExp rexp; // if we are in win* #if defined(__WIN32__) || defined(WIN) || defined(WIN32) || defined(Q_OS_WIN32) // Getting pointer to console HANDLE hConsole; if (target() == "STDOUT_TARGET") hConsole = GetStdHandle(STD_OUTPUT_HANDLE); else if (target() == "STDERR_TARGET") hConsole = GetStdHandle(STD_ERROR_HANDLE); // save colors CONSOLE_SCREEN_BUFFER_INFO cbi = {sizeof(cbi)}; GetConsoleScreenBufferInfo(hConsole,&cbi); ColorMap::ConstIterator colorMapIt = colorMap.constBegin(); ColorMap::ConstIterator colorMapEnd = colorMap.constEnd(); for(;colorMapIt != colorMapEnd; ++colorMapIt) { rexp.setPattern(colorMapIt.key()); if (rexp.exactMatch(message)) { // load colors SetConsoleTextAttribute(hConsole, colorMapIt.value().second*16 + colorMapIt.value().first); break; } } // print message to output console writer()->operator <<(message); // load old colors SetConsoleTextAttribute(hConsole, cbi.wAttributes); #endif // #if defined(__WIN32__) || defined(WIN) || defined(WIN32) || defined(Q_OS_WIN32) // if we are in *nix #if defined(linux) || defined(__linux) || defined(__linux__) || defined(Q_OS_UNIX) ColorMap::ConstIterator colorMapIt = colorMap.constBegin(); ColorMap::ConstIterator colorMapEnd = colorMap.constEnd(); for(;colorMapIt != colorMapEnd; ++colorMapIt) { rexp.setPattern(colorMapIt.key()); if (rexp.exactMatch(message)) { message.prepend(QString("\e[%1m").arg(QString::number(colorMapIt.value().first))); message.append("\e[0m"); break; } } writer()->operator <<(message); #endif //#if defined(linux) || defined(__linux) || defined(__linux__) || defined(Q_OS_UNIX) // обрабатываем ошибки, по умолчанию метод не реализован if (handleIoErrors()) return; if (immediateFlush()) { writer()->flush(); if (handleIoErrors()) return; } } void ColorConsoleAppender::setColorMap(const ColorMap& map) { colorMap = map; } /****************************************************************************** * Implementation: Operators, Helper ******************************************************************************/} // namespace Log4Qt
#include "colorconsoleappender.h".............................SimpleTimeLayout *timeLayout = new SimpleTimeLayout(); timeLayout->setName("TimeLayout"); timeLayout->activateOptions(); ColorConsoleAppender *colorAppender = new ColorConsoleAppender(timeLayout, ColorConsoleAppender::STDOUT_TARGET);colorAppender->setName("ColorAppender");colorAppender->activateOptions();ColorConsoleAppender::ColorMap colorMap;colorMap[".*Qt.*"] = QPair<int,int>(ColorConsoleAppender::ForegroundLightGreen, ColorConsoleAppender::BackgroundBlue);colorMap[".*INFO.*Logger - .*"] = QPair<int,int>(ColorConsoleAppender::ForegroundLightGreen, ColorConsoleAppender::BackgroundBlue);colorMap[".*WARN.*Logger.*"] = QPair<int,int>(ColorConsoleAppender::ForegroundLightRed, ColorConsoleAppender::BackgroundBlue);colorAppender->setColorMap(colorMap);LogManager::rootLogger()->addAppender(colorAppender);LogManager::rootLogger();qDebug() << "From qDebug() ";LogManager::logger("Logger")->info("First message");LogManager::logger("Logger")->warn("Warn message");LogManager::logger("SecondLogger")->warn("Second message");
[ 75%] Building CXX object CMakeFiles/main.dir/colorconsoleappender.cpp.objc:\mingw\bin\g++.exe -DQT_DLL -DQT_GUI_LIB -DQT_SQL_LIB -DQT_CORE_LIB -DQT_DEBUG -g -IC:\SABROG\colorappender -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include\QtGui -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include\QtSql -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include\QtCore -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include\Log4Qt -o CMakeFiles\main.dir\colorconsoleappender.cpp.obj -c C:\SABROG\colorappender\colorconsoleappender.cppC:\SABROG\colorappender\colorconsoleappender.cpp:63: warning: 'Log4Qt::ColorConsoleAppender::ColorConsoleAppender(QObject*)' redeclared without dllimport attribute: previous dllimport ignoredC:\SABROG\colorappender\colorconsoleappender.cpp:69: warning: 'Log4Qt::ColorConsoleAppender::ColorConsoleAppender(Log4Qt::Layout*, QObject*)' redeclared without dllimport attribute: previous dllimport ignoredC:\SABROG\colorappender\colorconsoleappender.cpp:76: warning: 'Log4Qt::ColorConsoleAppender::ColorConsoleAppender(Log4Qt::Layout*, const QString&, QObject*)' redeclared without dllimport attribute: previous dllimport ignoredC:\SABROG\colorappender\colorconsoleappender.cpp:83: warning: 'Log4Qt::ColorConsoleAppender::ColorConsoleAppender(Log4Qt::Layout*, Log4Qt::ConsoleAppender::Target, QObject*)' redeclared without dllimport attribute: previous dllimport ignoredC:\SABROG\colorappender\colorconsoleappender.cpp:91: warning: 'virtual void Log4Qt::ColorConsoleAppender::append(const Log4Qt::LoggingEvent&)' redeclared without dllimport attribute: previous dllimport ignoredC:\SABROG\colorappender\colorconsoleappender.cpp:163: warning: 'void Log4Qt::ColorConsoleAppender::setColorMap(const QHash<QString, QPair<int, int> >&)' redeclared without dllimport attribute: previous dllimport ignoredC:\CMake\bin\cmake.exe -E cmake_progress_report C:\SABROG\colorappender\CMakeFiles 3[100%] Building CXX object CMakeFiles/main.dir/moc_colorconsoleappender.cxx.objc:\mingw\bin\g++.exe -DQT_DLL -DQT_GUI_LIB -DQT_SQL_LIB -DQT_CORE_LIB -DQT_DEBUG -g -IC:\SABROG\colorappender -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include\QtGui -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include\QtSql -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include\QtCore -IC:\SABROG\qt-everywhere-opensource-src-4.6.2\include\Log4Qt -o CMakeFiles\main.dir\moc_colorconsoleappender.cxx.obj -c C:\SABROG\colorappender\moc_colorconsoleappender.cxxC:\SABROG\colorappender\moc_colorconsoleappender.cxx:76: warning: 'Log4Qt::ColorConsoleAppender::staticMetaObject' redeclared without dllimport attribute afterbeing referenced with dll linkageC:\SABROG\colorappender\moc_colorconsoleappender.cxx:85: warning: 'virtual const QMetaObject* Log4Qt::ColorConsoleAppender::metaObject() const' redeclared without dllimport attribute: previous dllimport ignoredC:\SABROG\colorappender\moc_colorconsoleappender.cxx:90: warning: 'virtual void* Log4Qt::ColorConsoleAppender::qt_metacast(const char*)' redeclared without dllimport attribute: previous dllimport ignoredC:\SABROG\colorappender\moc_colorconsoleappender.cxx:98: warning: 'virtual int Log4Qt::ColorConsoleAppender::qt_metacall(QMetaObject::Call, int, void**)' redeclared without dllimport attribute: previous dllimport ignoredLinking CXX executable main.exeC:\CMake\bin\cmake.exe -E cmake_link_script CMakeFiles\main.dir\link.txt --verbose=1c:\mingw\bin\g++.exe -g CMakeFiles\main.dir\main.cpp.obj CMakeFiles\main.dir\colorconsoleappender.cpp.obj CMakeFiles\main.dir\moc_colorconsoleappender.cxx.obj -o main.exe -Wl,--out-implib,libmain.dll.a -Wl,--major-image-version,0,--minor-image-version,0 C:\SABROG\qt-everywhere-opensource-src-4.6.2\lib\libQtGuid4.a C:\SABROG\qt-everywhere-opensource-src-4.6.2\lib\libQtSqld4.a C:\SABROG\qt-everywhere-opensource-src-4.6.2\lib\libQtCored4.a C:\SABROG\qt-everywhere-opensource-src-4.6.2\lib\liblog4qt.dll.a C:\SABROG\qt-everywhere-opensource-src-4.6.2\lib\libQtGui4.a C:\SABROG\qt-everywhere-opensource-src-4.6.2\lib\libQtSql4.a C:\SABROG\qt-everywhere-opensource-src-4.6.2\lib\libQtCore4.a -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32CMakeFiles\main.dir\main.cpp.obj: In function `main':C:/SABROG/colorappender/main.cpp:42: undefined reference to `_imp___ZN6Log4Qt20ColorConsoleAppenderC1EPNS_6LayoutENS_15ConsoleAppender6TargetEP7QObject'C:/SABROG/colorappender/main.cpp:53: undefined reference to `_imp___ZN6Log4Qt20ColorConsoleAppender11setColorMapERK5QHashI7QString5QPairIiiEE'CMakeFiles\main.dir\colorconsoleappender.cpp.obj: In function `ColorConsoleAppender':C:/SABROG/colorappender/colorconsoleappender.cpp:64: undefined reference to `_imp___ZTVN6Log4Qt20ColorConsoleAppenderE'C:/SABROG/colorappender/colorconsoleappender.cpp:64: undefined reference to `_imp___ZTVN6Log4Qt20ColorConsoleAppenderE'C:/SABROG/colorappender/colorconsoleappender.cpp:71: undefined reference to `_imp___ZTVN6Log4Qt20ColorConsoleAppenderE'C:/SABROG/colorappender/colorconsoleappender.cpp:71: undefined reference to `_imp___ZTVN6Log4Qt20ColorConsoleAppenderE'C:/SABROG/colorappender/colorconsoleappender.cpp:79: undefined reference to `_imp___ZTVN6Log4Qt20ColorConsoleAppenderE'CMakeFiles\main.dir\colorconsoleappender.cpp.obj:C:/SABROG/colorappender/colorconsoleappender.cpp:79: more undefined references to `_imp___ZTVN6Log4Qt20ColorConsoleAppenderE' followCMakeFiles\main.dir\moc_colorconsoleappender.cxx.obj:C:/SABROG/colorappender/moc_colorconsoleappender.cxx:87: undefined reference to `_imp___ZN6Log4Qt20ColorConsoleAppender16staticMetaObjectE'CMakeFiles\main.dir\moc_colorconsoleappender.cxx.obj: In function `_static_initialization_and_destruction_0':C:/SABROG/colorappender/moc_colorconsoleappender.cxx:79: undefined reference to`_imp___ZN6Log4Qt20ColorConsoleAppender16staticMetaObjectE'collect2: ld returned 1 exit statusmingw32-make[2]: *** [main.exe] Error 1mingw32-make[2]: Leaving directory `C:/SABROG/colorappender'mingw32-make[1]: *** [CMakeFiles/main.dir/all] Error 2mingw32-make[1]: Leaving directory `C:/SABROG/colorappender'mingw32-make: *** [all] Error 2
class LOG4QT_EXPORT ColorConsoleAppender : public ConsoleAppender
enum Value{/*! NULL_INT is used for no level has been specified */NULL_INT = 0,ALL_INT = 32,TRACE_INT = 64,DEBUG_INT = 96, // qDebug()INFO_INT = 128, WARN_INT = 150, // qWarning()ERROR_INT = 182, // qCritical()FATAL_INT = 214, // qFatal()OFF_INT = 255};
LogManager::logger("Logger")->setLevel(Level(Level::INFO_INT));
Log4Qt::LogManager::setTreshold(Level);
Log4Qt::*Appender::setThreshold(Level)
// фильтрLevelMatchFilter *filter = new LevelMatchFilter();// не принимать сообщения filter->setAcceptOnMatch(false);// с данным уровнемfilter->setLevelToMatch(Level(Level::DEBUG_INT));//filter->activateOptions(); // не требуется// добавляем фильтр объектуcolorAppender->addFilter(filter);
cmake -DQT_USE_QTSQL=TRUE -DCMAKE_BUILD_TYPE=Release -G"MinGW Makefiles"mingw32-make
set(CMAKE_BUILD_TYPE Debug)