1use std::sync::atomic::{AtomicU8, Ordering};
25use std::time::{SystemTime, UNIX_EPOCH};
26
27const OFF: u8 = 0;
28const INFO: u8 = 1;
29const DEBUG: u8 = 2;
30
31static LEVEL: AtomicU8 = AtomicU8::new(OFF);
32static INIT: AtomicU8 = AtomicU8::new(0);
33
34fn level() -> u8 {
35 if INIT.load(Ordering::Acquire) == 0 {
36 let parsed = match std::env::var("BYTEFLOW_LOG") {
37 Ok(v) => {
38 let v = v.trim().to_ascii_lowercase();
39 match v.as_str() {
40 "" | "0" | "off" | "false" | "no" => OFF,
41 "debug" | "trace" | "2" => DEBUG,
42 _ => INFO,
44 }
45 }
46 Err(_) => OFF,
47 };
48 LEVEL.store(parsed, Ordering::Release);
49 INIT.store(1, Ordering::Release);
50 }
51 LEVEL.load(Ordering::Acquire)
52}
53
54fn stamp_ms() -> u64 {
55 match SystemTime::now().duration_since(UNIX_EPOCH) {
57 Ok(d) => d.as_millis() as u64,
58 Err(_) => 0,
59 }
60}
61
62pub fn set_level_for_tests(level: u8) {
64 LEVEL.store(level.min(DEBUG), Ordering::Release);
65 INIT.store(1, Ordering::Release);
66}
67
68#[inline]
70pub fn info(msg: impl std::fmt::Display) {
71 if level() >= INFO {
72 eprintln!("[{}] byteflow INFO {}", stamp_ms(), msg);
73 }
74}
75
76#[inline]
78pub fn debug(msg: impl std::fmt::Display) {
79 if level() >= DEBUG {
80 eprintln!("[{}] byteflow DEBUG {}", stamp_ms(), msg);
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct LogRecordError;
89
90impl std::fmt::Display for LogRecordError {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 f.write_str("log sink rejected the line")
93 }
94}
95
96impl std::error::Error for LogRecordError {}
97
98pub trait LogSink: Send + Sync + std::fmt::Debug + 'static {
104 fn try_record(&self, line: &str) -> Result<(), LogRecordError>;
105}
106
107pub(crate) fn info_sink(sink: Option<&std::sync::Arc<dyn LogSink>>, msg: impl std::fmt::Display) {
108 forward(sink, INFO, "INFO ", msg);
109}
110
111pub(crate) fn debug_sink(sink: Option<&std::sync::Arc<dyn LogSink>>, msg: impl std::fmt::Display) {
112 forward(sink, DEBUG, "DEBUG", msg);
113}
114
115fn forward(
116 sink: Option<&std::sync::Arc<dyn LogSink>>,
117 min: u8,
118 label: &str,
119 msg: impl std::fmt::Display,
120) {
121 let show = level() >= min;
122 if !show && sink.is_none() {
123 return;
124 }
125 let line = format!("[{}] byteflow {label} {msg}", stamp_ms());
126 if show {
127 eprintln!("{line}");
128 }
129 if let Some(sink) = sink {
130 let _ = sink.try_record(&line);
131 }
132}