Skip to content

Commit 38bff4c

Browse files
authored
Merge pull request #2432 from cagatay-y/refactor-logging
refactor(logging): make time formatting more explicit
2 parents c927d4c + 8159358 commit 38bff4c

1 file changed

Lines changed: 21 additions & 14 deletions

File tree

src/logging.rs

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use core::fmt;
22
use core::sync::atomic::{AtomicBool, Ordering};
3+
use core::time::Duration;
34

45
use anstyle::AnsiColor;
56
use log::{Level, LevelFilter, Metadata, Record};
@@ -41,14 +42,10 @@ impl log::Log for KernelLogger {
4142
return;
4243
}
4344

44-
// FIXME: Use `super let` once stable
45-
let time;
46-
let format_time = if self.time() {
47-
time = Microseconds(crate::processor::get_timer_ticks());
48-
format_args!("[{time}]")
49-
} else {
50-
format_args!("[ ]")
51-
};
45+
let time = self
46+
.time()
47+
.then(|| Duration::from_micros(crate::processor::get_timer_ticks()));
48+
let format_time = LogTime(time);
5249
let core_id = crate::arch::core_local::core_id();
5350
let level = ColorLevel(record.level());
5451

@@ -63,17 +60,27 @@ impl log::Log for KernelLogger {
6360
let format_target = format_args!(" {target:<10}");
6461

6562
let args = record.args();
66-
println!("{format_time}[{core_id}][{level}{format_target}] {args}");
63+
println!("[{format_time}][{core_id}][{level}{format_target}] {args}");
6764
}
6865
}
6966

70-
struct Microseconds(u64);
67+
struct LogTime(Option<Duration>);
7168

72-
impl fmt::Display for Microseconds {
69+
impl fmt::Display for LogTime {
7370
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74-
let seconds = self.0 / 1_000_000;
75-
let microseconds = self.0 % 1_000_000;
76-
write!(f, "{seconds:5}.{microseconds:06}")
71+
const TIME_SEC_WIDTH: usize = 5;
72+
const TIME_SUBSEC_WIDTH: usize = 6;
73+
74+
if let Some(time) = self.0 {
75+
let seconds = time.as_secs();
76+
let microseconds = time.subsec_micros();
77+
write!(
78+
f,
79+
"{seconds:TIME_SEC_WIDTH$}.{microseconds:0TIME_SUBSEC_WIDTH$}"
80+
)
81+
} else {
82+
write!(f, "{:1$}", "", TIME_SEC_WIDTH + 1 + TIME_SUBSEC_WIDTH)
83+
}
7784
}
7885
}
7986

0 commit comments

Comments
 (0)