use crate::exports::{log_to_file, log_to_window};
use log::{Level, Log, Metadata, Record};
#[derive(Debug, Clone)]
pub struct ArcDpsLogger {
name: &'static str,
}
impl ArcDpsLogger {
#[inline]
pub const fn new(name: &'static str) -> Self {
Self { name }
}
fn window_enabled(metadata: &Metadata) -> bool {
metadata.target() != "file"
}
fn file_enabled(metadata: &Metadata) -> bool {
match metadata.target() {
"file" | "both" | "all" => true,
"window" => false,
_ => matches!(metadata.level(), Level::Warn | Level::Error),
}
}
}
impl Log for ArcDpsLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
Self::window_enabled(metadata) || Self::file_enabled(metadata)
}
fn log(&self, record: &Record) {
let metadata = record.metadata();
if Self::window_enabled(metadata) {
WindowLogger { name: self.name }.log(record);
}
if Self::file_enabled(metadata) {
FileLogger { name: self.name }.log(record);
}
}
fn flush(&self) {}
}
#[derive(Debug, Clone)]
pub struct WindowLogger {
name: &'static str,
}
impl WindowLogger {
#[inline]
pub const fn new(name: &'static str) -> Self {
Self { name }
}
}
impl Log for WindowLogger {
fn enabled(&self, _metadata: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
let _ = log_to_window(format_message(self.name, record));
}
fn flush(&self) {}
}
#[derive(Debug, Clone)]
pub struct FileLogger {
name: &'static str,
}
impl FileLogger {
#[inline]
pub const fn new(name: &'static str) -> Self {
Self { name }
}
}
impl Log for FileLogger {
fn enabled(&self, _metadata: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
let _ = log_to_file(format_message(self.name, record));
}
fn flush(&self) {}
}
fn format_message(name: &'static str, record: &Record) -> String {
format!(
"{} {}: {}",
name,
record.level().to_string().to_lowercase(),
record.args()
)
}
#[cfg(test)]
mod tests {
use super::ArcDpsLogger;
use log::{Level, Metadata};
#[test]
fn enabled() {
fn meta(target: &str, level: Level) -> Metadata {
Metadata::builder().target(target).level(level).build()
}
const MOD: &str = module_path!();
let info = meta(MOD, Level::Info);
assert!(ArcDpsLogger::window_enabled(&info));
assert!(!ArcDpsLogger::file_enabled(&info));
let warn = meta(MOD, Level::Warn);
assert!(ArcDpsLogger::window_enabled(&warn));
assert!(ArcDpsLogger::file_enabled(&warn));
let error = meta(MOD, Level::Error);
assert!(ArcDpsLogger::window_enabled(&error));
assert!(ArcDpsLogger::file_enabled(&error));
let info_file = meta("file", Level::Info);
assert!(!ArcDpsLogger::window_enabled(&info_file));
assert!(ArcDpsLogger::file_enabled(&info_file));
let info_both = meta("both", Level::Info);
assert!(ArcDpsLogger::window_enabled(&info_both));
assert!(ArcDpsLogger::file_enabled(&info_both));
}
}