#log-messages #console #logging #log-level #log #web-sys

console_log

A logging facility that routes Rust log messages to the browser's console

7 releases (1 stable)

1.0.0 Mar 10, 2023
0.2.2 Mar 10, 2023
0.2.1 Feb 25, 2023
0.2.0 Apr 21, 2020
0.1.2 Jan 1, 2019

#15 in WebAssembly

Download history 101182/week @ 2024-07-20 95149/week @ 2024-07-27 83845/week @ 2024-08-03 105974/week @ 2024-08-10 93656/week @ 2024-08-17 74979/week @ 2024-08-24 71843/week @ 2024-08-31 73383/week @ 2024-09-07 75453/week @ 2024-09-14 85671/week @ 2024-09-21 78923/week @ 2024-09-28 85292/week @ 2024-10-05 80514/week @ 2024-10-12 92410/week @ 2024-10-19 92305/week @ 2024-10-26 105905/week @ 2024-11-02

385,260 downloads per month
Used in 1,777 crates (151 directly)

MIT/Apache

29KB
111 lines

console_log Crates.io

A logger that routes messages to the browser's console.

Usage

use log::Level;
fn main() {
    console_log::init_with_level(Level::Debug);

    info!("It works!");

    // ...
}

Details

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()

Colors

The "color" feature adds styling to the log messages.

Cargo.toml

console_log = { version = "1", features = ["color"] }

The styled log messages will be rendered as follows:

Styled log messages

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

[dependencies]
cfg-if = "0.1"
log = "0.4"
console_log = { version = "1", optional = true }

[features]
default = ["console_log"]

lib.rs

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.

License

This project is licensed under either of

at your option.

Contributing

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

See Also

Dependencies

~7.5–10MB
~181K SLoC