user932
user932

Reputation: 61

How to save debug info into particular file in qt?

I'm wondering how can I save a debug info into file named "LogFile-YYYYMMDDHHMMSS". I'm using such formula:

QString dt = QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss");
QString txt = QString("[%1] ").arg(dt);

switch (type)
{
  case QtDebugMsg:
     txt += QString("{Debug} \t\t %1").arg(msg);
     break;
  case QtWarningMsg:
     txt += QString("{Warning} \t %1").arg(msg);
     break;
  case QtCriticalMsg:
     txt += QString("{Critical} \t %1").arg(msg);
     break;
  case QtFatalMsg:
     txt += QString("{Fatal} \t\t %1").arg(msg);
     abort();
     break;
}

QFile outFile( QString("LogFile.log");
outFile.open(QIODevice::WriteOnly | QIODevice::Append);

QTextStream textStream(&outFile);
textStream << txt << endl;

Upvotes: 0

Views: 1409

Answers (2)

Michael Petch
Michael Petch

Reputation: 47553

I think a better answer uses a single datetime object (curdt in my example) and then produce two types of strings out of the one object. One for log information inside the log, and the log file name itself. We want to use a single copy of the current date/time so that what we write in the log file is the same date/time (in a different format) that appears in the log file name. If you called QDateTime::currentDateTime() twice it is possible to get two slightly different times.

/* Store a copy of the current date and time */
QDateTime curdt = QDateTime::currentDateTime();

/* Convert it to a string for logging */
QString dtstr = curdt.toString("dd/MM/yyyy hh:mm:ss");
QString txt = QString("[%1] ").arg(dtstr);

/* Create a filename for the log */
QString logfilename = "LogFile-" + curdt.toString("yyyyMMddhhmmss") + ".log";

[snip]

QFile outFile(logfilename);

Upvotes: 1

Jablonski
Jablonski

Reputation: 18504

Try this:

QString dt = "LogFile";
dt += QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss");
dt.remove("/");
dt.remove(":");
dt += ".log";
QFile outFile( dt );
utFile.open(QIODevice::WriteOnly | QIODevice::Append);

QTextStream textStream(&outFile);
textStream <<"test";
outFile.close();

You should remove this symbols because OS forbids using of this symbols in file path and your file will not be saved.

Or use easier way:

QString dt = "LogFile";
dt += QDateTime::currentDateTime().toString("ddMMyyyy hhmmss");
dt += ".log";

Upvotes: 1

Related Questions