1.定义了一个自定义的消息处理函数 customMessageHandler,用于处理 Qt 的日志消息。它接受消息类型(type)、消息上下文(context)和消息内容(msg)作为参数。
2.在 customMessageHandler 函数中,首先获取日志文件的路径,并创建或打开一个文件流对象 stream。
3.使用 QTextStream 将时间戳、日志消息以及额外的换行符写入日志文件。
4.然后,使用 QTextStream 将时间戳、日志消息写入控制台。
5.最后,调用 file.flush() 确保日志内容被写入文件。
6.在日志类的 initialize 方法中,通过调用qInstallMessageHandler 函数将自定义的消息处理函数设置为当前应用程序的消息处理程序。
代码如下
void customMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
QString logFilePath = QCoreApplication::applicationDirPath() + "/log.txt"; // 日志文件路径
static QFile file(logFilePath);
if (!file.isOpen()) {
if (!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
return;
}
QTextStream stream(&file);
stream << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz ") // 添加时间戳
<< qFormatLogMessage(type, context, msg) << endl << endl;
// 同时输出到控制台
QTextStream consoleStream(stdout);
consoleStream << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz ")
<< qFormatLogMessage(type, context, msg) << endl;
file.flush(); // 确保日志内容写入文件
}
void Log::initialize()
{
// 重新将 qDebug 输出重定向到文件和控制台
qInstallMessageHandler(customMessageHandler);
}