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

feat: add try_start() and try_with_level() #22

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
77 changes: 69 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
//! log::info!("Listening on port 8080");
//! ```

use log::SetLoggerError;

pub use log::LevelFilter;

#[cfg(not(target_arch = "wasm32"))]
Expand All @@ -22,42 +24,101 @@ mod wasm;

/// Starts logging depending on current environment.
///
/// # Log output
/// ## Log output
///
/// - when compiling with `--release` uses ndjson.
/// - pretty-prints otherwise.
/// - works in WASM out of the box.
///
/// # Examples
/// ## Examples
///
/// ```
/// femme::start();
/// log::warn!("Unauthorized access attempt on /login");
/// log::info!("Listening on port 8080");
/// ```
///
/// ## Panics
///
/// This function will panic if it is called more than once, or if another library has already initialized a global logger.
///
pub fn start() {
with_level(LevelFilter::Info);
with_level(LevelFilter::Info)
}

/// Starts logging depending on current environment.
///
/// ## Log output
///
/// - when compiling with `--release` uses ndjson.
/// - pretty-prints otherwise.
/// - works in WASM out of the box.
///
/// ## Examples
///
/// ```
/// femme::try_start().ok(); // Handle Result or ignore
/// log::warn!("Unauthorized access attempt on /login");
/// log::info!("Listening on port 8080");
/// ```
///
/// ## Errors
///
/// This function will fail if it is called more than once, or if another library has already initialized a global logger.
///
pub fn try_start() -> Result<(), SetLoggerError> {
try_with_level(LevelFilter::Info)
}

/// Start logging with a log level.
///
/// All messages under the specified log level will statically be filtered out.
///
/// # Examples
/// ## Examples
///
/// ```
/// femme::with_level(log::LevelFilter::Trace);
/// femme::with_level(log::LevelFilter::Warn);
/// log::warn!("Unauthorized access attempt on /login");
/// log::info!("Listening on port 8080"); // Will be hidden
/// ```
///
/// ## Panics
///
/// This function will panic if it is called more than once, or if another library has already initialized a global logger.
///
pub fn with_level(level: log::LevelFilter) {
try_with_level(level).expect("Could not start logging")
}

/// Start logging with a log level.
///
/// All messages under the specified log level will statically be filtered out.
///
/// ## Examples
///
/// ```
/// femme::try_with_level(log::LevelFilter::Warn).ok(); // Handle Result or ignore
/// log::warn!("Unauthorized access attempt on /login");
/// log::info!("Listening on port 8080"); // Will be hidden
/// ```
///
/// ## Errors
///
/// This function will fail if it is called more than once, or if another library has already initialized a global logger.
///
pub fn try_with_level(level: log::LevelFilter) -> Result<(), SetLoggerError> {
#[cfg(target_arch = "wasm32")]
wasm::start(level);
wasm::start(level)?;

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

Ok(())
}
7 changes: 4 additions & 3 deletions src/ndjson.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
//! Print logs as ndjson.

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

/// Start logging.
pub(crate) fn start(level: LevelFilter) {
pub(crate) fn start(level: LevelFilter) -> Result<(), SetLoggerError> {
let logger = Box::new(Logger {});
log::set_boxed_logger(logger).expect("Could not start logging");
log::set_boxed_logger(logger)?;
log::set_max_level(level);
Ok(())
}

#[derive(Debug)]
Expand Down
7 changes: 4 additions & 3 deletions src/pretty.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Pretty print logs.

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

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

/// Start logging.
pub(crate) fn start(level: LevelFilter) {
pub(crate) fn start(level: LevelFilter) -> Result<(), SetLoggerError> {
let logger = Box::new(Logger {});
log::set_boxed_logger(logger).expect("Could not start logging");
log::set_boxed_logger(logger)?;
log::set_max_level(level);
Ok(())
}

#[derive(Debug)]
Expand Down
7 changes: 4 additions & 3 deletions src/wasm.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
//! Print logs as ndjson.

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

use std::collections::HashMap;

/// Start logging.
pub(crate) fn start(level: LevelFilter) {
pub(crate) fn start(level: LevelFilter) -> Result<(), SetLoggerError> {
let logger = Box::new(Logger {});
log::set_boxed_logger(logger).expect("Could not start logging");
log::set_boxed_logger(logger)?;
log::set_max_level(level);
Ok(())
}

#[derive(Debug)]
Expand Down