Skip to content

Commit

Permalink
get rid of custom log filtering implementations
Browse files Browse the repository at this point in the history
Signed-off-by: ozkanonur <work@onurozkan.dev>
  • Loading branch information
onur-ozkan committed Mar 18, 2023
1 parent 1bfd6b5 commit ed5c72b
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 246 deletions.
104 changes: 15 additions & 89 deletions mm2src/common/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use chrono::{Local, TimeZone, Utc};
use crossbeam::queue::SegQueue;
use itertools::Itertools;
#[cfg(not(target_arch = "wasm32"))]
use lightning::util::logger::{Level as LightningLevel, Logger as LightningLogger, Record as LightningRecord};
use log::{Level, Record};
use lightning::util::logger::{Logger as LightningLogger, Record as LightningRecord};
use log::Record;
use parking_lot::Mutex as PaMutex;
use serde_json::Value as Json;
use std::cell::RefCell;
Expand All @@ -23,7 +23,6 @@ use std::hash::{Hash, Hasher};
use std::mem::swap;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Weak};
use std::thread;
Expand All @@ -35,14 +34,14 @@ pub use log::{self as log_crate, debug, error, info, trace, warn, LevelFilter};
pub mod wasm_log;

#[cfg(target_arch = "wasm32")]
pub use wasm_log::{LogLevel, WasmCallback, WasmLoggerBuilder};
pub use wasm_log::{WasmCallback, WasmLoggerBuilder};

#[cfg(not(target_arch = "wasm32"))]
#[path = "log/native_log.rs"]
mod native_log;

#[cfg(not(target_arch = "wasm32"))]
pub use native_log::{FfiCallback, LogLevel, UnifiedLoggerBuilder};
pub use native_log::{FfiCallback, UnifiedLoggerBuilder};

lazy_static! {
/// If this C callback is present then all the logging output should happen through it
Expand All @@ -54,7 +53,7 @@ lazy_static! {
pub type LogCallbackBoxed = Box<dyn LogCallback>;

pub trait LogCallback: Send + Sync + 'static {
fn callback(&mut self, level: LogLevel, line: String);
fn callback(&mut self, line: String);

fn into_boxed(self) -> LogCallbackBoxed
where
Expand Down Expand Up @@ -118,9 +117,9 @@ thread_local! {
}

#[doc(hidden)]
pub fn chunk2log(mut chunk: String, level: LogLevel) {
pub fn chunk2log(mut chunk: String) {
let used_log_callback = if let Some(ref mut log_cb) = *LOG_CALLBACK.lock() {
log_cb.callback(level, chunk.clone());
log_cb.callback(chunk.clone());
true
} else {
false
Expand Down Expand Up @@ -179,7 +178,7 @@ macro_rules! log {
let file = $crate::filename(file!());
let msg = format!($($args)+);
let chunk = format!("{}, {}:{}] {}", time, file, line!(), msg);
$crate::log::chunk2log(chunk, $crate::log::LogLevel::Info)
$crate::log::chunk2log(chunk)
}}
}

Expand Down Expand Up @@ -440,7 +439,7 @@ impl Status {
tail.push_back(log);
}

chunk2log(chunk, LogLevel::Info)
chunk2log(chunk)
}
}

Expand Down Expand Up @@ -601,8 +600,6 @@ pub struct LogState {
/// (this thread becomes a center of gravity for the other registered threads).
/// In the future we might also use `gravity` to log into a file.
gravity: PaMutex<Option<Arc<Gravity>>>,
/// Keeps track of the log level that the log state is initiated with
level: LogLevel,
/// `log_dashboard_sometimes` abort handle if it has been spawned.
_dashboard_abort_handle: Option<AbortOnDropHandle>,
}
Expand Down Expand Up @@ -709,7 +706,7 @@ fn log_dashboard_sometimesʹ(dashboard: Vec<Arc<Status>>, dl: &mut DashboardLogg
passed_str, timeframe_str, tags_str, line
));
}
chunk2log(buf, LogLevel::Info)
chunk2log(buf)
}

