"__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