源码引用log4Qt
参考网站: https://developer.aliyun.com/article/804837
1. 下载最新的源码1.5.1:https://github.com/MEONMedical/Log4Qt
下载下来解压后只需要留下:
a. build.pri
b. g++.pri
c. src 目录
2. 在自己的工程pro文件中引用log4qt子工程
#################日志库的引入######################## ##https://github.com/MEONMedical/Log4Qt include($$PWD/Log4Qt-1.5.1/src/log4qt/log4qt.pri) include($$PWD/Log4Qt-1.5.1/build.pri) include($$PWD/Log4Qt-1.5.1/g++.pri) QT += concurrent DEFINES += LOG4QT_LIBRARY DEFINES += LOG4QT_EXPORT INCLUDEPATH += Log4Qt-1.5.1/src/ INCLUDEPATH += Log4Qt-1.5.1/src/log4qt DEPENDPATH += Log4Qt-1.5.1/src/log4qt ###################################################
3. 修改一处编译错误Log4Qt-1.5.1/src/log4qt/dailyfileappender.cpp 添加头文件引用
#include <QStringBuilder>
4. 代码配置控制台日志输出:
#include "mainwindow.h" #include <QApplication> #include <QStandardPaths> #include <QDir> #include "logmanager.h" #include "propertyconfigurator.h" #include <consoleappender.h> #include <dailyrollingfileappender.h> #include <ttcclayout.h> #include <patternlayout.h> #include <QDebug> #include <QTextCodec> int main(int argc, char *argv[]) { QApplication a(argc, argv); Log4Qt::PropertyConfigurator::configure("log.conf"); Log4Qt::LogManager::setHandleQtMessages(true); Log4Qt::Logger *logger = Log4Qt::Logger::rootLogger(); Log4Qt::PatternLayout *layout = new Log4Qt::PatternLayout(); layout->setName("PatternLayout"); layout->setConversionPattern("%d{yyyy-MM-dd HH:mm:ss.zzz} [%p] %m%n"); layout->activateOptions(); // show log at the output window Log4Qt::ConsoleAppender *appender = new Log4Qt::ConsoleAppender(); appender->setName("ConsoleAppender"); appender->setLayout(layout); appender->setEncoding(QTextCodec::codecForName("UTF-8")); appender->setTarget(Log4Qt::ConsoleAppender::STDOUT_TARGET); // write log to stdout appender->setImmediateFlush(true); appender->setThreshold(Log4Qt::Level::ALL_INT); // output all log appender->activateOptions(); // add appender logger->addAppender(appender); logger->setLevel(Log4Qt::Level::ALL_INT); qDebug() << ("new log"); qInfo() << ("new log"); qWarning() << ("new log"); qCritical() << ("new log"); MainWindow w; w.show(); int ret = a.exec(); return ret; }
5. 配置文件log.conf配置日志输出到文件:
log4j.rootLogger=ALL, daily log4j.appender.daily=org.apache.log4j.DailyRollingFileAppender log4j.appender.daily.file=app.log log4j.appender.daily.appendFile=true log4j.appender.daily.datePattern=yyyy-MM-dd.log log4j.appender.daily.layout=org.apache.log4j.PatternLayout log4j.appender.daily.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.zzz} %p:%m%n
6. 在工程文件pro里添加将log.conf拷贝到输出目录
DISTFILES += \ log.conf logconf.commands = $(COPY_DIR) \"$$replace(PWD, /, \\)\log.conf\" \"$$replace(OUT_PWD, /, \\)\" first.depends += $(first) logconf export(first.depends) export(logconf.commands) QMAKE_EXTRA_TARGETS += first logconf
到此结束。