[REFACTOR] Split Android and CrOS logging.

Previously, they are all cramped in main.cc. Split them
into their respective files logging.cc, logging_android.cc
and provide a common header, logging.h, that main.cc can use.

Bug: 147696014
Bug: 148818798
Test: builds
Test: build logging.cc in Android
Change-Id: Iafdaee6be20e204f4faa1d1d8f81e43670f08d96
diff --git a/Android.bp b/Android.bp
index 527d246..b502632 100644
--- a/Android.bp
+++ b/Android.bp
@@ -303,6 +303,7 @@
         "daemon_state_android.cc",
         "hardware_android.cc",
         "libcurl_http_fetcher.cc",
+        "logging_android.cc",
         "metrics_reporter_android.cc",
         "metrics_utils.cc",
         "network_selector_android.cc",
diff --git a/common/utils.cc b/common/utils.cc
index e7b6975..fc89040 100644
--- a/common/utils.cc
+++ b/common/utils.cc
@@ -30,6 +30,7 @@
 #include <sys/resource.h>
 #include <sys/stat.h>
 #include <sys/types.h>
+#include <time.h>
 #include <unistd.h>
 
 #include <algorithm>
@@ -1074,6 +1075,14 @@
   return file_name.value();
 }
 
+string GetTimeAsString(time_t utime) {
+  struct tm tm;
+  CHECK_EQ(localtime_r(&utime, &tm), &tm);
+  char str[16];
+  CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
+  return str;
+}
+
 }  // namespace utils
 
 }  // namespace chromeos_update_engine
diff --git a/common/utils.h b/common/utils.h
index 9dca9e8..c6c34f4 100644
--- a/common/utils.h
+++ b/common/utils.h
@@ -18,6 +18,7 @@
 #define UPDATE_ENGINE_COMMON_UTILS_H_
 
 #include <errno.h>
+#include <time.h>
 #include <unistd.h>
 
 #include <algorithm>
@@ -329,6 +330,9 @@
                              uint16_t* high_version,
                              uint16_t* low_version);
 
+// Return a string representation of |utime| for log file names.
+std::string GetTimeAsString(time_t utime);
+
 }  // namespace utils
 
 // Utility class to close a file descriptor
