use log::{LevelFilter, SetLoggerError};
const LEVEL: &str = "{LEVEL}";
const PATH: &str = "{PATH}";
const ARGS: &str = "{ARGS}";
const TIMESTAMP: &str = "{TIMESTAMP}";
pub struct DioxusLogger {
level_filter: LevelFilter,
format: &'static str,
}
impl DioxusLogger {
pub fn new(level_filter: LevelFilter) -> Self {
let format = "[{LEVEL}] {PATH} - {ARGS}";
#[cfg(feature = "timestamps")]
let format = "[{TIMESTAMP} | {LEVEL}] {PATH} - {ARGS}";
Self {
level_filter,
format,
}
}
pub fn build(self) -> Result<(), SetLoggerError> {
let level = self.level_filter.clone();
log::set_boxed_logger(Box::new(self)).map(|()| log::set_max_level(level))
}
pub fn use_format(self, format: &'static str) -> Self {
Self {
level_filter: self.level_filter,
format
}
}
}
impl log::Log for DioxusLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= self.level_filter
}
fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}
let formatted = self
.format
.replace(LEVEL, record.level().as_str())
.to_owned()
.replace(PATH, record.module_path().unwrap_or(""))
.to_owned()
.replace(ARGS, record.args().to_string().as_str());
#[cfg(feature = "timestamps")]
let formatted = format_timestamp(formatted);
#[cfg(all(
not(target_family = "wasm"),
not(target_family = "android"),
not(target_family = "ios")
))]
println!("{formatted}");
#[cfg(target_family = "wasm")]
web_sys::console::log_1(&formatted.into());
}
fn flush(&self) {}
}
#[cfg(feature = "timestamps")]
fn format_timestamp(formatted: String) -> String {
let timestamp = time::OffsetDateTime::now_utc();
formatted
.to_owned()
.replace(TIMESTAMP, timestamp.to_string().as_str())
}
pub fn init(level_filter: LevelFilter) -> Result<(), SetLoggerError> {
DioxusLogger::new(level_filter).build()
}