Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use env_logger filters #33

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
22 changes: 18 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,8 @@ 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 level.
Expand All @@ -48,16 +50,28 @@ pub fn start() {
/// femme::with_level(log::LevelFilter::Trace);
/// ```
pub fn with_level(level: log::LevelFilter) {
let filter = Builder::new().filter_level(level).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(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