Last active
July 20, 2023 11:52
-
-
Save polovik/10714049 to your computer and use it in GitHub Desktop.
Log to file or log to output panel in QtCreator for Qt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QtDebug> | |
#include <QTranslator> | |
#include <QTextCodec> | |
#include <QLocale> | |
#include <QTime> | |
#include <QDir> | |
static QTextCodec *logCodec = NULL; | |
static FILE *logStream = NULL; | |
QString g_logFilePath = ""; | |
/** @brief For convenient parsing log files, messages have to be formatted as: | |
* level: message (`placeInSource`) | |
* where: | |
* level - Debug, Warning, Critical, Fatal | |
* message - log message | |
* placeInSource - point, where message was emited in format: (`filename:line, function_signature`) | |
*/ | |
void logging(QtMsgType type, const QMessageLogContext &context, const QString &msg) | |
{ | |
QByteArray localMsg = logCodec->fromUnicode(msg); | |
QString fileName(context.file); | |
fileName.remove(0, fileName.lastIndexOf("\\") + 1); | |
fileName.remove(0, fileName.lastIndexOf("/") + 1); | |
QByteArray file = logCodec->fromUnicode(fileName); | |
QTime time = QTime::currentTime(); | |
QString formatedTime = time.toString("hh:mm:ss.zzz"); | |
fprintf(logStream, "%s ", qPrintable(formatedTime)); | |
switch (type) { | |
case QtDebugMsg: | |
fprintf(logStream, "Debug: %s (`%s:%u, %s`)\n", localMsg.constData(), file.constData(), context.line, context.function); | |
break; | |
case QtWarningMsg: | |
fprintf(logStream, "Warning: %s (`%s:%u, %s`)\n", localMsg.constData(), file.constData(), context.line, context.function); | |
break; | |
case QtCriticalMsg: | |
fprintf(logStream, "Critical: %s (`%s:%u, %s`)\n", localMsg.constData(), file.constData(), context.line, context.function); | |
break; | |
case QtFatalMsg: | |
fprintf(logStream, "Fatal: %s (`%s:%u, %s`)\n", localMsg.constData(), file.constData(), context.line, context.function); | |
abort(); | |
break; | |
} | |
fflush(logStream); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
// Configure and redirect log output to stderr or in text file | |
QByteArray envVar = qgetenv("QTDIR"); // this variable is only set when run application in QtCreator | |
if (envVar.isEmpty()) { | |
g_logFilePath = QDir::tempPath() + QDir::separator() + "log_service.txt"; | |
logStream = _wfopen(g_logFilePath.toStdWString().c_str(), L"w"); | |
} else { | |
logStream = stderr; | |
} | |
logCodec = QTextCodec::codecForName("Windows-1251"); | |
qInstallMessageHandler(logging); | |
qDebug() << "Start service"; | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment