1. 程式人生 > >Qt 實現 Logger 日誌----輕量級開源庫QsLog的使用

Qt 實現 Logger 日誌----輕量級開源庫QsLog的使用

github的下載地址:https://github.com/victronenergy/QsLog
下載後,解壓到非中文目錄,用qt creator開啟(qt5.8.0,windows平臺上,親測可用),如圖:
在這裡插入圖片描述
編譯:
(1)編譯QsLogSharedLibrary,在windows平臺上,會生成QsLog2.lib和QsLog2.dll
(2)編譯官方給的demo,log_example_shared,將生成的,複製到build-QsLogExample目錄中。
(3)編譯log_example。
執行demo:
在build-QsLogExample資料夾中,雙擊log_example.exe,即刻看到生成是log。或者在qt createor中執行該工程,可以看到除錯臺中輸出的資訊。

將編譯的QsLog2.lib和QsLog2.dll應用到我們的專案中。
新建一個MyQsLogDemo工程,將標頭檔案新增到工程搜尋目錄中:

INCLUDEPATH += $$PWD/include/QsLog/QsLog.h \
               $$PWD/include/QsLog/QsLogDest.h \
               $$PWD/include/QsLog/QsLogDestConsole.h \
               $$PWD/include/QsLog/QsLogDestFile.h \
               $$PWD/include/QsLog/QsLogDestFunctor.h \
               $$PWD/include/QsLog/QsLogDisableForThisFile.h \
               $$PWD/include/QsLog/QsLogLevel.h

新增lib庫:

LIBS += $$PWD/lib/QsLog2.lib

在main.cpp檔案中新增測試程式碼:

#include "widget.h"

#include "include/QsLog/QsLog.h"
#include "include/QsLog/QsLogDest.h"

#include <QApplication>
#include <QDir>
#include <iostream>

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[]) { QApplication a(argc, argv); Widget w; w.show(); using namespace QsLogging; // 1. init the logging mechanism 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 < 10000000;++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(); }