1

I have this code:

    void myMessageHandler(QtMsgType type, const QMessageLogContext &, const QString & msg)
    {
        QTime time = QTime::currentTime();
        QString formattedTime = time.toString("hh:mm:ss");
        QByteArray formattedTimeMsg = formattedTime.toLocal8Bit();

        QString txt;
        switch (type) {
        case QtDebugMsg:
            txt = QString("%1: Debug: %2").arg(formattedTime, msg);
            break;
        case QtWarningMsg:
            txt = QString("%1: Warning: %2").arg(formattedTime, msg);
        break;
        case QtCriticalMsg:
            txt = QString("%1: Critical: %2").arg(formattedTime, msg);
        break;
        case QtFatalMsg:
            txt = QString("%1: Fatal: %2").arg(formattedTime, msg);
        break;
        }
        QFile outFile("debug.log");
        outFile.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream ts(&outFile);
        ts << txt << endl;
    }

which works very well as saving all console logs into the external file debug.log. However I don't know how to set it to format the file as UTF8 because some of my local special characters cant be read properly when open the file. And also how do I make new line after each record? It's all in one line depends on what application I open the log file - notepad won't show me new lines, notepad++ does, wordpad also don't...)

Thank you very much for your help guys!

B25Dec
  • 2,301
  • 5
  • 31
  • 54
Jiri Zaloudek
  • 326
  • 3
  • 19
  • Possible duplicate of [Create UTF-8 file in Qt](https://stackoverflow.com/questions/4780507/create-utf-8-file-in-qt) – ByteNudger Jul 03 '19 at 17:40

1 Answers1

0

Both can be achieved by configuring your text stream:

  1. End-of-line terminators will be translated into "\r\n" on Windows when the stream is opened as text: QTextStream ts(&outFile, QIODevice::Text);
  2. Set the codec to write UTF-8: ts.setCodec("UTF-8");

Documentation of QTexStream is quite good: https://doc.qt.io/qt-5/qtextstream.html

Georgy Pashkov
  • 1,285
  • 7
  • 11