C++ QT 5.0 - 内置日志记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17305374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:04:43  来源:igfitidea点击:

QT 5.0 - Built in Logging?

c++qtlogging

提问by rreeves

I was doing some research on Qt 5.0 Logging and it appears to have built in classes for logging. I'm having trouble finding an example. I have located the classes i believe are relevant here.

我正在对 Qt 5.0 Logging 进行一些研究,它似乎内置了用于日志记录的类。我很难找到一个例子。我在这里找到了我认为相关的课程。

QMessageLogger

消息记录器

QMessageLogContext

消息日志上下文

I can see roughly how to create the QMessageLogger Object from the documentation, but how can I create a log file and append to it?

我可以从文档中大致了解如何创建 QMessageLogger 对象,但是如何创建日志文件并将其附加到其中?

回答by Huy

By default using qDebug(), qWarning(), etc will allow you to log information out to the console.

默认情况下,使用 qDebug()、qWarning() 等将允许您将信息注销到控制台。

#include <QtDebug>
qDebug() << "Hello world!";

QMessageLogger is designed to leverage special C++ macros (e.g. function, line, file)

QMessageLogger 旨在利用特殊的 C++ 宏(例如函数、行、文件)

QMessageLogger(__FILE__, __LINE__, 0).debug() << "Hello world!";

In Qt5 the message logger is used behind the scenes since qDebug() is a macro that will eventually instantiate an instance of QMessageLogger. So I'd just go with using the regular qDebug().

在 Qt5 中,消息记录器在幕后使用,因为 qDebug() 是一个宏,最终会实例化 QMessageLogger 的实例。所以我只会使用常规的 qDebug()。

The QMessageLogContext contains what I'd consider as "meta-data", i.e. the file, line number, etc that the qDebug() statement it was called from. Normally you'd concern yourself with the log-context if you're defining your own QtMessageHandler (see qInstallMessageHandler()).

QMessageLogContext 包含我认为是“元数据”的内容,即从中调用 qDebug() 语句的文件、行号等。如果您定义自己的 QtMessageHandler(请参阅 qInstallMessageHandler()),通常您会关心日志上下文。

The message handler allows for more control of the logging mechanism - like sending logging information to a custom logging server or even to a file.

消息处理程序允许对日志机制进行更多控制——比如将日志信息发送到自定义日志服务器甚至文件。

As provided in the Qt Documentation, creating a custom message handler is simple:

正如 Qt 文档中提供的那样,创建自定义消息处理程序很简单:

void myMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
  std::cout << msg.toStdString();
}

Check out better examples and explanations here.

在此处查看更好的示例和解释