QTextStream: Add Prefix and Suffix to the beginning/end of a stream segment

67 Views Asked by At

I have a simple container class holding a QTextStream. I use it to write to a file. What I want is that the function below adds at the beginning of a stream operator call "LogHandle() << "foo" << 1234;" a prefix. E.g. "LOG:" and at the end a new line endl. Simply adding such a thing on each call of the << operator is not working of course.

Expected output:

Log: foo 1234 *break*

Current code:

class Handle{
public:
    Handle() {
        QString path = QCoreApplication::applicationDirPath();
        path.append("/foo.log");
        _file.setFileName(path);
        _stream.setDevice(&_file);
    }

    QFile _file;
    QTextStream _stream;
};

template <class T>
Handle& operator<< (Handle& out, T msg) {
    out._file.open(QIODevice::WriteOnly | QIODevice::Append);
    out._stream << msg;
    return out;
}
0

There are 0 best solutions below