最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Qt spdlog日志模塊的使用詳解

 更新時間:2025年04月12日 09:58:35   作者:sunriver2000  
在Qt應用程序開發(fā)中,良好的日志系統(tǒng)至關重要,本文將介紹如何使用spdlog 1.5.0創(chuàng)建滿足以下要求的日志系統(tǒng),感興趣的朋友一起看看吧

版本

spdlog版本:1.5.0

采用1.5.0版本主要基于以下考慮:兼容Qt5.9.X版本和兼容C++11。

spdlog 1.5.0下載地址:https://github.com/gabime/spdlog/releases/tag/v1.5.0

摘要

在Qt應用程序開發(fā)中,良好的日志系統(tǒng)至關重要。本文將介紹如何使用spdlog 1.5.0創(chuàng)建滿足以下要求的日志系統(tǒng):

  • 自定義文件名格式:yyyyMMdd_hhmmss_毫秒.log,不使用spdlog提供的日志輪轉功能

spdlog::sinks::rotating_file_sink_mt,采用自定義custom_rotating_file_sink;

  • 保留最近10個日志文件,每個日志文件大小限制為1MB。

例子

logmanager.h文件

#ifndef LOGMANAGER_H
#define LOGMANAGER_H
#include <QObject>
#include <memory>
#include <spdlog/spdlog.h>
class LogManager : public QObject
{
    Q_OBJECT
public:
    static LogManager& instance();
    void initialize(const QString& logDir = "logs",
                    const QString& appName = "app",
                    size_t maxFileSize = 1024 * 1024, // 1MB
                    size_t maxFiles = 10);
    void shutdown();
    template<typename... Args>
    static void log(spdlog::level::level_enum level, const QString& message, Args... args)
    {
        if (instance().m_logger)
        {
            instance().m_logger->log(level, message.toStdString().c_str(), args...);
        }
    }
    // 便捷方法
    static void trace(const QString& message)
    {
        log(spdlog::level::trace, message);
    }
    static void debug(const QString& message)
    {
        log(spdlog::level::debug, message);
    }
    static void info(const QString& message)
    {
        log(spdlog::level::info, message);
    }
    static void warn(const QString& message)
    {
        log(spdlog::level::warn, message);
    }
    static void error(const QString& message)
    {
        log(spdlog::level::err, message);
    }
    static void critical(const QString& message)
    {
        log(spdlog::level::critical, message);
    }
private:
    LogManager(QObject* parent = nullptr);
    ~LogManager();
    std::shared_ptr<spdlog::logger> createCustomLogger(const std::string& base_filename,
            size_t max_size,
            size_t max_files);
    std::shared_ptr<spdlog::logger> m_logger;
    std::atomic<bool> m_shuttingDown{false};
signals:
    void aboutToShutdown();
private slots:
    void onAboutToQuit();
};
// 日志宏定義
#define LOG_TRACE(...)    LogManager::log(spdlog::level::trace, __VA_ARGS__)
#define LOG_DEBUG(...)    LogManager::log(spdlog::level::debug, __VA_ARGS__)
#define LOG_INFO(...)     LogManager::log(spdlog::level::info, __VA_ARGS__)
#define LOG_WARN(...)     LogManager::log(spdlog::level::warn, __VA_ARGS__)
#define LOG_ERROR(...)    LogManager::log(spdlog::level::err, __VA_ARGS__)
#define LOG_CRITICAL(...) LogManager::log(spdlog::level::critical, __VA_ARGS__)
#endif // LOGMANAGER_H

logmanager.cpp文件

