Inject the logger for Asterinas

This commit is contained in:
Chen Chengjun
2024-11-15 16:58:06 +08:00
committed by Tate, Hongliang Tian
parent 7865469998
commit 0cb2ea562e
18 changed files with 149 additions and 5 deletions

View File

@ -0,0 +1,64 @@
// SPDX-License-Identifier: MPL-2.0
use log::{Metadata, Record};
use ostd::timer::Jiffies;
/// The logger used for Asterinas.
struct AsterLogger;
static LOGGER: AsterLogger = AsterLogger;
impl log::Log for AsterLogger {
fn enabled(&self, _metadata: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
let timestamp = Jiffies::elapsed().as_duration().as_secs_f64();
// Use a global lock to prevent interleaving of log messages.
use ostd::sync::SpinLock;
static RECORD_LOCK: SpinLock<()> = SpinLock::new(());
let _lock = RECORD_LOCK.disable_irq().lock();
print_logs(record, timestamp);
}
fn flush(&self) {}
}
#[cfg(feature = "log_color")]
fn print_logs(record: &Record, timestamp: f64) {
use owo_colors::Style;
let timestamp_style = Style::new().green();
let record_style = Style::new().default_color();
let level_style = match record.level() {
log::Level::Error => Style::new().red(),
log::Level::Warn => Style::new().bright_yellow(),
log::Level::Info => Style::new().blue(),
log::Level::Debug => Style::new().bright_green(),
log::Level::Trace => Style::new().bright_black(),
};
super::_print(format_args!(
"{} {:<5}: {}\n",
timestamp_style.style(format_args!("[{:>10.3}]", timestamp)),
level_style.style(record.level()),
record_style.style(record.args())
));
}
#[cfg(not(feature = "log_color"))]
fn print_logs(record: &Record, timestamp: f64) {
super::_print(format_args!(
"{} {:<5}: {}\n",
format_args!("[{:>10.3}]", timestamp),
record.level(),
record.args()
));
}
pub(super) fn init() {
ostd::logger::inject_logger(&LOGGER);
}

View File

@ -0,0 +1,43 @@
// SPDX-License-Identifier: MPL-2.0
//! `print` and `println` macros
//!
//! FIXME: It will print to all `virtio-console` devices, which is not a good choice.
//!
use core::fmt::{Arguments, Write};
struct VirtioConsolesPrinter;
impl Write for VirtioConsolesPrinter {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
for (_, device) in aster_console::all_devices() {
device.send(s.as_bytes());
}
Ok(())
}
}
/// Prints the formatted arguments to the standard output.
pub fn _print(args: Arguments) {
VirtioConsolesPrinter.write_fmt(args).unwrap();
}
/// Copied from Rust std: <https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs>
#[macro_export]
macro_rules! print {
($($arg:tt)*) => {{
$crate::_print(format_args!($($arg)*));
}};
}
/// Copied from Rust std: <https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs>
#[macro_export]
macro_rules! println {
() => {
$crate::print!("\n")
};
($($arg:tt)*) => {{
$crate::_print(format_args_nl!($($arg)*));
}};
}

View File

@ -0,0 +1,30 @@
// SPDX-License-Identifier: MPL-2.0
//! The logger implementation for Asterinas.
//!
//! This logger now has the most basic logging functionality, controls the output
//! based on the globally set log level. Different log levels will be represented
//! with different colors if enabling `log_color` feature.
//!
//! This logger guarantees _atomicity_ under concurrency: messages are always
//! printed in their entirety without being mixed with messages generated
//! concurrently on other cores.
//!
//! IRQs are disabled while printing. So do not print long log messages.
#![no_std]
#![deny(unsafe_code)]
extern crate alloc;
use component::{init_component, ComponentInitError};
mod aster_logger;
mod console;
pub use console::_print;
#[init_component]
fn init() -> Result<(), ComponentInitError> {
aster_logger::init();
Ok(())
}