Qt 中基于 spdlog 的高效日志管理方案

发布于:2025-05-08 ⋅ 阅读:(24) ⋅ 点赞:(0)

在开发 Qt 应用程序时,日志记录是一项至关重要的功能,它能帮助我们追踪程序的运行状态、定位错误和分析性能。本文将介绍如何在 Qt 项目中集成 spdlog 库,并封装一个简单易用的日志管理类 QtLogger,实现高效的日志记录和管理。

为什么选择 spdlog?

spdlog 是一个快速、头文件仅有的 C++ 日志库,具有丰富的功能和良好的性能。它支持多种日志记录方式,如同步日志、异步日志,还提供了强大的日志格式化和日志文件滚动功能。在 Qt 项目中使用 spdlog,可以方便地实现高质量的日志管理。

QtLogger 类的设计与实现

我们设计了一个名为 QtLogger 的单例类,用于统一管理 Qt 应用中的日志记录。下面是该类的详细实现:

头文件定义

#ifndef LOGGERMANAGER_H
#define LOGGERMANAGER_H

#pragma once
#include <QObject>
#include <QString>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/rotating_file_sink.h>
#include <memory>
#include <spdlog/async.h>

class QtLogger : public QObject {
   
    Q_OBJECT
public:
    static void initialize(const QString& logDir = "logs",
                          qint64 maxSizeMB = 10,
                          int maxFiles = 2);

    static QtLogger* instance();

    // Qt风格日志接口
    Q_INVOKABLE static void debug(const QString& message);
    Q_INVOKABLE static void info(const QString& message);
    Q_INVOKABLE static void warning(const QString& message);
    Q_INVOKABLE static void error(const QString& message);

    // 带格式化的日志
    template<typename... Args>
    static void logDebug(const QString& fmt, Args&&... args) {
   
        instance()->logger_->debug(fmt.toStdString(), std::forward<Args>(args)...);
    }

signals:
    void logMessage(QtMsgType type, const QString& message);

private:
    explicit QtLogger(QObject* parent = nullptr);
    ~QtLogger();

    static QtLogger* instance_;
    std::shared_ptr<spdlog::logger> logger_

网站公告

今日签到

点亮在社区的每一天
去签到