#![deny(missing_docs)]
#![doc(html_root_url = "https://docs.rs/console_log/1.0.0")]
use log::{Level, Log, Metadata, Record, SetLoggerError};
use web_sys::console;
#[cfg(feature = "color")]
use wasm_bindgen::JsValue;
#[cfg(feature = "color")]
const STYLE: style::Style<'static> = style::Style::default();
#[cfg(feature = "color")]
#[doc(hidden)]
mod style;
static LOGGER: WebConsoleLogger = WebConsoleLogger {};
struct WebConsoleLogger {}
impl Log for WebConsoleLogger {
#[inline]
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= log::max_level()
}
fn log(&self, record: &Record) {
if !self.enabled(record.metadata()) {
return;
}
log(record);
}
fn flush(&self) {}
}
#[cfg_attr(not(feature = "color"), inline)]
pub fn log(record: &Record) {
#[cfg(not(feature = "color"))]
{
let console_log = match record.level() {
Level::Error => console::error_1,
Level::Warn => console::warn_1,
Level::Info => console::info_1,
Level::Debug => console::log_1,
Level::Trace => console::debug_1,
};
console_log(&format!("{}", record.args()).into());
}
#[cfg(feature = "color")]
{
let console_log = match record.level() {
Level::Error => console::error_4,
Level::Warn => console::warn_4,
Level::Info => console::info_4,
Level::Debug => console::log_4,
Level::Trace => console::debug_4,
};
let message = {
let message = format!(
"%c{level}%c {file}:{line} %c\n{text}",
level = record.level(),
file = record.file().unwrap_or_else(|| record.target()),
line = record
.line()
.map_or_else(|| "[Unknown]".to_string(), |line| line.to_string()),
text = record.args(),
);
JsValue::from(&message)
};
let level_style = {
let style_str = match record.level() {
Level::Trace => STYLE.trace,
Level::Debug => STYLE.debug,
Level::Info => STYLE.info,
Level::Warn => STYLE.warn,
Level::Error => STYLE.error,
};
JsValue::from(style_str)
};
let file_line_style = JsValue::from_str(STYLE.file_line);
let text_style = JsValue::from_str(STYLE.text);
console_log(&message, &level_style, &file_line_style, &text_style);
}
}
#[inline]
pub fn init_with_level(level: Level) -> Result<(), SetLoggerError> {
log::set_logger(&LOGGER)?;
log::set_max_level(level.to_level_filter());
Ok(())
}
#[inline]
pub fn init() -> Result<(), SetLoggerError> {
init_with_level(Level::Info)
}