wasm_bindgen_console_logger/
lib.rs

1//! # `wasm-bindgen` console logger
2//!
3//! This small utility crate integrates the [`log`](https://crates.io/crates/log)
4//! crate with the JavaScript console logging functions with the help of
5//! [`wasm-bindgen`](https://crates.io/crates/wasm-bindgen).
6
7//! ## Example
8//!
9//! ```
10//! use log::{error, info, warn};
11//! use wasm_bindgen::prelude::*;
12//! use wasm_bindgen_console_logger::DEFAULT_LOGGER;
13//!
14//! #[wasm_bindgen]
15//! pub fn start() {
16//!     log::set_logger(&DEFAULT_LOGGER).unwrap();
17//!     log::set_max_level(log::LevelFilter::Info);
18//!
19//!     error!("Error message");
20//!     warn!("Warning message");
21//!     info!("Informational message");
22//! }
23//! ```
24
25use log::{Level, Log, Metadata, Record};
26use wasm_bindgen::prelude::*;
27
28pub const DEFAULT_LOGGER: ConsoleLogger = ConsoleLogger {
29    formatter: &format_message,
30    log_level: Level::Trace,
31};
32
33fn format_message(record: &Record) -> String {
34    if record.level() >= Level::Debug {
35        format!("{}: {}", record.level(), record.args())
36    } else {
37        format!("{}", record.args())
38    }
39}
40
41/// Formats a `log::Record` as a `String`
42pub type RecordFormatter = Fn(&Record) -> String + Send + Sync;
43
44/// Logs messages to the Web browser's console
45///
46/// Error and warning messages will be logged with `console.error()` and `console.warn()`, respectively.
47/// All other messages will be logged with `console.log()`.
48pub struct ConsoleLogger {
49    formatter: &'static RecordFormatter,
50    log_level: Level,
51}
52
53impl ConsoleLogger {
54    /// Constructs a new `ConsoleLogger`
55    ///
56    /// The given function will be used to format the logged messages.
57    pub fn new(formatter: &'static RecordFormatter, log_level: Level) -> Self {
58        ConsoleLogger { formatter, log_level }
59    }
60
61    /// Constructs a `ConsoleLogger` with the given maximum log level
62    /// 
63    /// A default log formatter will be used.
64    pub fn with_level(level: Level) -> Self {
65        ConsoleLogger::new(&format_message, level)
66    }
67}
68
69impl Default for ConsoleLogger {
70    fn default() -> Self {
71        DEFAULT_LOGGER
72    }
73}
74
75impl Log for ConsoleLogger {
76    fn enabled(&self, metadata: &Metadata) -> bool {
77        metadata.level() <= self.log_level
78    }
79
80    fn log(&self, record: &Record) {
81        if self.enabled(record.metadata()) {
82            let msg = (self.formatter)(record);
83            match record.level() {
84                Level::Error => error(&msg),
85                Level::Warn => warn(&msg),
86                _ => log(&msg),
87            }
88        }
89    }
90
91    fn flush(&self) {}
92}
93
94// Bindings to console functions
95#[wasm_bindgen]
96extern "C" {
97    #[wasm_bindgen(js_namespace=console)]
98    fn log(text: &str);
99
100    #[wasm_bindgen(js_namespace=console)]
101    fn warn(text: &str);
102
103    #[wasm_bindgen(js_namespace=console)]
104    fn error(text: &str);
105}