Qt中提供 Qt::qDebug()、Qt::qWarning()、Qt::qCritical()、Qt::qFatal()进行log输出。如果要输出log.txt文件,需要配合调用Qt::qInstallMessageHandler()函数。但功能并不强大。这里推荐一个第三方Qt日志库:QsLog 。
github: https://github.com/victronenergy/QsLog
下面讲解如何使用:
-
在github上下载源码,可以制作成lib库形式,也可以以源文件方式加入到项目中,这里直接复制源码加入到项目中。
-
编写测试代码:
test.cpp#include "../QsLog/QsLog.h" #include "../QsLog/QsLogDest.h" void init() { // 初始化日志机制 Logger& logger = Logger::instance(); // 设置日志等级 logger.setLoggingLevel(QsLogging::TraceLevel); // 添加文件为目的地 const QString sLogPath(QDir(QApplication::applicationDirPath()).filePath("log.txt")); DestinationPtr fileDestination(DestinationFactory::MakeFileDestination( sLogPath, EnableLogRotation, MaxSizeBytes(1024 * 1024), MaxOldLogCount(2))); // //MaxSizeBytes 代表log文件最大大小,MaxOldLogCount表示旧log文件个数 logger.addDestination(fileDestination); // 打印日志 QLOG_TRACE() << "1-trace msg"; QLOG_DEBUG() << "2-debug msg"; QLOG_INFO() << "3-info msg"; QLOG_WARN() << "4-warn msg"; QLOG_ERROR() << "5-error msg"; QLOG_FATAL() << "6-fatal msg"; for(int i = 0; i < 1000000; ++i) { QLOG_ERROR() << QString::number(i) + QString::fromUtf8(" this message should not be visible"); } QsLogging::Logger::destroyInstance(); }
-
输出结果:
三个log.txt文件,一个当前的,两个以前的。
具体的日志信息: