我正在使用Qt 5.7开发一个项目,并且遇到LtLogger
类的问题:
#ifndef LTLOGGER_H
#define LTLOGGER_H
#include <QObject>
#include <QScopedPointer>
#include <QFile>
#include <QMutexLocker>
#include <QDateTime>
#include <QThread>
#include <QMutex>
#include <QApplication>
#include <utils/config.h>
#include "ltlogsocket.h"
/**
* @brief Log backup folder name
*/
static const QString LT_LOG_BACKUP_FOLDER_NAME="logBackup";
#ifdef PLATFORM_NEXO360
/**
* @brief Log file name
*/
static const QString LT_LOG_FILE_NAME="dc.log";
#endif
/**
* @class Logger class
*/
class LtLogger : public QObject
{
Q_OBJECT
public:
/**
* @brief Constructor
* @param parent
*/
explicit LtLogger(QObject* const parent,
Config* const ltConfig);
/**
* @brief Message handler method
* @param type
* @param ctx
* @param msg
*/
void ltMessageHandler(QtMsgType type,
const QMessageLogContext& ctx,
const QString& msg);
signals:
public slots:
};
#endif // LTLOGGER_H
及其实现:
#include "ltlogger.h"
LtLogger::LtLogger(QObject *parent,
Config* const ltConfig)
: QObject(parent),
m_ltLogSocket(new LtLogSocket(parent,
ltConfig))
{
qInstallMessageHandler(ltMessageHandler);
} // constructor
void LtLogger::ltMessageHandler(QtMsgType type,
const QMessageLogContext& ctx,
const QString& msg)
{
QString func = ctx.function;
func = func.left(func.lastIndexOf("("));
func = func.mid(func.indexOf(" "));
func = func.mid(func.indexOf("::")+2);
QString currTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz");
QString txt;
switch (type) {
case QtInfoMsg:
txt = QString("%1 [%2] %3/%4: %5").arg(currTime).arg(QThread::currentThread()->objectName()).arg("I").arg(func).arg(msg);
break;
case QtDebugMsg:
txt = QString("%1 [%2] %3/%4: %5").arg(currTime).arg(QThread::currentThread()->objectName()).arg("D").arg(func).arg(msg);
break;
case QtWarningMsg:
txt = QString("%1 %2/%3: %4").arg(currTime).arg("W").arg(func).arg(msg);
break;
case QtCriticalMsg:
txt = QString("%1 %2/%3 (%4.%5): %6").arg(currTime).arg("C").arg(func).arg(ctx.file).arg(ctx.line).arg(msg);
break;
case QtFatalMsg:
txt = QString("%1 %2/%3 (%4.%5): %6").arg(currTime).arg("F").arg(func).arg(ctx.file).arg(ctx.line).arg(msg);
abort();
}
QTextStream ts(m_ltLogFile.data());
ts << txt << endl;
ts.flush(); // Clear the buffered data
ltCleanupLogs();
} // ltMessageHandler
当我尝试构建项目时,出现以下错误:
ltlogger.cpp: In constructor ‘LtLogger::LtLogger(QObject*, Config*)’:
ltlogger.cpp:9:44: error: invalid use of non-static member function ‘void LtLogger::ltMessageHandler(QtMsgType, const QMessageLogContext&, const QString&)’
qInstallMessageHandler(ltMessageHandler);
我缺少什么,如何将成员方法注册为消息处理程序,我在构造函数中进行了尝试,如代码所示。
答案 0 :(得分:1)
编译器给出正确的提示。 QtMessageHandler是一个独立的函数:
typedef void (*QtMessageHandler)(QtMsgType, const QMessageLogContext &, const QString &);
您可以像这样使用处理程序:
LtLogger globalLogger;
void messageHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg){
globalLogger.ltMessageHandler(type, ctx, msg);
}
[...]
qInstallMessageHandler(messageHandler);