logoutput.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #ifndef LOGOUTPUT_H
  2. #define LOGOUTPUT_H
  3. /**
  4. * @brief QDebug的日志输出重定向到文件
  5. * @author wjp
  6. * @date 2024.3.8 modify by wjp
  7. *
  8. * */
  9. #include <QObject>
  10. #include <QtMessageHandler>
  11. #include <QDebug>
  12. #include <QFile>
  13. #include <QMutex>
  14. #include <QMutexLocker>
  15. #define LOG_MAXSIZE 5 * 1024 * 1024 //单个log文件最大值
  16. class LogOutput : public QObject
  17. {
  18. Q_OBJECT
  19. public:
  20. static LogOutput * getInstance();
  21. void install(); //安装信息处理函数
  22. void uninstall(); //卸载信息处理函数
  23. void deleteLog(); //删除过期日志
  24. protected:
  25. // 此函数用于注册
  26. static void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg);
  27. private:
  28. //将构造函数,拷贝构造,赋值运算符都定义为私有,不允许外部类操作
  29. explicit LogOutput(QObject *parent = nullptr); //构造函数
  30. ~LogOutput(); //析构
  31. LogOutput(const LogOutput &sig) = delete; //拷贝构造函数
  32. LogOutput& operator=(const LogOutput &sig) = delete ; //赋值运算符重载
  33. private:
  34. static LogOutput *ins; //私有静态对象
  35. static QMutex m_mutex;
  36. QString logPath;
  37. QFile m_curLogFile;
  38. QString m_curLogFileDate;// 当前日志所属日期,防止在午夜24点刚刚过,需要更换日志输出文件
  39. //信息处理函数(重写的myMessageHandler)
  40. /*功能说明:通过调试信息保存到日志文件
  41. *
  42. *参数说明:
  43. * msgType: 调试信息类型或级别(qdebug, qwarning, qfatal 。。。。)
  44. * context: 调试信息所处文本,可使用context.file和context.line获取文本所处行数及所处文件路径,以及使用context.function获取文本所处函数名
  45. * msg: 调试信息内容,自定义
  46. */
  47. void outPutMsg(QtMsgType msgType, const QMessageLogContext &context, const QString &msg);
  48. /*
  49. * 函数功能:
  50. * 1、根据调试信息以及日期,保存到相应的文件。
  51. * 2、在保存文件前需要判断文件大小是否大于自定义值,如果大于,便按照序号从小到大新建一个。
  52. */
  53. void saveLog(QString message);
  54. // 打开日志文件
  55. void openTheLogFile();
  56. };
  57. #endif // LOGOUTPUT_H