Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a Logger instead of cout?

Tags:

c++

logging

cout

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:

  1. Logging is thread safe, so preferred for multi threading
  2. 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?

like image 634
Emilio7773 Avatar asked Dec 13 '25 09:12

Emilio7773


1 Answers

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 an output is typically used all across an application and it is beneficial to have application-wide configurations, a logger (often a global object) can be used instead:

 void foo() {
      auto x = calculate_some_result();
      LOGGER << x;
}
like image 136
463035818_is_not_a_number Avatar answered Dec 16 '25 07:12

463035818_is_not_a_number