gpt4 book ai didi

c++ - QMessageLogger : Singleton for a Logger?

转载 作者:搜寻专家 更新时间:2023-10-31 01:00:15 25 4
gpt4 key购买 nike

我想为我的应用程序实现一个记录器,因此我创建了一个派生自 QMessageLogger 的类 MyAppLogger

假设我在我的 Qt MyApp 项目中实现了其他几个类:

  • MainWidget : QWidget
  • 帮助对话框:QDialog
  • 计算数字

如何在不创建三个记录器的情况下为所有这些类提供记录器?我想使用 Singleton 机制。但是我读到单例是一种糟糕的编程技术!?

Here我刚刚创建了一个带有两个空对话框的简单项目。然后我有一个 MyAppLogger,它将创建格式化的字符串,如:

[MyApp] info 12:12:00:123[ms]_12.12.2012) Object 'MyCalculator'created at 0xdeadbeef

[MyApp] fatal 12:12:00:123[ms]_12.12.2012) Crash at function 'divisionDouble'

当然有所需的正确参数(currentSystemTimeInMillis()、funtionname 等...)

例如 Logger,假设有很多其他类,应该能够使用那些 void info(...)、debug(...)、critical(...)、fatal(...); ETC。 header :

#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
}

最佳答案

据我所知,您想要实现两件事:

  1. 更改所有日志输出的输出格式。
    您应该考虑使用 qSetMessagePattern为此。

  2. 将所有日志输出写入文件:
    不需要子类化 QMessageLogger。只需使用 qInstallMessageHandler安装自定义处理程序并将日志消息写入文件。

使用这两种方法的优点是您可以使用 qt 自己的调试宏(qDebug()、qFatal() ...)并且您不需要编写自己的 MessageLogger 或考虑 Singletons。

关于c++ - QMessageLogger : Singleton for a Logger?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31474860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com