目次
I.はじめに
Qt プログラムがリリースされた後も、いくつかのデバッグ出力情報を確認する必要があります。一般に、出力情報はログ ファイルに書き込まれます。この記事では、カスタム関数を使用して、デバッグ、警告、クリティカル、致命的、および情報情報をログに自動的に出力します。 main 関数に 2 行のコードを追加するだけです。
また、ログファイルの出力過多やファイルサイズの過大化を防ぐため、ログファイルサイズが上限を超えないように設定されている場合など、ファイルが上限を超えた場合の自動上書き・書き換え機能を追加しました。 1M の場合、ログ ファイルのサイズが 1M を超える場合、以前の内容はクリアされ、保持されるだけになります。
2. ヘッダファイルのコード
ロッジ.h
#pragma once
#include <QMutex>
#include <QString>
#define LOG_FILE_NAME QString("/Log/") + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss") + QString(".log")
#define MAX_SIZE 1024 * 1024 //文件最大1M
static int s_logLevel = QtDebugMsg;
static QMutex s_logMutex;
static QString s_logPath;
void setLogPath(const QString& path);
void setLogLevel(int level);
void customLogMessageHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg);
3. ソースファイルコード
ロッジ.cpp
#include "loger.h"
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QTextStream>
#include <QDateTime>
void setLogPath(const QString& path)
{
s_logPath = path;
}
void setLogLevel(int level)
{
s_logLevel = level;
}
bool static ensureDirExist(const QString& dirPath)
{
QDir dir(dirPath);
if (dir.exists())
{
return true;
}
return dir.mkpath(dirPath);
}
void customLogMessageHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
if (type < s_logLevel)
{
return;
}
QString logInfo;
QString logTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss.zzz");
switch (type)
{
case QtDebugMsg:
logInfo = QString("%1 [Debug] %2").arg(logTime, msg);
break;
case QtWarningMsg:
logInfo = QString("%1 [Warning] %2").arg(logTime, msg);
break;
case QtCriticalMsg:
logInfo = QString("%1 [Critical] %2").arg(logTime, msg);
break;
case QtFatalMsg:
logInfo = QString("%1 [Fatal] %2").arg(logTime, msg);
abort();
case QtInfoMsg:
logInfo = QString("%1 [Info] %2").arg(logTime, msg);
break;
}
s_logMutex.lock();
QFile outFile(s_logPath);
QFileInfo fileInfo(outFile);
if (!ensureDirExist(fileInfo.absoluteDir().absolutePath()))
return;
if (outFile.size() > MAX_SIZE)
{
if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text))
return;
}
else
{
if (!outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
return;
}
QTextStream ts(&outFile);
ts << logInfo.toUtf8() << endl;
outFile.close();
s_logMutex.unlock();
}
4. 使用例
#include "loger.h"
int main(int argc, char *argv[])
{
setLogPath("./" + LOG_FILE_NAME);
qInstallMessageHandler(customLogMessageHandler);
//...其他代码.....
}
上記のコードをmain関数に追加して実行するだけで、qDebugやqInfo...などによる出力内容はコンソールには出力されず、すべてログファイルに出力されます。