Reland "[Logging] Disable always-log-ERRORs-to-stderr unless LOG_TO_FILE is set."

This is a reland of ffa05b99247df703a03b472f6d7b1fa0f3f23582

logging::LogMessage has a special-case to write LOG_ERROR messages
to stderr, even if LOG_TO_STDERR is not enabled, to make ERROR and
FATAL messages more visible, especially in tests.

Restrict this behaviour to apply only when no log destinations are
set, other than LOG_TO_FILE, so that binaries which only
LOG_TO_SYSTEM_DEBUG_LOG will never emit logspam to stderr.

Tested by adding a unit test for this case.

Bug: 968387
Change-Id: Ibe3369eb2a47accdd17cd3cbb19c921de827ca70
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1704917
Reviewed-by: danakj <[email protected]>
Commit-Queue: Wez <[email protected]>
Auto-Submit: Wez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#678513}
diff --git a/base/logging.cc b/base/logging.cc
index eaf5662..4c4bfa6 100644
--- a/base/logging.cc
+++ b/base/logging.cc
@@ -482,13 +482,23 @@
   if (severity < g_min_log_level)
     return false;
 
-  // Return true here unless we know ~LogMessage won't do anything. Note that
-  // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
-  // when g_logging_destination is LOG_NONE.
+  // Return true here unless we know ~LogMessage won't do anything.
   return g_logging_destination != LOG_NONE || log_message_handler ||
          severity >= kAlwaysPrintErrorLevel;
 }
 
+// Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
+// If |severity| is high then true will be returned when no log destinations are
+// set, or only LOG_TO_FILE is set, since that is useful for local development
+// and debugging.
+bool ShouldLogToStderr(int severity) {
+  if (g_logging_destination & LOG_TO_STDERR)
+    return true;
+  if (severity >= kAlwaysPrintErrorLevel)
+    return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
+  return false;
+}
+
 int GetVlogVerbosity() {
   return std::max(-1, LOG_INFO - GetMinLogLevel());
 }
@@ -850,11 +860,7 @@
 #endif  // OS_FUCHSIA
   }
 
-  if ((g_logging_destination & LOG_TO_STDERR) != 0 ||
-      severity_ >= kAlwaysPrintErrorLevel) {
-    // Write logs with destination LOG_TO_STDERR to stderr. Also output to
-    // stderr for logs above a certain log level to better detect and diagnose
-    // problems with unit tests, especially on the buildbots.
+  if (ShouldLogToStderr(severity_)) {
     ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
     fflush(stderr);
   }