Reputation: 1122
I have a QtQuick/QML application running on a remote embedded target system. I have syslog configured on the target to direct log messages to a log server.
Now, I'd like to have the standard out and err console output also redirected to the local syslog so I can get all of my application feedback in one place.
Is there a "best practices" way to do this? Or will I want/need to obtain all this output within my application and log it through "normal channels"?
Edit: I can do this with bash redirection per this question/answer, but I would still prefer to do it from within the application, if possible.
Edit: I suppose I should make more clear that I'm not asking about how to get the messages that go through the application's logging API to go to syslog. If there are errors in my QtQuick QML, the Qt runtime generates error and warning messages that get printed to stderr. It's those messages that I want to get redirected to the system logging facility.
Upvotes: 1
Views: 1507
Reputation: 498
Since Qt 5.6 there is more straightforward option:
You can use qDebug()
, qInfo()
, qWarning()
and other Qt logging functions and they will pass their output to syslog.
Since Qt 5.6 the support for syslog is built-in: you need to
-syslog
in the Qt configure script (if you use buildroot, just add BR2_PACKAGE_QT5BASE_SYSLOG=y
)#include <QtGlobal>
qputenv("QT_LOGGING_TO_CONSOLE", QByteArray("0"));
to your program, so the output goes to syslog instead of consoleExample:
#include <QtGlobal>
#include <QByteArray>
int main()
{
// Needed to enable logging to syslog or journald.
qputenv("QT_LOGGING_TO_CONSOLE", QByteArray("0"));
// Send some messages, which should go to syslog/journald.
qDebug("qDebug");
qInfo("qInfo");
qWarning("qWarning");
}
Source:
Upvotes: 0
Reputation: 8698
Mind that all Qt and QML log will be streamed through this channel.
#include <syslog.h>
#include <QtGlobal>
/// Consider https://linux.die.net/man/3/openlog
/// Qt Log Message handler
static void qtLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray loc = msg.toUtf8();
switch (type) {
case QtDebugMsg:
syslog (LOG_DEBUG, "%s", loc.constData());
break;
case QtInfoMsg:
syslog (LOG_INFO, "%s", loc.constData());
break;
case QtWarningMsg:
syslog (LOG_WARNING, "%s", loc.constData());
break;
case QtCriticalMsg:
syslog (LOG_CRIT, "%s", loc.constData());
break;
case QtFatalMsg:
syslog (LOG_ERR, "%s", loc.constData());
break;
}
}
int main(int argc, char* argv[])
{
/// When starting the process
openlog("MY_APP_LOG", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_USER);
/// Install Qt Log Message Handler in main.cpp
qInstallMessageHandler(qtLogMessageHandler);
/// The Qt app GUI start can be
QApplication app(argc, argv);
app.exec();
/// When quitting the process
closelog();
}
Upvotes: 3