Skip to content

Commit

Permalink
improve: use the OnceLock api repalce the Once
Browse files Browse the repository at this point in the history
  • Loading branch information
Joinhack committed Apr 5, 2024
1 parent 4550290 commit 692c8e9
Showing 1 changed file with 12 additions and 19 deletions.
31 changes: 12 additions & 19 deletions bls-runtime/src/plog.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,36 @@
use std::{fmt::Arguments, sync::Once};
use std::{
fmt::Arguments, sync::OnceLock
};

use env_logger::Logger;
use log::{Level, Log, MetadataBuilder, Record};
use log::{
Level, Log, MetadataBuilder, Record
};

static mut ENV_LOGGER: Option<Logger> = None;
static mut ENV_LOGGER: OnceLock<Logger> = OnceLock::new();

/// The logger should only be set once in log crate by set_logger,
/// if set the console as output, can't be set the file as output.
/// Therefore, we need a logger where the console is set as output
/// before initializing the env_log by the configure file.
pub(crate) fn env_logger() -> Option<&'static mut Logger> {
static ONCE: Once = Once::new();
pub(crate) fn env_logger() -> &'static Logger {
unsafe {
ONCE.call_once(|| {
ENV_LOGGER.get_or_init(|| {
// the log metadata
let metadata = MetadataBuilder::new().build();
let mut builder = env_logger::Builder::from_default_env();
// set the console as output.
builder.target(Default::default());
let logger = builder.build();
logger.enabled(&metadata);
ENV_LOGGER = Some(logger);
});
ENV_LOGGER.as_mut()
logger
})
}
}

/// log info by level
pub fn plog(level: Level, args: Arguments<'_>) {
let record = Record::builder().args(args).level(level).build();
env_logger().map(|l| l.log(&record));
env_logger().log(&record)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_env_logger() {
assert_eq!(env_logger().is_some(), true);
}
}

0 comments on commit 692c8e9

Please sign in to comment.