Qt原生线程打印日志
#ifndef LOGMSGPRINT_H
#define LOGMSGPRINT_H
#include <QObject>
#include <QQueue>
#include <QMutex>
#include <QThread>
#include <QDebug>
#include <QDir>
#include <QDate>
class LogMsgPrint{
public:
static LogMsgPrint *Inst()
{
static LogMsgPrint LogMsgPrintInstance = {};
return(&LogMsgPrintInstance);
}
public:
bool m_logging = false;
QMutex m_mutexLog = {};
QQueue<QString> m_queueLog = {}; // 日志队列
QThread * m_pLogThread = NULL;
public:
LogMsgPrint()
{
if(m_logging == false)
{
m_logging = true;
if(m_pLogThread == NULL)
{
m_pLogThread = QThread::create(&LogFun);
}
}
};
static void LogFun()
{
LogMsgPrint *thiz = LogMsgPrint::Inst();
if(thiz != NULL)
{
while(thiz->m_logging == true)
{
if(thiz->m_queueLog.empty() == true)
{
QThread::msleep(100);
continue;
}
thiz->m_mutexLog.lock();
QString text = thiz->m_queueLog.front();
thiz->m_queueLog.dequeue();
thiz->m_mutexLog.unlock();
thiz->WriteToLogFlie(text);
}
}
};
void InsertQueue(QString m_txt)
{
m_mutexLog.lock();
m_queueLog.enqueue(m_txt);
m_mutexLog.unlock();
}
void SetPathName(const QString &strPathName)
{
QDir dir(strPathName);
if(!dir.exists())
{
dir.mkpath(strPathName);
}
m_strPathName = strPathName;
if(m_pLogThread != NULL)
{
m_pLogThread->start();
}
}
private:
QString m_strPathName = QString();
QString m_strFileName = QString();
QFile m_outFile={};
QTextStream m_ts = {};
void WriteToLogFlie(const QString &strMsg)
{
QString strFileName = QString("/%1.log").arg(QDate::currentDate().toString("yyyy-MM-dd"));
if(m_strFileName.compare(strFileName) != 0)
{
if(m_outFile.isOpen() == true)
{
m_outFile.close();
}
m_strFileName = strFileName;
m_outFile.setFileName(m_strPathName + strFileName);
m_outFile.open(QIODevice::WriteOnly | QIODevice::Append);
m_ts.setDevice(&m_outFile);
}
if(m_outFile.isOpen() == true)
{
m_ts << strMsg << Qt::endl;
m_outFile.flush();
}
}
public:
void ClearLogFile()
{
QDir dir(m_strPathName);
if( ! dir.exists() )
{
bool isok = dir.mkpath(".");
if(!isok)
{
//TODO:报错
return;
}
}
foreach(QFileInfo username , dir.entryInfoList(QDir::NoDotAndDotDot|QDir::Dirs))
{
QDir userdir(username.absolutePath()+"/"+username.fileName());
userdir.setNameFilters({"*.log"});
foreach(QFileInfo logfile, userdir.entryInfoList(QDir::Files | QDir::NoSymLinks))
{
QString str = logfile.fileName();
QStringList listMsg = str.split("-");
if(listMsg.count() == 3)
{
int year, month,day;
year = listMsg[0].toInt();
month = listMsg[1].toInt();
day = listMsg[2].split(".")[0].toInt();
if(QDate(year,month,day).startOfDay().addMonths(3).toTime_t() < QDateTime::currentDateTimeUtc().toTime_t())
{
QFile(userdir.absoluteFilePath(str)).remove();
}
}
}
}
}
};
#endif // LOGMSGPRINT_H
main.cpp内容:
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
void customMessageHandler(QtMsgType, const QMessageLogContext &, const QString &strMsg)
{
#else
void customMessageHandler(QtMsgType, const char *strMsg)
{
#endif
LogMsgPrint::Inst()->InsertQueue(QString("[%1]:%2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss zzz"), strMsg));
}
int main(int argc, char *argv[])
{
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)TopLevelExceptionFilter);
if(!IsKeyboardConnection())
{
qputenv("QT_IM_MODULE", "tgtsml");
}
QtSingleApplication a("QtSingleApplication_Test_id",argc, argv);
if(a.isRunning())//判断实例是否已经运行
{
QMessageBox::warning(NULL, "提示!", "该程序正在运行中!");
QString str = "该程序正在运行中!当前时间为:" + QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss");
a.sendMessage(str, 1000); //1s后激活前个实例
return EXIT_SUCCESS;
}
m_strApplicationPath = a.applicationDirPath() + "/Log";
LogMsgPrint::Inst()->SetPathName(m_strApplicationPath);
#ifdef HW_FOR_RELEASE
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
qInstallMessageHandler(customMessageHandler);
#else
qInstallMsgHandler(customMessageHandler);
#endif
#endif
qInstallMessageHandler(customMessageHandler);
App()->show();
OutputControl * pOutputControl = new OutputControl();
a.installEventFilter(pOutputControl);
LogMsgPrint::Inst()->ClearLogFile();
return a.exec();
}