#![allow(missing_docs)]
use std::sync::atomic::{AtomicU8, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
const OFF: u8 = 0;
const INFO: u8 = 1;
const DEBUG: u8 = 2;
static LEVEL: AtomicU8 = AtomicU8::new(OFF);
static INIT: AtomicU8 = AtomicU8::new(0);
fn level() -> u8 {
if INIT.load(Ordering::Acquire) == 0 {
let parsed = match std::env::var("BYTEFLOW_LOG") {
Ok(v) => {
let v = v.trim().to_ascii_lowercase();
match v.as_str() {
"" | "0" | "off" | "false" | "no" => OFF,
"debug" | "trace" | "2" => DEBUG,
_ => INFO,
}
}
Err(_) => OFF,
};
LEVEL.store(parsed, Ordering::Release);
INIT.store(1, Ordering::Release);
}
LEVEL.load(Ordering::Acquire)
}
fn stamp_ms() -> u64 {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(d) => d.as_millis() as u64,
Err(_) => 0,
}
}
pub fn set_level_for_tests(level: u8) {
LEVEL.store(level.min(DEBUG), Ordering::Release);
INIT.store(1, Ordering::Release);
}
#[inline]
pub fn info(msg: impl std::fmt::Display) {
forward(None, INFO, "INFO ", msg);
}
#[inline]
pub fn debug(msg: impl std::fmt::Display) {
forward(None, DEBUG, "DEBUG", msg);
}
#[cfg(feature = "tracing")]
fn tracing_enabled(min: u8) -> bool {
if min >= DEBUG {
tracing::enabled!(target: "byteflow", tracing::Level::DEBUG)
} else {
tracing::enabled!(target: "byteflow", tracing::Level::INFO)
}
}
#[cfg(not(feature = "tracing"))]
#[inline(always)]
fn tracing_enabled(_min: u8) -> bool {
false
}
#[cfg(feature = "tracing")]
fn emit_tracing(min: u8, msg: &dyn std::fmt::Display) {
if min >= DEBUG {
tracing::debug!(target: "byteflow", "{msg}");
} else {
tracing::info!(target: "byteflow", "{msg}");
}
}
#[cfg(not(feature = "tracing"))]
#[inline(always)]
fn emit_tracing(_min: u8, _msg: &dyn std::fmt::Display) {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LogRecordError;
impl std::fmt::Display for LogRecordError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("log sink rejected the line")
}
}
impl std::error::Error for LogRecordError {}
pub trait LogSink: Send + Sync + std::fmt::Debug + 'static {
fn try_record(&self, line: &str) -> Result<(), LogRecordError>;
}
pub(crate) fn info_sink(sink: Option<&std::sync::Arc<dyn LogSink>>, msg: impl std::fmt::Display) {
forward(sink, INFO, "INFO ", msg);
}
pub(crate) fn debug_sink(sink: Option<&std::sync::Arc<dyn LogSink>>, msg: impl std::fmt::Display) {
forward(sink, DEBUG, "DEBUG", msg);
}
fn forward(
sink: Option<&std::sync::Arc<dyn LogSink>>,
min: u8,
label: &str,
msg: impl std::fmt::Display,
) {
let show = level() >= min;
let traced = tracing_enabled(min);
if !show && sink.is_none() && !traced {
return;
}
if traced {
emit_tracing(min, &msg);
}
if !show && sink.is_none() {
return;
}
let line = format!("[{}] byteflow {label} {msg}", stamp_ms());
if show {
eprintln!("{line}");
}
if let Some(sink) = sink {
let _ = sink.try_record(&line);
}
}