简体   繁体   中英

Why use a Logger instead of 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?

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;
}

A logger offers you more control - you can tune the severity threshold, you can decide where the logging goes to (eg, 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM