Qt开源日志模块QsLog使用方法

    科技2022-07-21  147

           C++常用的日志库有log4cplus, log4cpp等,关于log4cplus的使用可以看我的这篇博客【log4cplus的编译及使用方法】,Qt4也有一个比较老的日志库log4qt,介绍本篇Qt开源日志库QsLog的使用方法。

           QsLog github链接:https://github.com/victronenergy/QsLog

           打开QsLogSharedLibrary.pro工程就可以编译,可以生成dll

              在example下有QsLog的使用方法,双击log_example.pro即可加载所有example程序,如下图

                加载之后的项目结构

                QsLog日志级别

    enum Level {     TraceLevel = 0,     DebugLevel,     InfoLevel,     WarnLevel,     ErrorLevel,     FatalLevel,     OffLevel };

     提取QsLog的.h .lib .dll, 然后在VS中配置,示例代码

    #include "QsLog.h" #include "QsLogDest.h" #include "QsLogLevel.h" #include <QCoreApplication> #include <QDir> #include <iostream> #pragma comment(lib, "QsLog2.lib") using namespace QsLogging; void logFunction(const QString &message, QsLogging::Level level) {     std::cout << "From log function: " << qPrintable(message) << " " << static_cast<int>(level)         << std::endl; } int main(int argc, char *argv[]) {     QCoreApplication a(argc, argv);     //获取日志对象     Logger& logger = Logger::instance();     //设置日志等级     logger.setLoggingLevel(QsLogging::TraceLevel);     //设置日志生成路径     const QString sLogPath(QDir(a.applicationDirPath()).filePath("log.txt"));     // 2. add two destinations     DestinationPtr fileDestination(DestinationFactory::MakeFileDestination(         sLogPath, EnableLogRotation, MaxSizeBytes(512), MaxOldLogCount(2)));     DestinationPtr debugDestination(DestinationFactory::MakeDebugOutputDestination());     DestinationPtr functorDestination(DestinationFactory::MakeFunctorDestination(&logFunction));     logger.addDestination(debugDestination);     logger.addDestination(fileDestination);     logger.addDestination(functorDestination);     // 3. start logging     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!";     logger.setLoggingLevel(QsLogging::OffLevel);     for (int i = 0; i < 10; i++)      {         QLOG_ERROR() << QString::fromUtf8("this message should not be visible");     }     logger.setLoggingLevel(QsLogging::TraceLevel);     QLOG_DEBUG() << "Program ending";     QsLogging::Logger::destroyInstance();     return a.exec(); }

      运行结果

      QsLog的使用可以封装成类,在项目中使用。 

    Processed: 0.014, SQL: 8