简体   繁体   English

C++ QT 记录仪 object

[英]C++ QT Logger object

I am trying to create a globally accessible object (but I am not sure if creating a global object is a good solution) which will log to file my output stream. I would like it to work similar to std::cout, but with the difference that it would log to file.我正在尝试创建一个全局可访问的 object(但我不确定创建一个全局 object 是否是一个好的解决方案),它将记录到文件我的 output stream。我希望它的工作方式类似于 std::cout,但与区别在于它会记录到文件中。

class Logger
{
    QFile* file;
    QTextStream* stream;

public:
    Logger(QString filePath);
    {
        file = new QFile(filePath);
        if(file.open(QIODevice::ReadWrite)
            stream = new QTextStream(file);
    }
    QTextStream* Log()
    {
        return stream;
    }
};


int main(int argc, char *argv[])
{
    QString filePath="Logs.txt";
    Logger l(filePath);
    MyProgram a(argc, argv);
    return a.exec();
}

In case it would be global, all I would have to do is l.Log()<<"text I want to log in" .如果它是全球性的,我所要做的就是l.Log()<<"text I want to log in" I would prefer it to work like Log() << "text I want to log in" , but any solution would be useful: :)我希望它像Log() << "text I want to log in"一样工作,但任何解决方案都会有用::)

I want to also mention that I have came into a logger solution on web already, but it includes creating a temporary object - in my case constantly opening and closing file each time I want to log some text is not a solution.我还想提一下,我已经在 web 上找到了一个logger解决方案,但它包括创建一个临时的 object - 在我的例子中,每次我想记录一些文本时不断打开和关闭文件不是一个解决方案。 (unless this object would use some globally open file) (除非这个 object 会使用一些全局打开的文件)

What you need is Singleton Design Pattern .你需要的是Singleton 设计模式 In the entire program, you need only one object of your logger class. So you need to use Singleton Design Pattern and place it into a separate file and just included it in whatever you need the logger.在整个程序中,你只需要一个 object 的记录器 class。所以你需要使用 Singleton 设计模式并将其放入一个单独的文件中,并将其包含在任何你需要的记录器中。


For using streaming like operators (shift operator << ), you simply need to overload it:要使用流式运算符(移位运算符<< ),您只需重载它:

friend Logger& operator<<(Logger& other, QString const& message)
{
        (*other.stream) << message;
        return other;
}

But in the case of Logger, it's not that simple you written.但是对于 Logger 来说,它并不是你写的那么简单。 A logger base requirement are:记录器的基本要求是:

  1. Efficiently, to be fast enough in high rate logging.高效地,在高速率日志记录中足够快。
  2. Thread safe, to could be used in multi-threaded programs.线程安全,可以在多线程程序中使用。
  3. Formatting, to be used easily.格式化,方便使用。
  4. Log leveling, to could categorize logs.日志分级,可以对日志进行分类。

Take a look at: qDebug() , qInfo() , qWarning() and qFatal() .看看: qDebug()qInfo()qWarning()qFatal() My suggestion for logging libraries are:我对日志库的建议是:

  1. Boost.Log提升日志
  2. Speed Log速度日志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM