QT4保存调试日志
windows下Qt程序發布后,所有調試日志都沒有了,有時候出錯不容易找出,所以做了個根據命令行傳入debug后,把調試日志寫到文件中的功能:
#include <QtGui/QApplication> #include "mainwindow.h" #include <QFile> #include <QTextStream> #include <QDebug> #include <QDateTime>static QString logfilepath = "debuglog.txt";void customMessageHandler(QtMsgType type, const char *msg) {QString txt;switch (type) {//調試信息提示case QtDebugMsg:txt = QString("Debug: %1").arg(msg);break;//一般的warning提示case QtWarningMsg:txt = QString("Warning: %1").arg(msg);break;//嚴重錯誤提示case QtCriticalMsg:txt = QString("Critical: %1").arg(msg);break;//致命錯誤提示case QtFatalMsg:txt = QString("Fatal: %1").arg(msg);abort();}QDateTime now = QDateTime::currentDateTime();QString filepath = "debuglog_" + now.toString("yyyyMMddhhmmss") + ".txt";QFile outFile(logfilepath);outFile.open(QIODevice::WriteOnly | QIODevice::Append);QTextStream ts(&outFile);ts << txt << endl; }int main(int argc, char *argv[]) {QApplication a(argc, argv);// 獲取命令行參數QStringList ql = QCoreApplication::arguments ();// 遍歷命令行參數,如果傳入debug 則把qDebug等輸出重定向到文件中foreach(QString tmp, ql){qDebug() << "parm: " << tmp << endl;if (tmp == "debug"){QDateTime now = QDateTime::currentDateTime();logfilepath = "debuglog_" + now.toString("yyyyMMddhhmmss") + ".txt";//先注冊自己的MsgHandleIrqInstallMsgHandler(customMessageHandler);}}//以后就可以像下面這樣直接打日志到文件中,而且日志也會包含時間信息qDebug("This is a debug message at thisisqt.com");qWarning("This is a warning message at thisisqt.com");qCritical("This is a critical message at thisisqt.com");//qFatal("This is a fatal message at thisisqt.com");MainWindow w;w.show();return a.exec(); } 參考:http://www.cppblog.com/lauer3912/archive/2011/04/10/143870.html
總結
- 上一篇: Linux查看CPU型号及内存频率及其它
- 下一篇: LINUX的“脏奶牛”