main: Move logger into its own mod

In preparation for extending its functionality, refactor the Logger
struct and its implementation to a new file / module.

Assisted-by: Claude:Opus-4.6
Signed-off-by: Rob Bradford <rbradford@meta.com>
This commit is contained in:
Rob Bradford
2026-04-28 14:27:44 +01:00
parent 3fc0ff00d5
commit 661faf51fe
2 changed files with 50 additions and 41 deletions

View File

@@ -0,0 +1,47 @@
// Copyright © 2026 Cloud Hypervisor Contributors
//
// SPDX-License-Identifier: Apache-2.0
//
use std::sync::Mutex;
pub struct Logger {
pub output: Mutex<Box<dyn std::io::Write + Send>>,
pub start: std::time::Instant,
}
impl log::Log for Logger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}
fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}
let now = std::time::Instant::now();
let duration = now.duration_since(self.start);
let duration_s = duration.as_secs_f32();
let location = if let (Some(file), Some(line)) = (record.file(), record.line()) {
format!("{file}:{line}")
} else {
record.target().to_string()
};
let mut out = self.output.lock().unwrap();
write!(
&mut *out,
// 10: 6 decimal places + sep => whole seconds in range `0..=999` properly aligned
"cloud-hypervisor: {:>10.6?}s: <{}> {}:{} -- {}\r\n",
duration_s,
std::thread::current().name().unwrap_or("anonymous"),
record.level(),
location,
record.args(),
)
.ok();
}
fn flush(&self) {}
}

View File

@@ -3,6 +3,7 @@
// SPDX-License-Identifier: Apache-2.0
//
mod logger;
#[cfg(test)]
mod test_util;
@@ -39,6 +40,8 @@ use vmm::vm_config::{
use vmm_sys_util::eventfd::EventFd;
use vmm_sys_util::signal::block_signal;
use crate::logger::Logger;
#[cfg(feature = "dhat-heap")]
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
@@ -116,47 +119,6 @@ enum FdTableError {
Dup2(#[source] std::io::Error),
}
struct Logger {
output: Mutex<Box<dyn std::io::Write + Send>>,
start: std::time::Instant,
}
impl log::Log for Logger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}
fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}
let now = std::time::Instant::now();
let duration = now.duration_since(self.start);
let duration_s = duration.as_secs_f32();
let location = if let (Some(file), Some(line)) = (record.file(), record.line()) {
format!("{file}:{line}")
} else {
record.target().to_string()
};
let mut out = self.output.lock().unwrap();
write!(
&mut *out,
// 10: 6 decimal places + sep => whole seconds in range `0..=999` properly aligned
"cloud-hypervisor: {:>10.6?}s: <{}> {}:{} -- {}\r\n",
duration_s,
std::thread::current().name().unwrap_or("anonymous"),
record.level(),
location,
record.args(),
)
.ok();
}
fn flush(&self) {}
}
fn prepare_default_values() -> (String, String, String) {
(default_vcpus(), default_memory(), default_rng())
}