【发布时间】:2023-04-05 20:03:01
【问题描述】:
我想为我的应用程序实现一个记录器,因此我创建了一个派生自 QMessageLogger 的类 MyAppLogger。
假设我在我的 Qt MyApp 项目中实现了其他几个类:
- MainWidget:QWidget
- 帮助对话框:QDialog
- 计算数值
如何在不创建三个 Logger 的情况下为所有这些类提供 Logger?我想使用 Singleton 机制。 但我读过单例是一种糟糕的编程技术!?
Here 我刚刚创建了一个带有两个空对话框的简单项目。然后我有一个 MyAppLogger,它将创建格式化字符串,如:
[MyApp] info 12:12:00:123[ms]_12.12.2012) 对象“MyCalculator”创建于 0xdeadbeef
[MyApp] 致命 12:12:00:123[ms]_12.12.2012) 函数“divisionDouble”崩溃
当然带有所需的正确参数(currentSystemTimeInMillis()、函数名等...)
示例 Logger,想象还有很多其他类,它们应该能够使用那些 void info(...)、debug(...)、critical(...)、fatal(...);等等。 标题:
#ifndef MYAPPLOGGER_H
#define MYAPPLOGGER_H
#include <QString>
#include <QFile>
class MyAppLogger
{
public:
MyAppLogger(QString outputFile);
void info(char* expression);
void debug(char* expression);
void critical(char* expression);
void fatal(char* expression);
private:
QFile * _debugFile;
};
#endif // MYAPPLOGGER_H
以及对应的SRC:
#include "myapplogger.h"
MyAppLogger::MyAppLogger(QString outputFile)
{
_debugFile = new QFile(outputFile);
}
void MyAppLogger::critical(char *expression)
{
QString line("[MyAPP] \t critical \t SYS_TIME (12:45:00_12.12.2012) :: ");
line.append(expression);
// write line to a file
// write line to STD output
}
【问题讨论】:
-
单身人士有其用途。没有人愿意将记录器传递给每个函数或在每个类中保留对记录器的引用。但是您不必使用单例,您可以简单地选择仅实例化一个全局记录器。但是您必须小心确保在其他人尝试使用它之前创建它。 Singleton 可以提供帮助。
-
为什么需要重写QMessageLogger?通常定义 static void action(QtMsgType type, const QMessageLogContext &context, const QString &msg) 并调用 qInstallMessageHandler(action);
-
@demonplus 除了doc.qt.io/qt-5/qtglobal.html#qInstallMessageHandler,我还有另一个例子吗?
-
基本上这就是您所需要的。您能否在帖子中分享更多详细信息,您在 MyAppLogger 中尝试做什么?
-
@demonplus 刚刚编辑了线程。我想要预先格式化的输出。
标签: c++ qt logging singleton qt5