#include "logmanager.h"
#include <spdlog/sinks/base_sink.h>
#include <spdlog/details/file_helper.h>
#include <mutex>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <vector>
#include <algorithm>
#include <QDir>
#include <QFileInfo>
#include <QDateTime>
#include <QCoreApplication>
#include <csignal>
#include <QDebug>
// 替換 std::filesystem 的 C++11 兼容實現(xiàn)
namespace spdlog
{
    class custom_rotating_file_sink : public spdlog::sinks::base_sink<std::mutex>
    {
    public:
        custom_rotating_file_sink(const std::string& base_filename,
                                  std::size_t max_size,
                                  std::size_t max_files)
            : base_filename_(base_filename),
              max_size_(max_size),
              max_files_(max_files)
        {
            file_helper_.open(gen_filename());
        }
    protected:
        void sink_it_(const spdlog::details::log_msg& msg) override
        {
            spdlog::memory_buf_t formatted;
            formatter_->format(msg, formatted);
            if (file_helper_.size() + formatted.size() > max_size_)
            {
                rotate_();
            }
            file_helper_.write(formatted);
        }
        void flush_() override
        {
            file_helper_.flush();
        }
    private:
        std::string gen_filename()
        {
            QDateTime now = QDateTime::currentDateTime();
            QString timeStr = now.toString("yyyyMMddhhmmss");
            // 添加毫秒部分(3位)
            int ms = now.time().msec();
            timeStr += QString("_%1").arg(ms, 3, 10, QLatin1Char('0'));
            return base_filename_ + "_" + timeStr.toStdString() + ".log";
        }
        void rotate_()
        {
            file_helper_.close();
            cleanup_old_files();
            file_helper_.open(gen_filename());
        }
        void cleanup_old_files()
        {
            if (max_files_ == 0) return;
            QFileInfo base_info(QString::fromStdString(base_filename_));
            QDir dir = base_info.absoluteDir();
            QString base_name = base_info.fileName();
            QFileInfoList files = dir.entryInfoList(QStringList() << (base_name + "_*.log"),
                                                    QDir::Files, QDir::Time);
            // 刪除最舊的文件
            while (files.size() >= static_cast<int>(max_files_))
            {
                QFile::remove(files.last().absoluteFilePath());
                files.removeLast();
            }
        }
        std::string base_filename_;
        std::size_t max_size_;
        std::size_t max_files_;
        spdlog::details::file_helper file_helper_;
    };
} // namespace
LogManager::LogManager(QObject* parent) : QObject(parent)
{
    // 連接Qt退出信號
    connect(qApp, &QCoreApplication::aboutToQuit, this, &LogManager::onAboutToQuit);
    // 處理異常信號
    static auto handleSignal = [](int)
    {
        LogManager::instance().shutdown();
        std::_Exit(1);
    };
    std::signal(SIGTERM, handleSignal);
    std::signal(SIGSEGV, handleSignal);
    std::signal(SIGINT, handleSignal);
    std::signal(SIGABRT, handleSignal);
}
LogManager::~LogManager()
{
    shutdown();
}
LogManager& LogManager::instance()
{
    static LogManager instance;
    return instance;
}
void LogManager::initialize(const QString& logDir, const QString& appName, size_t maxFileSize, size_t maxFiles)
{
    if (m_logger)
    {
        return;
    }
    // 確保日志目錄存在
    QDir().mkpath(logDir);
    std::string base_filename = QDir(logDir).absoluteFilePath(appName).toStdString();
    m_logger = createCustomLogger(base_filename, maxFileSize, maxFiles);
    // 設置默認日志格式
    m_logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%l] [thread %t] %v");
    m_logger->set_level(spdlog::level::trace);
    spdlog::register_logger(m_logger);
    spdlog::set_default_logger(m_logger);
}
void LogManager::shutdown()
{
    /*
    if (m_logger)
    {
        spdlog::drop(m_logger->name());
        m_logger.reset();
    }
    spdlog::shutdown();
    */
    if (m_shuttingDown) return;
    m_shuttingDown = true;
    emit aboutToShutdown();
    try
    {
        if (m_logger)
        {
            m_logger->flush();
            spdlog::drop(m_logger->name());
        }
        spdlog::shutdown();
        m_logger.reset();
    }
    catch (const spdlog::spdlog_ex& ex)
    {
        qCritical() << "Log shutdown error:" << ex.what();
    }
}
void LogManager::onAboutToQuit()
{
    shutdown();
}
std::shared_ptr<spdlog::logger> LogManager::createCustomLogger(const std::string& base_filename,
        size_t max_size,
        size_t max_files)
{
    auto sink = std::make_shared<spdlog::custom_rotating_file_sink>(base_filename, max_size, max_files);
    auto logger = std::make_shared<spdlog::logger>("qt_logger", sink);
    return logger;
}

main.cpp文件

#include <QCoreApplication>
#include "logmanager.h"
#include <QTimer>
#include <QDebug>
int main(int argc, char* argv[])
{
    QCoreApplication a(argc, argv);
    // 初始化日志系統(tǒng)
    LogManager::instance().initialize("logs", "MyAppTest");
    // 連接關閉信號進行額外清理
    QObject::connect(&LogManager::instance(), &LogManager::aboutToShutdown, []()
    {
        LOG_INFO("Performing final cleanup before shutdown...");
    });
    for (int i = 0; i < 5000; ++i)
    {
        LOG_INFO("This is a test message to fill up the log file. Iteration: {}", i);
    }
    return a.exec();
}

