1 新建项目T33Debug
main.cpp |
#include <QDebug> #include <QFile> #include <QMutex> //文件锁
void MyMessageHandler(QtMsgType type,const QMessageLogContext &context,const QString &msg) { //使用一个文件锁,当在写文件的时候,要等写完之后才能继续执行 static QMutex mutex; mutex.lock();
QString strContext; //在QMessageLogContext中保存的有文件名,文件行号,方法等信息 strContext.sprintf("%s %d %s:\r\n\t",context.file,context.line,context.function);
QString output = strContext + msg + "\r\n";
if(type == QtDebugMsg) { QFile file("debug.log"); file.open(QFile::WriteOnly | QFile::Append); file.write(output.toUtf8()); file.close(); } if(type == QtWarningMsg) { QFile file("warning.log"); file.open(QFile::WriteOnly|QFile::Append); file.write(output.toUtf8()); file.close(); } if(type == QtCriticalMsg) { QFile file("critical.log"); file.open(QFile::WriteOnly | QFile::Append); file.write(output.toUtf8()); file.close(); } if(type == QtFatalMsg) { QFile file("fatal.log"); file.open(QFile::WriteOnly | QFile::Append); file.write(output.toUtf8()); file.close(); }
printf("%s",output.toUtf8().data()); mutex.unlock(); }
int main() { //To suppress the output at runtime, install your own message //handler with qInstallMessageHandler(). qInstallMessageHandler(MyMessageHandler); qDebug() << "output debug"; qDebug("%s,%d","outputdebug",1);
qWarning() << "warning"; qCritical() << "cridical"; //可以放开下面的一句,然后发现目录也有相应的fatal.log文件 //qFatal("fatal info"); } |
运行结果: 输入目录(E:\QT\build-T33Debug-Desktop_Qt_5_3_MinGW_32bit-Debug)的文件如下: |