C++ clog

clog and cerr, both are associated with stderr, but it differs from cerr in the sense that the streams in clog are buffered and not automatically tied with cout.

Buffered output is more efficient than unbuffered output. In the case of buffered output, all the output is saved into a variable and written to disk all at once. For unbuffered output, we have to keep writing to disk. 

Buffered output isn't preferred for critical errors. In case of system crash, there can come a situation where the output was still in buffer and wasn't written to disk and the error message cannot be retrieved. We cannot afford to lose error data in case of system crash so we keep writing the critical errors to disc even though it is slower.

clog is commonly used for logging purposes. For non-critical event logging, efficiency is more important so clog is preferred to cerr.

clog declaration

extern ostream clog;

It is defined in <iostream> header file.

The clog object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed. clog is not tied to any other stream.

The "c" in clog refers to "character", hence clog means "character log".

The clog object is used along with the insertion operator (<<) in order to display a stream of characters. The general syntax is:

clog << varName;

or

clog << "Some String";

The extraction operator can be used more than once with a combination of variables, strings and manipulators (like endl):

clog << var1 << "Some String" << var2 << endl;

Example : How clog works?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	char fileName[] = "data.txt";
	ifstream infile(fileName);
	
	if(infile)
		cout << infile.rdbuf();
		
	else
		clog << "Error while opening the file " << fileName << endl; 
      return 0;
}

In this program, clog is used to stream the log data because the error in this case is not critical to the application. So use of buffered output of clog is more efficient

When you run the program, the output will be [if there is error in opening the file]:

Error while opening the file data.txt
Did you find this article helpful?