到此這篇關于Qt spdlog日志模塊的使用的文章就介紹到這了,更多相關Qt spdlog日志模塊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • C++11原子操作詳解

    C++11原子操作詳解

    這篇文章主要為大家介紹了C++的原子操作,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-11-11
  • 基于Matlab實現(xiàn)BP神經網絡交通標志識別

    基于Matlab實現(xiàn)BP神經網絡交通標志識別

    道路交通標志用以禁止、警告、指示和限制道路使用者有秩序地使用道路,?保障出行安全.若能自動識別道路交通標志,?則將極大減少道路交通事故的發(fā)生。本文將介紹基于Matlab實現(xiàn)BP神經網絡交通標志識別,感興趣的可以學習一下
    2022-01-01
  • C/C++?QT實現(xiàn)解析JSON文件的示例代碼

    C/C++?QT實現(xiàn)解析JSON文件的示例代碼

    JSON是一種輕量級的數(shù)據交換格式,它是基于ECMAScript的一個子集,使用完全獨立于編程語言的文本格式來存儲和表示數(shù)據。這篇文章主要介紹了QT實現(xiàn)解析JSON文件的示例代碼,需要的可以參考一下
    2022-01-01
  • 詳解C語言中的memset()函數(shù)

    詳解C語言中的memset()函數(shù)

    這篇文章主要介紹了C語言中的memset()函數(shù),包括其與memcpy()函數(shù)的區(qū)別,需要的朋友可以參考下
    2015-08-08
  • C++中的類與對象深度解析

    C++中的類與對象深度解析

    這篇文章主要為大家詳細介紹了C++中的類與對象,使用數(shù)據庫,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • C++中的throw關鍵字詳解

    C++中的throw關鍵字詳解

    throw關鍵字是在C語言中用來拋出異常的關鍵字,它通常與try和catch一起使用,用于在程序中發(fā)生錯誤時進行異常處理,當遇到無法處理的錯誤情況時,我們可以使用throw關鍵字主動拋出異常,所以本文給大家詳細的介紹一下C++中的throw關鍵字,需要的朋友可以參考下
    2023-09-09
  • C++命名空間?缺省參數(shù)?const總結?引用總結?內聯(lián)函數(shù)?auto關鍵字詳解

    C++命名空間?缺省參數(shù)?const總結?引用總結?內聯(lián)函數(shù)?auto關鍵字詳解

    這篇文章主要介紹了C++命名空間?缺省參數(shù)?const總結?引用總結?內聯(lián)函數(shù)?auto關鍵字詳解的相關資料,需要的朋友可以參考下
    2023-01-01
  • 使用代碼驗證linux子進程與父進程的關系

    使用代碼驗證linux子進程與父進程的關系

    Linux下父進程可以使用fork 函數(shù)創(chuàng)建子進程,但是當父進程先退出后,子進程會不會也退出呢?通過下面這個小實驗,我們能夠很好的看出來
    2014-02-02
  • 一篇文章教你3分鐘如何發(fā)布Qt程序

    一篇文章教你3分鐘如何發(fā)布Qt程序

    這篇文章主要給大家介紹了關于教你3分鐘如何發(fā)布Qt程序的相關資料,文中通過實例代碼結束的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2020-08-08
  • C語言實現(xiàn)簡單彈球游戲

    C語言實現(xiàn)簡單彈球游戲

    這篇文章主要為大家詳細介紹了C語言實現(xiàn)簡單彈球游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-02-02

最新評論

绥化市| 岳阳市| 乐亭县| 自治县| 金塔县| 保亭| 高要市| 敦煌市| 民和| 石河子市| 纳雍县| 疏附县| 始兴县| 南丹县| 永春县| 江永县| 陆良县| 柘城县| 长阳| 梅河口市| 新干县| 蛟河市| 静宁县| 舞钢市| 平遥县| 长顺县| 沙坪坝区| 应城市| 保德县| 确山县| 珠海市| 荆门市| 唐河县| 黄浦区| 乾安县| 新乐市| 灌南县| 绥宁县| 宜兴市| 邵东县| 宁强县|