Skip to content

Commit

Permalink
Use env_logger filters
Browse files Browse the repository at this point in the history
  • Loading branch information
IcanDivideBy0 committed Oct 15, 2021
1 parent 94e5aa8 commit 6217832
Show file tree
Hide file tree
Showing 6 changed files with 174 additions and 24 deletions.
108 changes: 108 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ serde = "1.0.97"
serde_derive = "1.0.97"
serde_json = "1.0.56"
cfg-if = "0.1.9"
env_logger = "0.8.3"

[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "0.3.25", features = ["console"] }
Expand Down
34 changes: 30 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! log::info!("Listening on port 8080");
//! ```

use env_logger::filter::{Builder, Filter};
pub use log::LevelFilter;

#[cfg(not(target_arch = "wasm32"))]
Expand Down Expand Up @@ -36,7 +37,30 @@ mod wasm;
/// log::info!("Listening on port 8080");
/// ```
pub fn start() {
with_level(LevelFilter::Info);
let filter = Builder::from_env("RUST_LOG").build();
with_filter(filter);
}

/// Start logging with a log filter.
///
/// # Examples
/// ```
/// let filter = env_logger::filter::Builder::from_env("RUST_LOG").build();
/// femme::with_filter(filter);
/// ```
pub fn with_filter(filter: Filter) {
#[cfg(target_arch = "wasm32")]
wasm::start(filter);

#[cfg(not(target_arch = "wasm32"))]
{
// Use ndjson in release mode, pretty logging while debugging.
if cfg!(debug_assertions) {
pretty::start(filter);
} else {
ndjson::start(filter);
}
}
}

/// Start logging with a log level.
Expand All @@ -48,16 +72,18 @@ pub fn start() {
/// femme::with_level(log::LevelFilter::Trace);
/// ```
pub fn with_level(level: log::LevelFilter) {
let filter = Builder::new().filter_level(level).build();

#[cfg(target_arch = "wasm32")]
wasm::start(level);
wasm::start(filter);

#[cfg(not(target_arch = "wasm32"))]
{
// Use ndjson in release mode, pretty logging while debugging.
if cfg!(debug_assertions) {
pretty::start(level);
pretty::start(filter);
} else {
ndjson::start(level);
ndjson::start(filter);
}
}
}
25 changes: 17 additions & 8 deletions src/ndjson.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,40 @@
//! Print logs as ndjson.

use log::{kv, LevelFilter, Log, Metadata, Record};
use env_logger::filter::Filter;
use log::{kv, Log, Metadata, Record};
use std::io::{self, StdoutLock, Write};
use std::time;

/// Start logging.
pub(crate) fn start(level: LevelFilter) {
let logger = Box::new(Logger {});
pub(crate) fn start(filter: Filter) {
let max_level = filter.filter();
let logger = Box::new(Logger { filter });
log::set_boxed_logger(logger).expect("Could not start logging");
log::set_max_level(level);
log::set_max_level(max_level);
}

#[derive(Debug)]
pub(crate) struct Logger {}
pub(crate) struct Logger {
filter: Filter,
}

impl Log for Logger {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.level() <= log::max_level()
self.filter.enabled(metadata)
}

fn log(&self, record: &Record<'_>) {
if self.enabled(record.metadata()) {
if self.filter.matches(record) {
let stdout = io::stdout();
let mut handle = stdout.lock();
let level = get_level(record.level());
let time = time::UNIX_EPOCH.elapsed().unwrap().as_millis();
write!(&mut handle, "{{\"level\":{},\"time\":{},\"msg\":", level, time).unwrap();
write!(
&mut handle,
"{{\"level\":{},\"time\":{},\"msg\":",
level, time
)
.unwrap();
serde_json::to_writer(&mut handle, record.args()).unwrap();
format_kv_pairs(&mut handle, &record);
writeln!(&mut handle, "}}").unwrap();
Expand Down
18 changes: 11 additions & 7 deletions src/pretty.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Pretty print logs.

use log::{kv, Level, LevelFilter, Log, Metadata, Record};
use env_logger::filter::Filter;
use log::{kv, Level, Log, Metadata, Record};
use std::io::{self, StdoutLock, Write};

// ANSI term codes.
Expand All @@ -11,22 +12,25 @@ const GREEN: &'static str = "\x1b[32m";
const YELLOW: &'static str = "\x1b[33m";

/// Start logging.
pub(crate) fn start(level: LevelFilter) {
let logger = Box::new(Logger {});
pub(crate) fn start(filter: Filter) {
let max_level = filter.filter();
let logger = Box::new(Logger { filter });
log::set_boxed_logger(logger).expect("Could not start logging");
log::set_max_level(level);
log::set_max_level(max_level);
}

#[derive(Debug)]
pub(crate) struct Logger {}
pub(crate) struct Logger {
filter: Filter,
}

impl Log for Logger {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.level() <= log::max_level()
self.filter.enabled(metadata)
}

fn log(&self, record: &Record<'_>) {
if self.enabled(record.metadata()) {
if self.filter.matches(record) {
let stdout = io::stdout();
let mut handle = stdout.lock();
format_src(&mut handle, &record);
Expand Down
12 changes: 7 additions & 5 deletions src/wasm.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
//! Print logs as ndjson.

use env_logger::filter::Filter;
use js_sys::Object;
use log::{kv, Level, LevelFilter, Log, Metadata, Record};
use wasm_bindgen::prelude::*;

use std::collections::HashMap;

/// Start logging.
pub(crate) fn start(level: LevelFilter) {
let logger = Box::new(Logger {});
pub(crate) fn start(filter: Filter) {
let max_level = filter.filter();
let logger = Box::new(Logger { filter });
log::set_boxed_logger(logger).expect("Could not start logging");
log::set_max_level(level);
log::set_max_level(max_level);
}

#[derive(Debug)]
pub(crate) struct Logger {}

impl Log for Logger {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.level() <= log::max_level()
self.filter.enabled(metadata)
}

fn log(&self, record: &Record<'_>) {
if self.enabled(record.metadata()) {
if self.filter.matches(record) {
let args = format!("{}", record.args()).into();
let line = format_line(&record).into();

Expand Down

0 comments on commit 6217832

Please sign in to comment.