前言
最近项目中需要用到日志库。上一次项目中用到了log4qt库,这个库有个麻烦的点是要配置config文件,所以这次切换到了QsLog。用了后这个库的感受是,比较轻量级,嘎嘎好用,推荐一波。
下载QsLog库
https://github.com/victronenergy/QsLog
使用
源码引入
我是放在3rdparty目录下的,所以在主工程pro中新增代码:
INCLUDEPATH += $$PWD/../3rdparty/QsLog
include($$PWD/../3rdparty/QsLog/QsLog.pri)
初始化
简单配置下初始化参数,主要配置 MaxSizeBytes和MaxOldLogCount,其他的直接用就好了。必须的头文件:#include "./QsLog.h"
#include "./QsLog.h"
bool logConfig()
{QsLogging::Logger& logger = QsLogging::Logger::instance();logger.setLoggingLevel(QsLogging::TraceLevel);//设置log位置为exe所在目录const QString sLogPath(QDir(QCoreApplication::applicationDirPath()).filePath("log.txt"));// 2. 添加两个destinationQsLogging::DestinationPtr fileDestination(QsLogging::DestinationFactory::MakeFileDestination(sLogPath, QsLogging::EnableLogRotation, QsLogging::MaxSizeBytes(512000), QsLogging::MaxOldLogCount(5)));QsLogging::DestinationPtr debugDestination(QsLogging::DestinationFactory::MakeDebugOutputDestination());//DestinationPtr functorDestination(DestinationFactory::MakeFunctorDestination(&logFunction));//这样和槽函数连接//DestinationPtr sigsSlotDestination(DestinationFactory::MakeFunctorDestination(this, SLOT(logSlot(QString,int))));logger.addDestination(debugDestination);logger.addDestination(fileDestination);//logger.addDestination(functorDestination);//logger.addDestination(sigsSlotDestination);return true;
}
使用
QLOG_INFO() << "Program started";QLOG_INFO() << "Built with Qt" << QT_VERSION_STR << "running on" << qVersion();QLOG_TRACE() << "Here's a" << QString::fromUtf8("trace") << "message";QLOG_DEBUG() << "Here's a" << static_cast<int>(QsLogging::DebugLevel) << "message";QLOG_WARN() << "Uh-oh!";qDebug() << "This message won't be picked up by the logger";QLOG_ERROR() << "An error has occurred";qWarning() << "Neither will this one";QLOG_FATAL() << "Fatal error!";
最后效果
切割log文件
log.txt中的数据
原文地址
Qt日志库QsLog使用教程-小何博客