1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#![deny(missing_docs)]
#![doc(html_root_url = "https://docs.rs/console_log/0.1.2")]

//! A logger that logs to the browser's console.
//!
//! # Example
//!
//! ```rust,no_run
//! use log::Level;
//! use log::info;
//! fn main() {
//!     console_log::init_with_level(Level::Debug);
//!
//!     info!("It works!");
//!
//!     // ...
//! }
//! ```
//!
//! # Log Levels
//! 
//! Rust's log levels map to the browser's console log in the following way.
//! 
//! | Rust       | Web Console       |
//! |------------|-------------------|
//! | `trace!()` | `console.debug()` |
//! | `debug!()` | `console.log()`   |
//! | `info!()`  | `console.info()`  |
//! | `warn!()`  | `console.warn()`  |
//! | `error!()` | `console.error()` |
//! 
//! # Getting Fancy
//!
//! The feature set provided by this crate is intentionally very basic. If you need more flexible
//! formatting of log messages (timestamps, file and line info, etc.) this crate can be used with
//! the [`fern`] logger via the [`console_log::log`] function.
//!
//! # Code Size
//! 
//! [Twiggy] reports this library adding about 180Kb to the size of a minimal wasm binary in a
//! debug build. If you want to avoid this, mark the library as optional and conditionally
//! initialize it in your code for non-release builds.
//! 
//! `Cargo.toml`
//! ```toml
//! [dependencies]
//! cfg_if = "0.1"
//! log = "0.4"
//! console_log = { version = "0.1", optional = true }
//! 
//! [features]
//! default = ["console_log"]
//! ```
//! 
//! `lib.rs`
//! ```rust,ignore
//! use wasm_bindgen::prelude::*;
//! use cfg_if::cfg_if;
//!
//! cfg_if! {
//!     if #[cfg(feature = "console_log")] {
//!         fn init_log() {
//!             use log::Level;
//!             console_log::init_with_level(Level::Trace).expect("error initializing log");
//!         }
//!     } else {
//!         fn init_log() {}
//!     }
//! }
//! 
//! #[wasm_bindgen]
//! pub fn main() {
//!     init_log();
//!     // ...
//! }
//! ```
//! 
//! # Limitations
//! 
//! The file and line number information associated with the log messages reports locations from
//! the shims generated by `wasm-bindgen`, not the location of the logger call.
//!
//! [Twiggy]: https://github.com/rustwasm/twiggy
//! [`console_log::log`]: fn.log.html
//! [`fern`]: https://docs.rs/fern

use log::{Log, Level, Record, Metadata, SetLoggerError};
use web_sys::console;

static LOGGER: WebConsoleLogger = WebConsoleLogger {};

struct WebConsoleLogger {}

impl Log for WebConsoleLogger {
    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) {}
}

/// Print a `log::Record` to the browser's console at the appropriate level.
///
/// This function is useful for integrating with the [`fern`](https://crates.io/crates/fern) logger
/// crate.
///
/// ## Example
/// ```rust,ignore
/// fern::Dispatch::new()
///     .chain(fern::Output::call(console_log::log))
///     .apply()?;
/// ```
pub fn log(record: &Record) {
    // pick the console.log() variant for the appropriate logging level
    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());
}

/// Initializes the global logger setting `max_log_level` to the given value.
///
/// ## Example
///
/// ```
/// use log::Level;
/// fn main() {
///     console_log::init_with_level(Level::Debug).expect("error initializing logger");
/// }
/// ```
pub fn init_with_level(level: Level) -> Result<(), SetLoggerError> {
    log::set_logger(&LOGGER)?;
    log::set_max_level(level.to_level_filter());
    Ok(())
}

/// Initializes the global logger with `max_log_level` set to `Level::Info` (a sensible default).
///
/// ## Example
///
/// ```
/// fn main() {
///     console_log::init().expect("error initializing logger");
/// }
/// ```
pub fn init() -> Result<(), SetLoggerError> {
    init_with_level(Level::Info)
}