In most of the open source C code I can see that a logger like the Google logging library glog
is used. But what are the advantages? The only advantages that I could find:
- Logging is thread safe, so preferred for multi threading
- You can choose severity levels
So If I am not doing multi threading and I don't need severity levels, is std::cout
safe to use or should I still use a logger? Why?
CodePudding user response:
Using a logger is typically more versatile than directly writing to stdout. A logger usually can be configured to write to stdout or to a file or elsewhere.
In general, directly using std::cout
is not recommended for anything but toy programs. Consider you have a function
void foo() {
auto x = calculate_some_result();
std::cout << x;
}
Then this function is of very limited use: It can only write to std::cout
, not to anywhere else. However, with just a tiny change it can, in principle, write the result anywhere:
void foo(std::ostream& out) {
auto x = calculate_some_result();
out << x;
}
Now the same function can write to a file, to stdout or to any other ostream
. As such output typically is used all across an application and it is beneficial to have application wide configuration, a logger (often a global object) can be used instead:
void foo() {
auto x = calculate_some_result();
LOGGER << x;
}
CodePudding user response:
A logger offers you more control - you can tune the severity threshold, you can decide where the logging goes to (e.g., a file, stdout, somewhere else), etc without recompiling the program.
If that is not a concern to you, and you're absolutely sure you'll always want the same output to stdout and will never want to tweak it (a least not without recompiling), by all means, go ahead and use cout
.