1、qt5-日志输出
代码已实际验证
需求(目的):生成log.txt日志文件,记录详细日志信息(包括等级、所在文件、所在行号、描述信息、产生时间等),以便于快速跟踪、定位。
//修改日志文件名为当前时间(精确到天)那么就自动会每天创建一个日志文件了。
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
static QMutex mutex;
mutex.lock();
QString text;
switch(type)
{
case QtDebugMsg:
text = QString("Debug:");
break;
case QtWarningMsg:
text = QString("Warning:");
break;
case QtCriticalMsg:
text = QString("Critical:");
break;
case QtFatalMsg:
text = QString("Fatal:");
}
QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
QString current_date = QString("(%1)").arg(current_date_time);
QString message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
QFile file("log.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream text_stream(&file);
text_stream << message << "\r\n";
file.flush();
file.close();
mutex.unlock();
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
//注册MessageHandler
qInstallMessageHandler(outputMessage);
//打印日志到文件中
qDebug("This is a debug message");
qWarning("This is a warning message");
qCritical("This is a critical message");
qFatal("This is a fatal message");
return app.exec();
}
2、zlog日志输出;注意要自己下载zlog库文件和头文件
bool InitLogFile(void)
{
int rc;
char szAppPath[MAX_PATH] = { 0 };
GetAppPath(szAppPath);
char szTime[32] = { 0 };
GetTimeEx2(szTime);
char szConfigPath[MAX_PATH] = { 0 };
sprintf_s(szConfigPath, "%s/zlog.conf", szAppPath);
char szLogFilePath[256] = { 0 };
sprintf_s(szLogFilePath, 256, "%s/log", szAppPath);
if (_access(szLogFilePath, 0) < 0)
_mkdir(szLogFilePath);
char szLogFilePathEx[256] = { 0 };
sprintf_s(szLogFilePathEx, 256, "%s/log/CameraCapturePro-%s.log", szAppPath, szTime);//输出日志文件的目录
FILE *pFile = fopen(szConfigPath, "wb");
if (pFile)
{
char *pWriteData = "[formats]\n";
fwrite(pWriteData, 1, strlen(pWriteData), pFile);
char *pWriteData2 = "my = \"%d|%V| %m%n\"\n";
fwrite(pWriteData2, 1, strlen(pWriteData2), pFile);
char *pWriteData3 = "[rules]\n";
fwrite(pWriteData3, 1, strlen(pWriteData3), pFile);
char *pWriteData4 = "my_cat.DEBUG >stdout;my\n";
fwrite(pWriteData4, 1, strlen(pWriteData4), pFile);
char szData[256] = { 0 };
sprintf_s(szData, 256, "my_cat.INFO \"%s\";my\n", szLogFilePathEx);
fwrite(szData, 1, strlen(szData), pFile);
fclose(pFile);
pFile = NULL;
}
rc = dzlog_init(szConfigPath, "my_cat");
if (rc)
{
OutputDebugString(L"dzlog_init failed \n");
return false;
}
return true;
}
后期就可以直接这样使用,最后会输出到文件中
dzlog_info("%s(%d) strCammeraName == "" ", __FUNCTION__, __LINE__);