clog
Overview
The clog is an object of ostream class of C++. It is used for error and event logging purposes. The object is declared in the iostream header. It is associated with the stderr, standard error output stream.
Syntax of clog in C++
The clog object is used along with the insertion operator << to output the characters to the standard error stream, which is a default destination for error messages and other diagnostic warnings.
Parameters of Clog in C++
clog is not a function, so it doesn't have the concept of parameters. It is used along with the insertion operator to print characters.
Return Value of Clog in C++
clog is not a function, so it also doesn't have the concept of the return value.
Example
In this example, we are printing the log(kind of information) with the help of a clog object.
Output:
How does Clog in C++ Work?
clog means character log. This object is associated with the standard error output stream in C++, so we can output the characters to show the warnings and errors.
The cerr object, associated with the stderr, is also used to print the errors to the standard error output stream. Still, the stream in clog is buffered, which means the characters will be first fed into an allocated space named buffer, and then the characters will be written to standard stream at once. The clog stream, which works with a buffered stream, is much more efficient than cerr because there is no need to write the data continuously. Still, at the same time, it is risky. If the system crashes in between the runtime, then if there is some error or diagnostic message stored in the buffer, that message will be lost.
More Example
Invalid File Open
In this example, we will see how we can use clog for logging purposes, we are going to open a file, and for details about the operation inside the code, we will provide concurrent logs.
Output 1: If file fails to open,
Output 2: If file opens successfully,
Conclusion
- clog is an object of the ostream class.
- The clog object is declared in the iostream header.
- To make this object work in the program,
- Either we can use a std namespace like this using namespace std;.
- Or scope resolution operator with std keyword like this std::.
- It prints the error messages and warnings to the standard error output stream, stderr.
- Unlike the cerr and similar to cout, it is associated with a buffer.
- It provides more efficiency than cerr but less reliability because the error messages might not be visible immediately and hence can be lost due to buffering process.