diff --git a/logging.cc b/logging.cc
new file mode 100644
index 0000000..6320e36
--- /dev/null
+++ b/logging.cc
@@ -0,0 +1,87 @@
+//
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <base/files/file_util.h>
+#include <base/logging.h>
+#include <base/strings/string_util.h>
+#include <base/strings/stringprintf.h>
+
+#include "update_engine/common/utils.h"
+#include "update_engine/logging.h"
+
+using std::string;
+
+namespace chromeos_update_engine {
+
+namespace {
+
+constexpr char kSystemLogsRoot[] = "/var/log";
+
+void SetupLogSymlink(const string& symlink_path, const string& log_path) {
+  // TODO(petkov): To ensure a smooth transition between non-timestamped and
+  // timestamped logs, move an existing log to start the first timestamped
+  // one. This code can go away once all clients are switched to this version or
+  // we stop caring about the old-style logs.
+  if (utils::FileExists(symlink_path.c_str()) &&
+      !utils::IsSymlink(symlink_path.c_str())) {
+    base::ReplaceFile(
+        base::FilePath(symlink_path), base::FilePath(log_path), nullptr);
+  }
+  base::DeleteFile(base::FilePath(symlink_path), true);
+  if (symlink(log_path.c_str(), symlink_path.c_str()) == -1) {
+    PLOG(ERROR) << "Unable to create symlink " << symlink_path
+                << " pointing at " << log_path;
+  }
+}
+
+string SetupLogFile(const string& kLogsRoot) {
+  const string kLogSymlink = kLogsRoot + "/update_engine.log";
+  const string kLogsDir = kLogsRoot + "/update_engine";
+  const string kLogPath =
+      base::StringPrintf("%s/update_engine.%s",
+                         kLogsDir.c_str(),
+                         utils::GetTimeAsString(::time(nullptr)).c_str());
+  mkdir(kLogsDir.c_str(), 0755);
+  SetupLogSymlink(kLogSymlink, kLogPath);
+  return kLogSymlink;
+}
+
+}  // namespace
+
+void SetupLogging(bool log_to_system, bool log_to_file) {
+  logging::LoggingSettings log_settings;
+  log_settings.lock_log = logging::DONT_LOCK_LOG_FILE;
+  log_settings.logging_dest = static_cast<logging::LoggingDestination>(
+      (log_to_system ? logging::LOG_TO_SYSTEM_DEBUG_LOG : 0) |
+      (log_to_file ? logging::LOG_TO_FILE : 0));
+  log_settings.log_file = nullptr;
+
+  string log_file;
+  if (log_to_file) {
+    log_file = SetupLogFile(kSystemLogsRoot);
+    log_settings.delete_old = logging::APPEND_TO_OLD_LOG_FILE;
+    log_settings.log_file = log_file.c_str();
+  }
+  logging::InitLogging(log_settings);
+}
+
+}  // namespace chromeos_update_engine
diff --git a/logging.h b/logging.h
new file mode 100644
index 0000000..c9e7483
--- /dev/null
+++ b/logging.h
@@ -0,0 +1,23 @@
+//
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+namespace chromeos_update_engine {
+
+// Set up logging. |log_to_system| and |log_to_file| specifies
+// the destination of logs.
+void SetupLogging(bool log_to_system, bool log_to_file);
+
+}  // namespace chromeos_update_engine
diff --git a/logging_android.cc b/logging_android.cc
new file mode 100644
index 0000000..ae1c8ed
--- /dev/null
+++ b/logging_android.cc
@@ -0,0 +1,109 @@
+//
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <string>
+#include <vector>
+
+#include <base/files/dir_reader_posix.h>
+#include <base/logging.h>
+#include <base/strings/string_util.h>
+#include <base/strings/stringprintf.h>
+
+#include "update_engine/common/utils.h"
+
+using std::string;
+
+namespace chromeos_update_engine {
+namespace {
+
+constexpr char kSystemLogsRoot[] = "/data/misc/update_engine_log";
+constexpr size_t kLogCount = 5;
+
+// Keep the most recent |kLogCount| logs but remove the old ones in
+// "/data/misc/update_engine_log/".
+void DeleteOldLogs(const string& kLogsRoot) {
+  base::DirReaderPosix reader(kLogsRoot.c_str());
+  if (!reader.IsValid()) {
+    LOG(ERROR) << "Failed to read " << kLogsRoot;
+    return;
+  }
+
+  std::vector<string> old_logs;
+  while (reader.Next()) {
+    if (reader.name()[0] == '.')
+      continue;
+
+    // Log files are in format "update_engine.%Y%m%d-%H%M%S",
+    // e.g. update_engine.20090103-231425
+    uint64_t date;
+    uint64_t local_time;
+    if (sscanf(reader.name(),
+               "update_engine.%" PRIu64 "-%" PRIu64 "",
+               &date,
+               &local_time) == 2) {
+      old_logs.push_back(reader.name());
+    } else {
+      LOG(WARNING) << "Unrecognized log file " << reader.name();
+    }
+  }
+
+  std::sort(old_logs.begin(), old_logs.end(), std::greater<string>());
+  for (size_t i = kLogCount; i < old_logs.size(); i++) {
+    string log_path = kLogsRoot + "/" + old_logs[i];
+    if (unlink(log_path.c_str()) == -1) {
+      PLOG(WARNING) << "Failed to unlink " << log_path;
+    }
+  }
+}
+
+string SetupLogFile(const string& kLogsRoot) {
+  DeleteOldLogs(kLogsRoot);
+
+  return base::StringPrintf("%s/update_engine.%s",
+                            kLogsRoot.c_str(),
+                            utils::GetTimeAsString(::time(nullptr)).c_str());
+}
+
+}  // namespace
+
+void SetupLogging(bool log_to_system, bool log_to_file) {
+  logging::LoggingSettings log_settings;
+  log_settings.lock_log = logging::DONT_LOCK_LOG_FILE;
+  log_settings.logging_dest = static_cast<logging::LoggingDestination>(
+      (log_to_system ? logging::LOG_TO_SYSTEM_DEBUG_LOG : 0) |
+      (log_to_file ? logging::LOG_TO_FILE : 0));
+  log_settings.log_file = nullptr;
+
+  string log_file;
+  if (log_to_file) {
+    log_file = SetupLogFile(kSystemLogsRoot);
+    log_settings.delete_old = logging::APPEND_TO_OLD_LOG_FILE;
+    log_settings.log_file = log_file.c_str();
+  }
+  logging::InitLogging(log_settings);
+
+  // The log file will have AID_LOG as group ID; this GID is inherited from the
+  // parent directory "/data/misc/update_engine_log" which sets the SGID bit.
+  chmod(log_file.c_str(), 0640);
+}
+
+}  // namespace chromeos_update_engine
diff --git a/main.cc b/main.cc
index 26f9efb..4377a15 100644
--- a/main.cc
+++ b/main.cc
@@ -14,149 +14,22 @@
 // limitations under the License.
 //
 
-#include <inttypes.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <unistd.h>
 #include <xz.h>
 
-#include <algorithm>
-#include <string>
-#include <vector>
-
 #include <base/at_exit.h>
 #include <base/command_line.h>
-#include <base/files/dir_reader_posix.h>
-#include <base/files/file_util.h>
 #include <base/logging.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
 #include <brillo/flag_helper.h>
 
 #include "update_engine/common/terminator.h"
 #include "update_engine/common/utils.h"
 #include "update_engine/daemon.h"
+#include "update_engine/logging.h"
 
 using std::string;
 
