前言
最近项目中需要用到日志库。上一次项目中用到了log4qt库,这个库有个麻烦的点是要配置config文件,所以这次切换到了QsLog。用了后这个库的感受是,比较轻量级,嘎嘎好用,推荐一波。
下载QsLog库
https://github.com/victronenergy/QsLog
使用
源码引入
我是放在3rdparty目录下的,所以在主工程pro中新增代码:
INCLUDEPATH += $$PWD/../3rdparty/QsLog
include($$PWD/../3rdparty/QsLog/QsLog.pri)
![](https://img-blog.csdnimg.cn/img_convert/29fd8aead9ebd19c7fc5dc5f45f9f0c5.png)
初始化
简单配置下初始化参数,主要配置 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. 添加两个destination
QsLogging::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文件
![](https://img-blog.csdnimg.cn/img_convert/fb4a4922f8ea6a798fd745149b47ccf4.png)
log.txt中的数据
![](https://img-blog.csdnimg.cn/img_convert/2e225ee7905dba726a8acd09b31e1748.png)