# Problem with log writer

## Recommended Posts

Ive got a function in my class that writes to a log. It looks like this:
private:
// the log file
std::ofstream log;

public:
// log file function
void	writeLog(std::string what) {log << what << std::endl;}

And in the constructor I create/open it this way:
	system("del /F /Q SDL_Log.txt");   // delete first to make sure its new
log.open( "SDL_Log.txt", ios_base::out);

And everytime I edit something I write it to the log, then I can tell where the program died (cause thats where it stopped writing :P). But in my log file I get this:
Screen resolution set to 640 x 480
Renderworld is going to render 300 tiles
ng texture 0

Line two should be "Loading texture Background" but for some reason line three begins before line two manage to finish. And only the second half of line four is written, it should say "Loading texture 0". And there should be one more line saying "Loading texture 1". Whats wrong with the way Im handling the log file? I might add that this output isnt always what I get... sometimes its even right but I dont want that kind of chance based success when I run my program :P.

##### Share on other sites
Try to do a flush() call after all your writes.

##### Share on other sites
I edited the log writing function to:
	// log file function	void	writeLog(std::string what) {log << what << std::endl; log.flush();}

Still no luck... :/

##### Share on other sites
I'm not sure what the problem is, but this works for me:
//At start up...std::ofstream out;out.open("Log.txt"); //Automatically deletes any existing file, you have to tell it to append for it not to.std::clog.rdbuf(out.rdbuf()); //Redirect clog to output to file.//To log message:std::clog << "LOG: " << message << std::endl;

In fact mine is a little more complicated, because it can be called from different threads.

##### Share on other sites
Is your log function called from different threads? Cause in that case you need some synchronization. Something the likes of:
lockMutex( &m_mutex );log << what << std::endl;unlockMutex( &m_mutex );

##### Share on other sites
Nope... I havent learned anything about threading yet... but the function is called from multiple classes, could that be the problem?

##### Share on other sites
Razor, yes that did work but only to some extent, now only the class which the

std::ofstream log; // the log file

is a member of can write to it, any way to fix this?

##### Share on other sites
Really? I thought after setup you would be able to use clog anywhere to write to the log file, but I never tried it. I just have a util::Log(std::string message); function.

Oh, I forgot to mention, endl flushes the stream and \n doesn't, in case you ever need to know.

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627671
• Total Posts
2978551

• 11
• 10
• 10
• 12
• 22