Write to error log

Started by
5 comments, last by Fruny 19 years, 4 months ago
Hi all, I just want to know how I can write to "stderr" logfile to help debug my game. Thanks, Joshua P.S. I mean a standard function, not an "open, write, close" file system.
-----------------------------Sismondi GamesStarted c++ in October 2004...
Advertisement
Well this is not too difficult. Infact it is one of the first things you could do for an engine.

Just create a Singelton(Since the whole game will have only 1 logfile).
Then to use it something like this:

ErrorLogger::getLogger()<<"VBO support found!"<<std::endl;

The getLogger actually returns a reference to a ifstream object so usage should be the same.

Just before your application ends, you could do a

//close file
ErrorLogger::release();
use the fileprint standard fprintf(stderr,"error: whatever\n");

the filestream stdout and stderr opens when you start your app and closes when you quit the app.
And if you are using C++ you should just do:
cerr << blablabla;
instead of
cout << blablabla;

Thomas - www.moelhave.dk
I created a class LOG (functions CreateLog(),Write(), CloseLog()) , with an extern instance, like this I can get errors in my whole project. The only Problem I have is that is doesn't want to write to the file yet. I don't have the code with me, will post it this evening (GMT), but the idea is ok no? Or am I mistaken?

Joshua
-----------------------------Sismondi GamesStarted c++ in October 2004...
This is my class:
#ifndef LOG_H#define LOG_H#include <iostream>#include <fstream>#include <cstring>using namespace std;class LOG{      public:             void CreateLog();             void Write(string);             void CloseLog();      private:              ofstream log_file;};extern LOG logfile;#endif


This is log.cpp:
#include <iostream>#include <cstring>#include "log.h"using namespace std;LOG logfile;void LOG::CreateLog(){ log_file.open("log.txt", ios_base::out | ios_base::app);                 if(!log_file) cout<< "Error Creating log file";}void LOG::Write(string logtext){ log_file << logtext << endl;}void LOG::CloseLog(){ log_file.close();}


It works fine, tell me if there is a disadvantage to using a log in this way.

Joshua
-----------------------------Sismondi GamesStarted c++ in October 2004...
No, that's OK, though I suspect your logging code will actually evolve quite a bit as you start using it.

A few nitpicks though.

never ever put a using directive in a header file.
void Write(const string&);
Watch out for initialization order. Don't try to write to your log before the log object got constructed.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement