倘若是windows下,路径改为:const static QString log_path = QCoreApplication::applicationDirPath ();测试可用。
linux系统下程序如下:
#include <QDir>
#include <QFile>
#include <QMutex>
#include <QtDebug>
#include <QtGlobal>
#include <QDateTime>
void myMessageOutput(QtMsgType type, const char *msg)
{
const static QString log_path = QDir::homePath() + "/myProject/log/";
static QMutex mutex;
mutex.lock();
QString text;
switch(type)
{
case QtDebugMsg:
text = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd")).arg(QString("Debug:")).arg(msg);
fprintf(stderr, "%s\n", msg);
break;
case QtWarningMsg:
text = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd")).arg(QString("Warning:")).arg(msg);
fprintf(stderr, "%s\n", msg);
break;
case QtCriticalMsg:
text = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd")).arg(QString("Critical:")).arg(msg);
fprintf(stderr, "%s\n", msg);
break;
case QtFatalMsg:
text = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd")).arg(QString("Fatal:")).arg(msg);
fprintf(stderr, "%s\n", msg);
abort();
break;
default:
break;
}
if (!text.isEmpty())
{
QString message = text;
QString log_file = QDateTime::currentDateTime().toString("yyyy-MM-dd") + "log.txt";
QFile file(log_path+ "/" +log_file);
if (!file.open(QIODevice::WriteOnly | QIODevice::Append))
{
fprintf(stderr, "%s\n", file.errorString().toStdString().c_str());
}
QTextStream ts(&file);
ts << message << endl;
file.flush();
file.close();
}
mutex.unlock();
}
int main(int argc, char *argv[])
{
//注册MsgHandler
qInstallMsgHandler(myMessageOutput);
QCoreApplication a(argc, argv);
//在需要打印出错信息的位置,按照错误信息的严重程度选择以下四种打印方式
qDebug("This is a debug message");
qWarning("This is a warning message");
qCritical("This is a critical message");
qFatal("This is a fatal message"); //windows下测试,使用这条程序会崩。
}
注意:
1)main中添加了qInstallMsgHandler(myMessageOutput);这条代码后,打印信息都会写到日志文件中了,并不会在终端中输出。因此,在调试的过程中可以先把这条信息屏蔽掉;
2) windows下测试,使用qFatal("This is a fatal message");时,程序会直接崩掉,所以,日志输出时不要用这条输出信息?