#include "log.h" #pragma execution_character_set("utf-8") QString LogInfo::m_currtDate = QString(); QString LogInfo::m_folderPath = QString(); QFile* LogInfo::m_fileLog = NULL; const char* LogInfo::msgHead[] = { "Debug ", "Warning ", "Critical", "Fatal ", "Info " }; void LogInfo::recordLog(QString folderPath) { m_folderPath = folderPath; m_currtDate = QDateTime::currentDateTime().toString("yyyy-MM-dd"); logSysInit(m_folderPath); qInstallMessageHandler(&myMessageOutput); } void LogInfo::myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QString currtDate = QDateTime::currentDateTime().toString("yyyy-MM-dd"); if (currtDate != m_currtDate) { m_currtDate = currtDate; logSysInit(m_folderPath); } QString currentDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd"); if (m_fileLog) { QTextStream tWrite(m_fileLog); QString msgText = "%1 | %3 | %2\n"; msgText = msgText.arg(msgHead[type]).arg(msg).arg(currentDateTime); tWrite << msgText; } else { fprintf(stderr, "%s | %s | %s:%u, %s | %s\n", msgHead[type], currentDateTime.toLocal8Bit().constData(), context.file, context.line, context.function, msg.toLocal8Bit().constData()); } } void LogInfo::logSysInit(QString folderPath) { QString filePath = folderPath + "log-" + m_currtDate + ".log"; m_fileLog = new QFile(filePath); if (!m_fileLog->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) { return; } //初始化自定义日志处理函数myMessageOutput }