I have a problem with Russian text in debug log when I implemented my custom log handler via qInstallMessageHandler
function. Currently, my code is:
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
QByteArray localMsg = msg.toLatin1();
QString stringType;
switch (type) {
case QtDebugMsg:
stringType = "D";
break;
case QtWarningMsg:
stringType = "W";
break;
case QtCriticalMsg:
stringType = "C";
break;
case QtFatalMsg:
stringType = "Fatal";
break;
default:
stringType = "Unknown";
}
QString logString = QString("[%1] %2:%3 - %4\n")
.arg(stringType)
.arg(context.function)
.arg(context.line)
.arg(localMsg.constData());
if (__logFile.isOpen()) {
QTextStream stream(&__logFile);
stream << logString;
}
QTextStream stderrStream(stderr, QIODevice::WriteOnly);
stderrStream<<logString;
if (type == QtFatalMsg) {
abort();
}
}
And in main()
function:
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
createLogFile();
qInstallMessageHandler(myMessageOutput);
qDebug()<<"Hi привет";
But instead of "Hi привет" I got
[D] int main(int, char**):131 - Hi ??????
in qt creator log. I tried to user Windows-1251 codec, but it don't change anything.
The problem is here:
QByteArray localMsg = msg.toLatin1();
To quote the documentation for QString::toLatin1() :
Returns a Latin-1 representation of the string as a QByteArray.
The returned byte array is undefined if the string contains non-Latin1 characters. Those characters may be suppressed or replaced with a question mark .
Emphasis mine.
The good news is there's no reason you need to call this method. Converting the contents of msg from a QString to a QByteArray is completely unnecessary here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.