This repository has been archived on 2026-04-08. You can view files and clone it, but cannot push or open issues or pull requests.
SP713_CPP_QT/drivers/log/logHandler.cpp
2025-07-17 13:10:47 +08:00

57 lines
1.7 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "LogHandler.h"
#include <QDateTime>
#include <QMetaObject>
#include <iostream>
// 初始化静态成员
LogHandler* LogHandler::s_instance = nullptr;
QMutex LogHandler::s_mutex;
LogHandler::LogHandler(QObject *parent) : QObject(parent), m_logWidget(nullptr) {
}
// 获取单例实例(线程安全)
LogHandler* LogHandler::log_instance() {
if (!s_instance) {
QMutexLocker locker(&s_mutex);
if (!s_instance) {
s_instance = new LogHandler();
}
}
return s_instance;
}
// 初始化日志输出目标
void LogHandler::log_init(QPlainTextEdit *logWidget) {
LogHandler *handler = log_instance();
handler->m_logWidget = logWidget;
qInstallMessageHandler(log_handleMessage); // 注册消息处理器
}
// 静态消息处理函数
void LogHandler::log_handleMessage(QtMsgType type, const QMessageLogContext &, const QString &msg) {
LogHandler *handler = log_instance();
if (!handler) return;
// 格式化日志消息(添加时间和日志级别)
QString timestamp = QDateTime::currentDateTime().toString("[hh:mm:ss.zzz] ");
QString level;
switch (type) {
case QtDebugMsg: level = "DEBUG"; break;
case QtInfoMsg: level = "INFO"; break;
case QtWarningMsg: level = "WARN"; break;
case QtCriticalMsg: level = "ERROR"; break;
case QtFatalMsg: level = "FATAL"; break;
}
QString formattedMsg = QString("%1[%2] %3").arg(timestamp, level, msg);
// 如果有UI组件通过信号槽更新线程安全
if (handler->m_logWidget) {
emit handler->log_messageLogged(formattedMsg);
} else {
// 无UI时输出到控制台
std::cerr << formattedMsg.toStdString() << std::endl;
}
}