From ef80bd0a8d9158c9fdbcde30bd43e1d819ff338d Mon Sep 17 00:00:00 2001
From: zhangyao2022 <zhangyao108@huawei.com>
Date: Mon, 27 Nov 2023 19:35:55 +0800
Subject: [PATCH] fix: make sure all logs are written to disk

---
 core/sysmaster/src/manager/mod.rs |  1 +
 libs/log/src/inner.rs             | 22 ++++++++++++++++++++++
 libs/log/src/logger.rs            |  9 ++++++++-
 3 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/core/sysmaster/src/manager/mod.rs b/core/sysmaster/src/manager/mod.rs
index f1062e31..46228b77 100644
--- a/core/sysmaster/src/manager/mod.rs
+++ b/core/sysmaster/src/manager/mod.rs
@@ -460,6 +460,7 @@ impl Manager {
         }
 
         log::info!("Rebooting...");
+        log::flush!();
         let _ = reboot::reboot(reboot_mode); // make lint happy
     }
 
diff --git a/libs/log/src/inner.rs b/libs/log/src/inner.rs
index 13f42aed..f13c51ed 100644
--- a/libs/log/src/inner.rs
+++ b/libs/log/src/inner.rs
@@ -194,6 +194,14 @@ macro_rules! trace {
     )
 }
 
+/// flush output stream
+#[macro_export(local_inner_macros)]
+macro_rules! flush {
+    () => {
+        $crate::inner::__private_api_flush();
+    };
+}
+
 ///
 /* Private, shouldn't be used out of this file. */
 pub fn __private_api_log(
@@ -222,6 +230,20 @@ pub fn __private_api_log(
     }
 }
 
+///
+pub fn __private_api_flush() {
+    if STATE.load(Ordering::SeqCst) != INITIALIZED {
+        return;
+    }
+    let logger = unsafe { &LOGGER_LOCK };
+    match logger {
+        Some(v) => {
+            v.read().unwrap().flush();
+        }
+        None => {}
+    }
+}
+
 pub use crate::debug;
 pub use crate::error;
 pub use crate::info;
diff --git a/libs/log/src/logger.rs b/libs/log/src/logger.rs
index 11d8d224..15f8b118 100644
--- a/libs/log/src/logger.rs
+++ b/libs/log/src/logger.rs
@@ -340,6 +340,9 @@ impl log::Log for FileLogger {
                 if let Err(e) = file.flush() {
                     println!("Failed to flush log file: {}", e);
                 }
+                if let Err(e) = file.sync_all() {
+                    println!("Failed to sync all log file: {}", e);
+                }
             }
             None => {
                 if !get_open_when_needed() {
@@ -605,7 +608,11 @@ impl Log for CombinedLogger {
         }
     }
 
-    fn flush(&self) {}
+    fn flush(&self) {
+        for log in &self.loggers {
+            log.flush();
+        }
+    }
 }
 
 impl CombinedLogger {
-- 
2.33.0

