Skip to main content

byteflow/
log.rs

1//! Host-side scheduler diagnostics on stderr, gated by `BYTEFLOW_LOG`.
2//!
3//! # Why this is separate from the `print` native
4//!
5//! Actor-visible logging (`CallNative print`) writes to **stdout** and is part
6//! of the program's observable behaviour — samples and demos use it to show
7//! envelopes crossing the mailbox. Scheduler diagnostics (spawn / send /
8//! park / finish) are an **operator** concern: they must not pollute stdout
9//! when an embedder pipes Flow output, and they must stay off by default
10//! so a production run is silent unless asked.
11//!
12//! ```text
13//! BYTEFLOW_LOG unset / 0 / off / false  → silent
14//! BYTEFLOW_LOG=1 / info / true          → spawn, send, receive, finish
15//! BYTEFLOW_LOG=debug / 2                → also park, deliver queued/handoff
16//! ```
17//!
18//! # `tracing` integration
19//!
20//! With the optional `tracing` feature, every diagnostic is also emitted as a
21//! [`tracing`](https://docs.rs/tracing) event with target `byteflow` (INFO or
22//! DEBUG), independent of `BYTEFLOW_LOG`. Filter it like any other target,
23//! e.g. `RUST_LOG=byteflow=debug` with `tracing-subscriber`. The default build
24//! does not depend on `tracing`.
25//!
26//! # Cost when disabled
27//!
28//! Call sites pass `format_args!(..)`, not `format!(..)`: nothing is
29//! formatted or allocated unless stderr, a [`LogSink`] or a `tracing`
30//! subscriber will actually receive the line. Message delivery logs on every
31//! hop, so this keeps the hot path allocation-free.
32//!
33//! # Lazy init
34//!
35//! The level is read from the environment once (first call) and cached in
36//! atomics. That avoids re-parsing `std::env` on every send in a hot worker
37//! loop. Tests can override via [`set_level_for_tests`].
38
39// Docs ratchet: public items here predate `missing_docs`. Delete this
40// allow once they are documented; new files get the lint by default.
41#![allow(missing_docs)]
42
43use std::sync::atomic::{AtomicU8, Ordering};
44use std::time::{SystemTime, UNIX_EPOCH};
45
46const OFF: u8 = 0;
47const INFO: u8 = 1;
48const DEBUG: u8 = 2;
49
50static LEVEL: AtomicU8 = AtomicU8::new(OFF);
51static INIT: AtomicU8 = AtomicU8::new(0);
52
53fn level() -> u8 {
54    if INIT.load(Ordering::Acquire) == 0 {
55        let parsed = match std::env::var("BYTEFLOW_LOG") {
56            Ok(v) => {
57                let v = v.trim().to_ascii_lowercase();
58                match v.as_str() {
59                    "" | "0" | "off" | "false" | "no" => OFF,
60                    "debug" | "trace" | "2" => DEBUG,
61                    // "1", "info", "true", "yes", or any other non-empty token
62                    _ => INFO,
63                }
64            }
65            Err(_) => OFF,
66        };
67        LEVEL.store(parsed, Ordering::Release);
68        INIT.store(1, Ordering::Release);
69    }
70    LEVEL.load(Ordering::Acquire)
71}
72
73fn stamp_ms() -> u64 {
74    // Logging must never panic: a broken clock just prints epoch-ish 0.
75    match SystemTime::now().duration_since(UNIX_EPOCH) {
76        Ok(d) => d.as_millis() as u64,
77        Err(_) => 0,
78    }
79}
80
81/// Override the cached level (tests only). `0` off, `1` info, `2` debug.
82pub fn set_level_for_tests(level: u8) {
83    LEVEL.store(level.min(DEBUG), Ordering::Release);
84    INIT.store(1, Ordering::Release);
85}
86
87/// INFO-level line when [`BYTEFLOW_LOG`](crate::log) is at least `info`.
88#[inline]
89pub fn info(msg: impl std::fmt::Display) {
90    forward(None, INFO, "INFO ", msg);
91}
92
93/// DEBUG-level line when [`BYTEFLOW_LOG`](crate::log) is `debug`.
94#[inline]
95pub fn debug(msg: impl std::fmt::Display) {
96    forward(None, DEBUG, "DEBUG", msg);
97}
98
99/// Is a `tracing` subscriber interested in this level for target `byteflow`?
100#[cfg(feature = "tracing")]
101fn tracing_enabled(min: u8) -> bool {
102    if min >= DEBUG {
103        tracing::enabled!(target: "byteflow", tracing::Level::DEBUG)
104    } else {
105        tracing::enabled!(target: "byteflow", tracing::Level::INFO)
106    }
107}
108
109#[cfg(not(feature = "tracing"))]
110#[inline(always)]
111fn tracing_enabled(_min: u8) -> bool {
112    false
113}
114
115#[cfg(feature = "tracing")]
116fn emit_tracing(min: u8, msg: &dyn std::fmt::Display) {
117    if min >= DEBUG {
118        tracing::debug!(target: "byteflow", "{msg}");
119    } else {
120        tracing::info!(target: "byteflow", "{msg}");
121    }
122}
123
124#[cfg(not(feature = "tracing"))]
125#[inline(always)]
126fn emit_tracing(_min: u8, _msg: &dyn std::fmt::Display) {}
127
128/// A collector refused or dropped one diagnostic line.
129///
130/// The runtime ignores this. The flow keeps its original outcome.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub struct LogRecordError;
133
134impl std::fmt::Display for LogRecordError {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        f.write_str("log sink rejected the line")
137    }
138}
139
140impl std::error::Error for LogRecordError {}
141
142/// Receives the diagnostic line that would be written to stderr.
143///
144/// `try_record` runs on the worker that emitted the event. It must return
145/// promptly and must not panic. [`Err`] is ignored: a collector failure does
146/// not fail the flow. There is no queue inside the runtime.
147pub trait LogSink: Send + Sync + std::fmt::Debug + 'static {
148    fn try_record(&self, line: &str) -> Result<(), LogRecordError>;
149}
150
151pub(crate) fn info_sink(sink: Option<&std::sync::Arc<dyn LogSink>>, msg: impl std::fmt::Display) {
152    forward(sink, INFO, "INFO ", msg);
153}
154
155pub(crate) fn debug_sink(sink: Option<&std::sync::Arc<dyn LogSink>>, msg: impl std::fmt::Display) {
156    forward(sink, DEBUG, "DEBUG", msg);
157}
158
159fn forward(
160    sink: Option<&std::sync::Arc<dyn LogSink>>,
161    min: u8,
162    label: &str,
163    msg: impl std::fmt::Display,
164) {
165    let show = level() >= min;
166    let traced = tracing_enabled(min);
167    if !show && sink.is_none() && !traced {
168        // Common case: nobody listens, so `msg` is never formatted.
169        return;
170    }
171    if traced {
172        emit_tracing(min, &msg);
173    }
174    if !show && sink.is_none() {
175        return;
176    }
177    let line = format!("[{}] byteflow {label} {msg}", stamp_ms());
178    if show {
179        eprintln!("{line}");
180    }
181    if let Some(sink) = sink {
182        let _ = sink.try_record(&line);
183    }
184}