In my try to teach myself C++, I thought it would be helpful for me to have a functioning logging class for future "projects". This was written on my Windows box, in VC++ 2010.
I wanted to share this to others for use and to get tips for optimization and such.
I wrote the class in a file called "log.h":
And heres a little example:PHP Code:#include <iostream>
#include <fstream>
using namespace std;
class Log_Module {
public:
void init(string filename) {
if (!out.is_open()) {
out.open(filename);
file_name = filename;
}
else
cout << "There were already an open log file." << endl;
}
template <typename T>
void log(T log_this){
if (out.is_open() && out.good())
out << log_this << endl;
else {
int var = 1;
while(!out.is_open()) {
if (!file_name.length() > 0)
break;
if (var <= 10)
out.open(file_name);
else
break;
++var;
}
if (!out.is_open())
cout << "The log file could not be opened." << endl;
else
log( log_this );
}
}
void log_close(){
out.close();
}
private:
ofstream out;
string file_name;
};
Output:PHP Code:#include "log.h"
int main() {
Log_Module l;
l.init("C:\\Users\\Andreas\\Desktop\\log_out.txt");
l.log("Log a string.");
l.log(0x33FEE);
l.log(new signed int);
l.log(new unsigned int);
l.log((bool) true);
l.log((double) 20.22);
l.log_close();
}
Code:Log a string. 212974 002D5250 002D63F0 1 20.22![]()



Reply With Quote![[C++]Simple log class](http://ragezone.com/hyper728.png)

