Problem with log writer

Started by
6 comments, last by RAZORUNREAL 18 years, 9 months ago
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
Loading texture BackIn Main loop
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.
Advertisement
Try to do a flush() call after all your writes.
I edited the log writing function to:
	// log file function	void	writeLog(std::string what) {log << what << std::endl; log.flush();}


Still no luck... :/
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.
___________________________________________________David OlsenIf I've helped you, please vote for PigeonGrape!
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 );

Nope... I havent learned anything about threading yet... but the function is called from multiple classes, could that be the problem?
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?
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.
___________________________________________________David OlsenIf I've helped you, please vote for PigeonGrape!

This topic is closed to new replies.

Advertisement