c++ - QMessageLogger : Singleton for a Logger?

标签 c++ qt logging singleton qt5

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

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

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

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

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()、函数名称等...)

示例 Logger,想象一下还有很多其他类,它们应该能够使用这些 void info(...)、debug(...)、ritic(...)、 fatal(...); ETC。 标题:

#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 或考虑单例。

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

相关文章:

c++ - 两个排序数组的交集

c++ - 使用本地数组作为存储时,带有 std 字符串参数的模板类会出现段错误

linux - 如何更改 Munin 的 munin-graph.log、munin-html.log、munin-limits.log 和 munin-update.log 的日志级别?

c# - 每个功能的 serilog 多个实例

ssl - 减少 Wildfly 日志中的 javax.net.ssl 噪音

c++ - 奇怪的英特尔 C++ 编译器错误

c++ - 如何判断是哪个动态加载的库导致内存泄露

c++ - 如何在插件系统中正确暴露 API?

c++ - CONFUSED -- c++ 第 3 方库,c++ 新手

c++ - 在 Windows 上部署 QML 应用程序的正确方法