Qt日志库QsLog使用教程

前言

最近项目中需要用到日志库。上一次项目中用到了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. 添加两个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文件

log.txt中的数据

 

 

版权声明:
作者:小何
链接:https://ligo100.cn/houduanjishu/qt/645.html
来源:小何博客
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>
文章目录
关闭
目 录