async fn log_dashboard_sometimes(dashboardʷ: Weak<PaMutex<Vec<Arc<Status>>>>) {
Expand All @@ -733,7 +730,6 @@ impl LogState {
dashboard: Arc::new(PaMutex::new(Vec::new())),
tail: Arc::new(PaMutex::new(VecDeque::with_capacity(64))),
gravity: PaMutex::new(None),
level: LogLevel::default(),
_dashboard_abort_handle: None,
}
}
Expand All @@ -747,13 +743,10 @@ impl LogState {
dashboard,
tail: Arc::new(PaMutex::new(VecDeque::with_capacity(64))),
gravity: PaMutex::new(None),
level: LogLevel::default(),
_dashboard_abort_handle: Some(abort_handle),
}
}

pub fn set_level(&mut self, level: LogLevel) { self.level = level; }

/// The operation is considered "in progress" while the `StatusHandle` exists.
///
/// When the `StatusHandle` is dropped the operation is considered "finished" (possibly with a failure)
Expand Down Expand Up @@ -905,13 +898,11 @@ impl LogState {
tail.push_back(entry);
}

self.chunk2log(chunk, self.level)
self.chunk2log(chunk)
}

fn chunk2log(&self, chunk: String, level: LogLevel) {
if self.level.ge(&level) {
self::chunk2log(chunk, level);
}
fn chunk2log(&self, chunk: String) {
self::chunk2log(chunk);
/*
match self.log_file {
Some (ref f) => match f.lock() {
Expand All @@ -934,7 +925,7 @@ impl LogState {
/// Writes into the *raw* portion of the log, the one not shared with the UI.
pub fn rawln(&self, mut line: String) {
line.push('\n');
self.chunk2log(line, self.level);
self.chunk2log(line);
}

/// Binds the logger to the current thread,
Expand Down Expand Up @@ -984,25 +975,15 @@ impl LogState {
#[cfg(not(target_arch = "wasm32"))]
impl LightningLogger for LogState {
fn log(&self, record: &LightningRecord) {
let level = match record.level {
LightningLevel::Gossip => Level::Trace,
LightningLevel::Trace => Level::Debug,
LightningLevel::Debug => Level::Debug,
LightningLevel::Info => Level::Info,
LightningLevel::Warn => Level::Warn,
LightningLevel::Error => Level::Error,
};
let record = Record::builder()
.args(record.args)
.level(level)
.target("mm_log")
.module_path(Some(record.module_path))
.file(Some(record.file))
.line(Some(record.line))
.build();
let as_string = format_record(&record);
let level = LogLevel::from(record.metadata().level());
self.chunk2log(as_string, level);
self.chunk2log(as_string);
}
}

Expand Down Expand Up @@ -1034,61 +1015,6 @@ impl Drop for LogState {
#[derive(Debug)]
pub struct UnknownLogLevel(String);

impl FromStr for LogLevel {
type Err = UnknownLogLevel;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"off" => Ok(LogLevel::Off),
"error" => Ok(LogLevel::Error),
"warn" => Ok(LogLevel::Warn),
"info" => Ok(LogLevel::Info),
"debug" => Ok(LogLevel::Debug),
"trace" => Ok(LogLevel::Trace),
_ => Err(UnknownLogLevel(s.to_owned())),
}
}
}

impl From<Level> for LogLevel {
fn from(orig: Level) -> Self {
match orig {
Level::Error => LogLevel::Error,
Level::Warn => LogLevel::Warn,
Level::Info => LogLevel::Info,
Level::Debug => LogLevel::Debug,
Level::Trace => LogLevel::Trace,
}
}
}

impl From<LogLevel> for LevelFilter {
fn from(level: LogLevel) -> Self {
match level {
LogLevel::Off => LevelFilter::Off,
LogLevel::Error => LevelFilter::Error,
LogLevel::Warn => LevelFilter::Warn,
LogLevel::Info => LevelFilter::Info,
LogLevel::Debug => LevelFilter::Debug,
LogLevel::Trace => LevelFilter::Trace,
}
}
}

impl fmt::Display for LogLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let level = match self {
LogLevel::Off => "OFF",
LogLevel::Error => "ERROR",
LogLevel::Warn => "WARN",
LogLevel::Info => "INFO",
LogLevel::Debug => "DEBUG",
LogLevel::Trace => "TRACE",
};
write!(f, "{}", level)
}
}

/// It's the temporary `log::Record` formatter.
/// Format: `{d(%d %H:%M:%S)(utc)}, {f}:{L}] {l} {m}`
pub fn format_record(record: &Record) -> String {
Expand Down
44 changes: 4 additions & 40 deletions mm2src/common/log/native_log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,8 @@ use log::Record;
use log4rs::encode::pattern;
use log4rs::{append, config};
use std::os::raw::c_char;
use std::str::FromStr;

const DEFAULT_CONSOLE_FORMAT: &str = "[{d(%Y-%m-%d %H:%M:%S %Z)(utc)} {h({l})} {M}:{f}:{L}] {m}\n";
const DEFAULT_LEVEL_FILTER: LogLevel = LogLevel::Info;

#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub enum LogLevel {
/// A level lower than all log levels.
Off = 0,
/// Corresponds to the `ERROR` log level.
Error = 1,
/// Corresponds to the `WARN` log level.
Warn = 2,
/// Corresponds to the `INFO` log level.
Info = 3,
/// Corresponds to the `DEBUG` log level.
Debug = 4,
/// Corresponds to the `TRACE` log level.
Trace = 5,
}

impl LogLevel {
pub fn from_env() -> Option<LogLevel> {
let env_val = std::env::var("RUST_LOG").ok()?;
LogLevel::from_str(&env_val).ok()
}
}

impl Default for LogLevel {
fn default() -> Self { DEFAULT_LEVEL_FILTER }
}

pub struct FfiCallback {
cb_f: extern "C" fn(line: *const c_char),
Expand All @@ -46,15 +17,14 @@ impl FfiCallback {
}

impl LogCallback for FfiCallback {
fn callback(&mut self, _level: LogLevel, mut line: String) {
fn callback(&mut self, mut line: String) {
line.push('\0');
(self.cb_f)(line.as_ptr() as *const c_char)
}
}

pub struct UnifiedLoggerBuilder {
console_format: String,
filter: LogLevel,
console: bool,
mm_log: bool,
}
Expand All @@ -63,7 +33,6 @@ impl Default for UnifiedLoggerBuilder {
fn default() -> UnifiedLoggerBuilder {
UnifiedLoggerBuilder {
console_format: DEFAULT_CONSOLE_FORMAT.to_owned(),
filter: LogLevel::default(),
console: true,
mm_log: false,
}
Expand All @@ -78,11 +47,6 @@ impl UnifiedLoggerBuilder {
self
}

pub fn level_filter(mut self, filter: LogLevel) -> UnifiedLoggerBuilder {
self.filter = filter;
self
}

pub fn console(mut self, console: bool) -> UnifiedLoggerBuilder {
self.console = console;
self
Expand Down Expand Up @@ -112,7 +76,8 @@ impl UnifiedLoggerBuilder {
let app_names: Vec<_> = appenders.iter().map(|app| app.name()).collect();
let root = config::Root::builder()
.appenders(app_names)
.build(LevelFilter::from(self.filter));
// .build(LevelFilter::from(self.filter));
.build(LevelFilter::Debug);
let config = try_s!(config::Config::builder().appenders(appenders).build(root));

try_s!(log4rs::init_config(config));
Expand All @@ -126,8 +91,7 @@ struct MmLogAppender;
impl append::Append for MmLogAppender {
fn append(&self, record: &Record) -> anyhow::Result<()> {
let as_string = format_record(record);
let level = LogLevel::from(record.metadata().level());
chunk2log(as_string, level);
chunk2log(as_string);
Ok(())
}

Expand Down
Loading

0 comments on commit ed5c72b

Please sign in to comment.