Skip to content

Commit b2440b8

Browse files
authored
Merge pull request #6 from azriel91/feature/add-colors
Feature/add colors
2 parents 74e1740 + 6d8a93c commit b2440b8

File tree

5 files changed

+142
-21
lines changed

5 files changed

+142
-21
lines changed

Cargo.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,11 @@ version = "0.4"
1717
[dependencies.web-sys]
1818
version = "0.3"
1919
features = ["console"]
20+
21+
[dependencies.wasm-bindgen]
22+
version = "0.2"
23+
optional = true
24+
25+
[features]
26+
default = []
27+
color = ["wasm-bindgen"]

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,19 @@ Rust's log levels map to the browser's console log in the following way.
2727
| `warn!()` | `console.warn()` |
2828
| `error!()` | `console.error()` |
2929

30+
## Colors
31+
32+
The `"color"` feature adds styling to the log messages.
33+
34+
`Cargo.toml`
35+
```toml
36+
console_log = { version = "0.1", features = ["color"] }
37+
```
38+
39+
The styled log messages will be rendered as follows:
40+
41+
![Styled log messages](img/log_messages_styled.png)
42+
3043
## Code Size
3144

3245
[Twiggy](https://github.com/rustwasm/twiggy) reports this library adding about

img/log_messages_styled.png

19.1 KB
Loading

src/lib.rs

Lines changed: 88 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,40 +18,53 @@
1818
//! ```
1919
//!
2020
//! # Log Levels
21-
//!
21+
//!
2222
//! Rust's log levels map to the browser's console log in the following way.
23-
//!
23+
//!
2424
//! | Rust | Web Console |
2525
//! |------------|-------------------|
2626
//! | `trace!()` | `console.debug()` |
2727
//! | `debug!()` | `console.log()` |
2828
//! | `info!()` | `console.info()` |
2929
//! | `warn!()` | `console.warn()` |
3030
//! | `error!()` | `console.error()` |
31-
//!
31+
//!
3232
//! # Getting Fancy
3333
//!
3434
//! The feature set provided by this crate is intentionally very basic. If you need more flexible
3535
//! formatting of log messages (timestamps, file and line info, etc.) this crate can be used with
3636
//! the [`fern`] logger via the [`console_log::log`] function.
3737
//!
38+
//! ## Colors
39+
//!
40+
//! The `"color"` feature adds styling to the log messages.
41+
//!
42+
//! `Cargo.toml`
43+
//! ```toml
44+
//! console_log = { version = "0.1", features = ["color"] }
45+
//! ```
46+
//!
47+
//! The styled log messages will be rendered as follows:
48+
//!
49+
//! ![Styled log messages](img/log_messages_styled.png)
50+
//!
3851
//! # Code Size
39-
//!
52+
//!
4053
//! [Twiggy] reports this library adding about 180Kb to the size of a minimal wasm binary in a
4154
//! debug build. If you want to avoid this, mark the library as optional and conditionally
4255
//! initialize it in your code for non-release builds.
43-
//!
56+
//!
4457
//! `Cargo.toml`
4558
//! ```toml
4659
//! [dependencies]
4760
//! cfg_if = "0.1"
4861
//! log = "0.4"
4962
//! console_log = { version = "0.1", optional = true }
50-
//!
63+
//!
5164
//! [features]
5265
//! default = ["console_log"]
5366
//! ```
54-
//!
67+
//!
5568
//! `lib.rs`
5669
//! ```rust,ignore
5770
//! use wasm_bindgen::prelude::*;
@@ -67,26 +80,36 @@
6780
//! fn init_log() {}
6881
//! }
6982
//! }
70-
//!
83+
//!
7184
//! #[wasm_bindgen]
7285
//! pub fn main() {
7386
//! init_log();
7487
//! // ...
7588
//! }
7689
//! ```
77-
//!
90+
//!
7891
//! # Limitations
79-
//!
92+
//!
8093
//! The file and line number information associated with the log messages reports locations from
8194
//! the shims generated by `wasm-bindgen`, not the location of the logger call.
8295
//!
8396
//! [Twiggy]: https://github.com/rustwasm/twiggy
8497
//! [`console_log::log`]: fn.log.html
8598
//! [`fern`]: https://docs.rs/fern
8699
87-
use log::{Log, Level, Record, Metadata, SetLoggerError};
100+
use log::{Level, Log, Metadata, Record, SetLoggerError};
88101
use web_sys::console;
89102

103+
#[cfg(feature = "color")]
104+
use wasm_bindgen::JsValue;
105+
106+
#[cfg(feature = "color")]
107+
const STYLE: style::Style<'static> = style::Style::default();
108+
109+
#[cfg(feature = "color")]
110+
#[doc(hidden)]
111+
mod style;
112+
90113
static LOGGER: WebConsoleLogger = WebConsoleLogger {};
91114

92115
struct WebConsoleLogger {}
@@ -119,16 +142,60 @@ impl Log for WebConsoleLogger {
119142
/// .apply()?;
120143
/// ```
121144
pub fn log(record: &Record) {
122-
// pick the console.log() variant for the appropriate logging level
123-
let console_log = match record.level() {
124-
Level::Error => console::error_1,
125-
Level::Warn => console::warn_1,
126-
Level::Info => console::info_1,
127-
Level::Debug => console::log_1,
128-
Level::Trace => console::debug_1,
129-
};
130-
131-
console_log(&format!("{}", record.args()).into());
145+
#[cfg(not(feature = "color"))]
146+
{
147+
// pick the console.log() variant for the appropriate logging level
148+
let console_log = match record.level() {
149+
Level::Error => console::error_1,
150+
Level::Warn => console::warn_1,
151+
Level::Info => console::info_1,
152+
Level::Debug => console::log_1,
153+
Level::Trace => console::debug_1,
154+
};
155+
156+
console_log(&format!("{}", record.args()).into());
157+
}
158+
159+
#[cfg(feature = "color")]
160+
{
161+
// pick the console.log() variant for the appropriate logging level
162+
let console_log = match record.level() {
163+
Level::Error => console::error_4,
164+
Level::Warn => console::warn_4,
165+
Level::Info => console::info_4,
166+
Level::Debug => console::log_4,
167+
Level::Trace => console::debug_4,
168+
};
169+
170+
let message = {
171+
let message = format!(
172+
"%c{level}%c {file}:{line} %c\n{text}",
173+
level = record.level(),
174+
file = record.file().unwrap_or_else(|| record.target()),
175+
line = record
176+
.line()
177+
.map_or_else(|| "[Unknown]".to_string(), |line| line.to_string()),
178+
text = record.args(),
179+
);
180+
JsValue::from(&message)
181+
};
182+
183+
let level_style = {
184+
let style_str = match record.level() {
185+
Level::Trace => STYLE.trace,
186+
Level::Debug => STYLE.debug,
187+
Level::Info => STYLE.info,
188+
Level::Warn => STYLE.warn,
189+
Level::Error => STYLE.error,
190+
};
191+
192+
JsValue::from(style_str)
193+
};
194+
195+
let file_line_style = JsValue::from_str(STYLE.file_line);
196+
let text_style = JsValue::from_str(STYLE.text);
197+
console_log(&message, &level_style, &file_line_style, &text_style);
198+
}
132199
}
133200

134201
/// Initializes the global logger setting `max_log_level` to the given value.

src/style.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/// Log message styling.
2+
///
3+
/// Adapted from <https://gitlab.com/limira-rs/wasm-logger/-/blob/0c16227/src/lib.rs#L72-85>
4+
pub(crate) struct Style<'s> {
5+
pub trace: &'s str,
6+
pub debug: &'s str,
7+
pub info: &'s str,
8+
pub warn: &'s str,
9+
pub error: &'s str,
10+
pub file_line: &'s str,
11+
pub text: &'s str,
12+
}
13+
14+
impl Style<'static> {
15+
/// Returns default style values.
16+
pub const fn default() -> Self {
17+
macro_rules! bg_color {
18+
($color:expr) => {
19+
concat!("color: white; padding: 0 3px; background: ", $color, ";");
20+
};
21+
};
22+
23+
Style {
24+
trace: bg_color!("gray"),
25+
debug: bg_color!("blue"),
26+
info: bg_color!("green"),
27+
warn: bg_color!("orange"),
28+
error: bg_color!("darkred"),
29+
file_line: "font-weight: bold; color: inherit",
30+
text: "background: inherit; color: inherit",
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)