Monday, October 25, 2010

Log Time, Date, FileName, FunctionName, LineNumber for QT Applications in C++

Logging provides developers with detailed information about program flow. Logging also makes tracing of exceptions occured easier at run-time. By including date, time, filename, functionname, linenumber into a text file; it becomes a helpful guide for program flow trace. C++ comes with macros that are usable for logging purposes.
"__FILE__" macro gives information about the curent fileName and returns a string. "__FUNCTION__" macro gives information about the name of the current function and returns a string. "__LINE__" macro gives information about the current line number and returns an integer value. These are ANSI-Compliant Predefined Macros.
Logger.h file contains declaration for Log class.
#include <fstream>
#include <QString>
using namespace std;

class Log {
public:
 Log();
 ~Log();
 void trace(QString fileName, QString functionName, int lineNumber);
private:
 ofstream myFile;
 char stime[9];
 char sdate[9];
};


Logger.cpp file contains implementation for Log class. trace() method takes fileName, functionName and lineNumber as parameters.
#include <fstream>
#include "Logger.h"
#include <time.h>
using namespace std;

Log::Log() {
}

void Log::trace(QString fileName, QString functionName, int lineNumber) {
 _strtime(stime);
 _strdate(sdate);
 myFile.open("C:\\example.txt", fstream::in | fstream::out | fstream::app);
 myFile<<"Date:"<<sdate<<";"<<" Time:"<<stime<<";"<<" FileName:"<<qPrintable(fileName)<<";"<<" FunctionName:"<<qPrintable(functionName)<<";"<<" LineNo:"<<lineNumber<<endl;
 myFile.close(); 
}

Log::~Log(){
 myFile.close();
}


main.cpp file uses Log class trace method for logging purposes.
#include "logger.h"
int main(int argc, char *argv[])
{
   Log* logger = new Log();
   logger->trace(__FILE__, __FUNCTION__, __LINE__);
   return 0;
}


trace method produces the output to the example.txt file that is located under the c:\ root directory. Sample output is generated as follows:
Date:10/25/10; Time:21:07:25; FileName:.\main.cpp; FunctionName:main; LineNo:5

No comments:

Post a Comment