To redirect clog, I have been using this:

std::streambuf* clog_save;
	std::ofstream ofs;
	
	clog_save = std::clog.rdbuf();
	ofs.open(LogFilename.c_str());
	std::clog.rdbuf(ofs.rdbuf());
	
	cout << "Test cout." << endl;
	std::clog << "Test log." << endl;
	
	std::clog.rdbuf(clog_save);
	ofs.close();

However, it seems like bad "code reuse" practice to have to put this in every program I want to log. I tried to make this:

class Log
	{
		private:
			std::streambuf* clog_save;
			std::ofstream ofs;
		public:
			Log(const std::string &LogFilename)
			{
				clog_save = std::clog.rdbuf();
				ofs.open(LogFilename.c_str());
				std::clog.rdbuf(ofs.rdbuf());
			}
		
			~Log()
			{
				//reset the buffer
				std::clog.rdbuf(clog_save);
				ofs.close();
			}
	
	};

and do this to accomplish the same thing:

Log(LogFilename);
	cout << "Test cout." << endl;
	std::clog << "Test log." << endl;

but in this case "Test log." gets written to the screen instead of the file. This might have something to do with the scope of std::clog? I guess don't understand how these automatically instantiated classes (ie. cout, clog) work? Are they static or something?

Is there anyway to do this?

Thanks,
Dave

Log(LogFilename);

You have wrote Log constructor in the expression-statement: create an object then discard it - redirect the stream then come back - i.e. do nothing ;).
Try this (what desired):

Log anyVarName(LogFilename);

wow... hahaha, well at least my class was ok! Does

Log(filename)

have any use? Why is it not a compiler error?

Thanks for finding that ridiculous bug :)

Compiler error? Why?

expression_statement:: expression;
expression:: value | ...
value:: constructor_call | ...

It's a well-formed expression statement.
May be this constructor has drastic side effects... May be all my program code is concentrated in this constructor ;)

wow... hahaha, well at least my class was ok! Does

Log(filename)

have any use? Why is it not a compiler error?
Thanks for finding that ridiculous bug :)

Some immodest question to OP:
Are you sure that this OP problem is not solved yet?
;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.