-namespace chromeos_update_engine {
-namespace {
-
-string GetTimeAsString(time_t utime) {
-  struct tm tm;
-  CHECK_EQ(localtime_r(&utime, &tm), &tm);
-  char str[16];
-  CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
-  return str;
-}
-
-#ifdef __ANDROID__
-constexpr char kSystemLogsRoot[] = "/data/misc/update_engine_log";
-constexpr size_t kLogCount = 5;
-
-// Keep the most recent |kLogCount| logs but remove the old ones in
-// "/data/misc/update_engine_log/".
-void DeleteOldLogs(const string& kLogsRoot) {
-  base::DirReaderPosix reader(kLogsRoot.c_str());
-  if (!reader.IsValid()) {
-    LOG(ERROR) << "Failed to read " << kLogsRoot;
-    return;
-  }
-
-  std::vector<string> old_logs;
-  while (reader.Next()) {
-    if (reader.name()[0] == '.')
-      continue;
-
-    // Log files are in format "update_engine.%Y%m%d-%H%M%S",
-    // e.g. update_engine.20090103-231425
-    uint64_t date;
-    uint64_t local_time;
-    if (sscanf(reader.name(),
-               "update_engine.%" PRIu64 "-%" PRIu64 "",
-               &date,
-               &local_time) == 2) {
-      old_logs.push_back(reader.name());
-    } else {
-      LOG(WARNING) << "Unrecognized log file " << reader.name();
-    }
-  }
-
-  std::sort(old_logs.begin(), old_logs.end(), std::greater<string>());
-  for (size_t i = kLogCount; i < old_logs.size(); i++) {
-    string log_path = kLogsRoot + "/" + old_logs[i];
-    if (unlink(log_path.c_str()) == -1) {
-      PLOG(WARNING) << "Failed to unlink " << log_path;
-    }
-  }
-}
-
-string SetupLogFile(const string& kLogsRoot) {
-  DeleteOldLogs(kLogsRoot);
-
-  return base::StringPrintf("%s/update_engine.%s",
-                            kLogsRoot.c_str(),
-                            GetTimeAsString(::time(nullptr)).c_str());
-}
-#else
-constexpr char kSystemLogsRoot[] = "/var/log";
-
-void SetupLogSymlink(const string& symlink_path, const string& log_path) {
-  // TODO(petkov): To ensure a smooth transition between non-timestamped and
-  // timestamped logs, move an existing log to start the first timestamped
-  // one. This code can go away once all clients are switched to this version or
-  // we stop caring about the old-style logs.
-  if (utils::FileExists(symlink_path.c_str()) &&
-      !utils::IsSymlink(symlink_path.c_str())) {
-    base::ReplaceFile(
-        base::FilePath(symlink_path), base::FilePath(log_path), nullptr);
-  }
-  base::DeleteFile(base::FilePath(symlink_path), true);
-  if (symlink(log_path.c_str(), symlink_path.c_str()) == -1) {
-    PLOG(ERROR) << "Unable to create symlink " << symlink_path
-                << " pointing at " << log_path;
-  }
-}
-
-string SetupLogFile(const string& kLogsRoot) {
-  const string kLogSymlink = kLogsRoot + "/update_engine.log";
-  const string kLogsDir = kLogsRoot + "/update_engine";
-  const string kLogPath =
-      base::StringPrintf("%s/update_engine.%s",
-                         kLogsDir.c_str(),
-                         GetTimeAsString(::time(nullptr)).c_str());
-  mkdir(kLogsDir.c_str(), 0755);
-  SetupLogSymlink(kLogSymlink, kLogPath);
-  return kLogSymlink;
-}
-#endif  // __ANDROID__
-
-void SetupLogging(bool log_to_system, bool log_to_file) {
-  logging::LoggingSettings log_settings;
-  log_settings.lock_log = logging::DONT_LOCK_LOG_FILE;
-  log_settings.logging_dest = static_cast<logging::LoggingDestination>(
-      (log_to_system ? logging::LOG_TO_SYSTEM_DEBUG_LOG : 0) |
-      (log_to_file ? logging::LOG_TO_FILE : 0));
-  log_settings.log_file = nullptr;
-
-  string log_file;
-  if (log_to_file) {
-    log_file = SetupLogFile(kSystemLogsRoot);
-    log_settings.delete_old = logging::APPEND_TO_OLD_LOG_FILE;
-    log_settings.log_file = log_file.c_str();
-  }
-  logging::InitLogging(log_settings);
-
-#ifdef __ANDROID__
-  // The log file will have AID_LOG as group ID; this GID is inherited from the
-  // parent directory "/data/misc/update_engine_log" which sets the SGID bit.
-  chmod(log_file.c_str(), 0640);
-#endif
-}
-
-}  // namespace
-}  // namespace chromeos_update_engine
-
 int main(int argc, char** argv) {
   DEFINE_bool(logtofile, false, "Write logs to a file in log_dir.");
   DEFINE_bool(logtostderr,