Skip to main content

egui_pop_platform/
logs.rs

1//! Logs to a file in the platform's log directory, rotated by size, at
2//! a level the user sets.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! [`Logs`] is a sink for the `log` facade (egui-pop and most crates log
8//! through it): each line goes to `<dir>/<name>.log` and to a tail kept
9//! in memory (what a crash report quotes). When the file passes its
10//! size, it becomes `<name>.1.log` (the older ones shift, the oldest
11//! beyond [`Logs::keep`] goes) and a new one starts.
12//!
13//! [`LogsPlugin`] installs it as the process's logger (the router is
14//! installed once; another plugin instance takes it over; with
15//! [`LogsPlugin::install`] off, it stays the app's own), declares the
16//! `developer.log_level` setting (`error`, `warn`, `info`, `debug`,
17//! `trace`), the `logs.reveal` command (opens the folder) and the `logs`
18//! debug collector (the file, the level, the tail). An application on
19//! `tracing` or another logger feeds lines with [`Logs::write`].
20//!
21//! No step runs per line: a line is written from whatever thread logs
22//! it, and steps run on the interface thread. The crash report
23//! (`crash`) is where the logs reach the application's hooks.
24//!
25//! Owned rather than tracing-appender (MIT): it rotates by time, writes
26//! through tracing's subscriber, and keeps no tail to quote; this is a
27//! hundred lines over `std::fs`.
28//!
29//! ```
30//! use egui_pop_platform::logs::Logs;
31//!
32//! let dir = std::env::temp_dir().join(format!("egui-pop-logs-doc-{}", std::process::id()));
33//! let logs = Logs::new(&dir, "demo").max_size(200).keep(2);
34//! for i in 0..20 {
35//!     logs.write(log::Level::Info, "demo", &format!("line {i}"));
36//! }
37//! assert!(logs.tail().last().unwrap().ends_with("INFO  demo: line 19"));
38//! assert!(dir.join("demo.1.log").exists());
39//! assert!(!dir.join("demo.3.log").exists());
40//! # std::fs::remove_dir_all(&dir).unwrap();
41//! ```
42
43use std::collections::VecDeque;
44use std::fs::{File, OpenOptions};
45use std::io::Write as _;
46use std::path::{Path, PathBuf};
47use std::sync::atomic::{AtomicUsize, Ordering};
48use std::sync::{Arc, Mutex, RwLock};
49
50use egui_pop_api::services::ServiceToken;
51use egui_pop_api::{Ctx, Plugin, PluginError};
52use egui_pop_core::debug::FnCollector;
53use egui_pop_core::lock;
54use egui_pop_model::commands::CommandSpec;
55use egui_pop_model::ids::{CommandId, PluginId, SettingId};
56use egui_pop_model::values::{Descriptor, Value};
57pub use log::{Level, LevelFilter};
58use serde_json::json;
59
60/// The plugin's id.
61pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.logs");
62/// The level written: `error`, `warn`, `info`, `debug`, `trace`.
63pub const SETTING_LEVEL: SettingId = SettingId::from_static("developer.log_level");
64/// Opens the log folder.
65pub const CMD_REVEAL: CommandId = CommandId::from_static("logs.reveal");
66/// The logs, as a service.
67pub const LOGS: ServiceToken<Logs> = ServiceToken::new("platform.logs");
68/// How many lines the tail keeps.
69pub const TAIL: usize = 200;
70/// The levels, as the setting stores them.
71pub const LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"];
72
73struct Inner {
74    path: PathBuf,
75    max_size: u64,
76    keep: usize,
77    file: Mutex<Option<(File, u64)>>,
78    tail: Mutex<VecDeque<String>>,
79    level: AtomicUsize,
80}
81
82/// A log file and its tail. Cheap to clone (shared).
83#[derive(Clone)]
84pub struct Logs(Arc<Inner>);
85
86impl std::fmt::Debug for Logs {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        f.debug_struct("Logs")
89            .field("path", &self.0.path)
90            .field("level", &self.level())
91            .finish_non_exhaustive()
92    }
93}
94
95fn level_index(l: LevelFilter) -> usize {
96    l as usize
97}
98
99fn level_of(i: usize) -> LevelFilter {
100    LevelFilter::iter().nth(i).unwrap_or(LevelFilter::Info)
101}
102
103/// A level as the setting names it.
104pub fn parse_level(text: &str) -> Option<LevelFilter> {
105    match text {
106        "off" => Some(LevelFilter::Off),
107        "error" => Some(LevelFilter::Error),
108        "warn" => Some(LevelFilter::Warn),
109        "info" => Some(LevelFilter::Info),
110        "debug" => Some(LevelFilter::Debug),
111        "trace" => Some(LevelFilter::Trace),
112        _ => None,
113    }
114}
115
116/// `2026-10-12T14:03:07.123Z` for a time since the epoch.
117pub fn timestamp(since_epoch: std::time::Duration) -> String {
118    let secs = since_epoch.as_secs();
119    let (days, rest) = (secs / 86_400, secs % 86_400);
120    // Days to a civil date (Howard Hinnant's algorithm).
121    let z = days as i64 + 719_468;
122    let era = z.div_euclid(146_097);
123    let doe = z.rem_euclid(146_097);
124    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
125    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
126    let mp = (5 * doy + 2) / 153;
127    let d = doy - (153 * mp + 2) / 5 + 1;
128    let m = if mp < 10 { mp + 3 } else { mp - 9 };
129    let y = yoe + era * 400 + i64::from(m <= 2);
130    format!(
131        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z",
132        rest / 3_600,
133        rest / 60 % 60,
134        rest % 60,
135        since_epoch.subsec_millis()
136    )
137}
138
139/// Now, as [`timestamp`] writes it (the browser's clock on the web,
140/// where `std::time::SystemTime::now` panics).
141pub fn now() -> String {
142    timestamp(
143        web_time::SystemTime::now()
144            .duration_since(web_time::UNIX_EPOCH)
145            .unwrap_or_default(),
146    )
147}
148
149impl Logs {
150    /// Logs to `<dir>/<name>.log` (the directory is made on the first
151    /// line), at `info`, 5 MiB per file, 3 older files kept.
152    pub fn new(dir: impl AsRef<Path>, name: &str) -> Logs {
153        Logs(Arc::new(Inner {
154            path: dir.as_ref().join(format!("{name}.log")),
155            max_size: 5 * 1024 * 1024,
156            keep: 3,
157            file: Mutex::new(None),
158            tail: Mutex::new(VecDeque::new()),
159            level: AtomicUsize::new(level_index(LevelFilter::Info)),
160        }))
161    }
162
163    fn with(self, f: impl FnOnce(&mut Inner)) -> Logs {
164        let mut inner = Arc::try_unwrap(self.0).unwrap_or_else(|shared| Inner {
165            path: shared.path.clone(),
166            max_size: shared.max_size,
167            keep: shared.keep,
168            file: Mutex::new(None),
169            tail: Mutex::new(lock(&shared.tail).clone()),
170            level: AtomicUsize::new(shared.level.load(Ordering::Relaxed)),
171        });
172        f(&mut inner);
173        Logs(Arc::new(inner))
174    }
175
176    /// The size a file grows to before it is rotated.
177    pub fn max_size(self, bytes: u64) -> Logs {
178        self.with(|i| i.max_size = bytes.max(1))
179    }
180
181    /// How many older files are kept.
182    pub fn keep(self, files: usize) -> Logs {
183        self.with(|i| i.keep = files)
184    }
185
186    /// The file written now.
187    pub fn path(&self) -> &Path {
188        &self.0.path
189    }
190
191    /// The directory of the files.
192    pub fn dir(&self) -> &Path {
193        self.0.path.parent().unwrap_or(Path::new("."))
194    }
195
196    pub fn level(&self) -> LevelFilter {
197        level_of(self.0.level.load(Ordering::Relaxed))
198    }
199
200    /// Sets the level written (and the `log` facade's, when installed).
201    pub fn set_level(&self, level: LevelFilter) {
202        self.0.level.store(level_index(level), Ordering::Relaxed);
203        if installed().is_some_and(|l| Arc::ptr_eq(&l.0, &self.0)) {
204            log::set_max_level(level);
205        }
206    }
207
208    /// The last lines written, oldest first.
209    pub fn tail(&self) -> Vec<String> {
210        lock(&self.0.tail).iter().cloned().collect()
211    }
212
213    /// Writes a line, if its level passes: to the file (rotated when
214    /// full) and the tail. A failing file is given up silently (the
215    /// tail stays).
216    pub fn write(&self, level: Level, target: &str, message: &str) {
217        if level > self.level() {
218            return;
219        }
220        let line = format!("{} {:<5} {target}: {message}", now(), level);
221        {
222            let mut tail = lock(&self.0.tail);
223            tail.push_back(line.clone());
224            while tail.len() > TAIL {
225                tail.pop_front();
226            }
227        }
228        let mut file = lock(&self.0.file);
229        if file
230            .as_ref()
231            .is_some_and(|(_, size)| *size + line.len() as u64 + 1 > self.0.max_size)
232        {
233            *file = None;
234            self.rotate();
235        }
236        if file.is_none() {
237            let _ = std::fs::create_dir_all(self.dir());
238            *file = OpenOptions::new()
239                .create(true)
240                .append(true)
241                .open(&self.0.path)
242                .ok()
243                .map(|f| {
244                    let size = f.metadata().map(|m| m.len()).unwrap_or(0);
245                    (f, size)
246                });
247        }
248        if let Some((f, size)) = file.as_mut()
249            && writeln!(f, "{line}").is_ok()
250        {
251            *size += line.len() as u64 + 1;
252        }
253    }
254
255    /// `<name>.log` becomes `<name>.1.log`, the older ones shift.
256    fn rotate(&self) {
257        let numbered = |n: usize| {
258            let stem = self
259                .0
260                .path
261                .file_stem()
262                .map(|s| s.to_string_lossy().into_owned())
263                .unwrap_or_default();
264            self.dir().join(format!("{stem}.{n}.log"))
265        };
266        if self.0.keep == 0 {
267            let _ = std::fs::remove_file(&self.0.path);
268            return;
269        }
270        let _ = std::fs::remove_file(numbered(self.0.keep));
271        for n in (1..self.0.keep).rev() {
272            let _ = std::fs::rename(numbered(n), numbered(n + 1));
273        }
274        let _ = std::fs::rename(&self.0.path, numbered(1));
275    }
276
277    /// Flushes the file.
278    pub fn flush(&self) {
279        if let Some((f, _)) = lock(&self.0.file).as_mut() {
280            let _ = f.flush();
281        }
282    }
283
284    /// Makes these the process's logs: the `log` facade writes here from
285    /// now on. Fails when another logger was installed first.
286    pub fn install(&self) -> Result<(), String> {
287        static SET: std::sync::OnceLock<Result<(), String>> = std::sync::OnceLock::new();
288        SET.get_or_init(|| {
289            log::set_logger(&ROUTER)
290                .map_err(|_| "another logger is installed: feed it to Logs::write".to_string())
291        })
292        .clone()?;
293        *ROUTER
294            .0
295            .write()
296            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(self.clone());
297        log::set_max_level(self.level());
298        Ok(())
299    }
300}
301
302/// The `log` facade's logger: hands each record to the installed
303/// [`Logs`].
304struct Router(RwLock<Option<Logs>>);
305
306static ROUTER: Router = Router(RwLock::new(None));
307
308impl log::Log for Router {
309    fn enabled(&self, m: &log::Metadata<'_>) -> bool {
310        installed().is_some_and(|l| m.level() <= l.level())
311    }
312
313    fn log(&self, r: &log::Record<'_>) {
314        if let Some(l) = installed() {
315            l.write(r.level(), r.target(), &r.args().to_string());
316        }
317    }
318
319    fn flush(&self) {
320        if let Some(l) = installed() {
321            l.flush();
322        }
323    }
324}
325
326/// The logs the `log` facade writes to, when installed.
327pub fn installed() -> Option<Logs> {
328    ROUTER.0.try_read().ok().and_then(|l| l.as_ref().cloned())
329}
330
331/// Logs to a file, as a plugin (see the module).
332#[derive(Debug)]
333pub struct LogsPlugin {
334    logs: Logs,
335    install: bool,
336}
337
338impl LogsPlugin {
339    /// Logs of the application `app` (its name or id) in the platform's
340    /// log directory ([`crate::dirs::log_dir`]; the temporary directory
341    /// when the environment names none).
342    pub fn new(app: &str) -> Self {
343        let dir = crate::dirs::log_dir(app).unwrap_or_else(|| crate::dirs::temp_dir().join(app));
344        let name = app.rsplit('.').next().unwrap_or(app).to_lowercase();
345        Self {
346            logs: Logs::new(dir, &name),
347            install: true,
348        }
349    }
350
351    /// Other logs (another directory, size, files kept).
352    pub fn logs(mut self, logs: Logs) -> Self {
353        self.logs = logs;
354        self
355    }
356
357    /// Whether the logs become the process's logger (on by default).
358    /// Off, they hold only what is written to them ([`Logs::write`]):
359    /// several apps in one process (tests, a simulated desktop) each keep
360    /// their own, the `log` facade's lines from the others staying out.
361    pub fn install(mut self, on: bool) -> Self {
362        self.install = on;
363        self
364    }
365}
366
367impl Plugin for LogsPlugin {
368    fn id(&self) -> PluginId {
369        PLUGIN
370    }
371
372    fn title(&self) -> String {
373        "Logs".into()
374    }
375
376    fn priority(&self) -> i32 {
377        // First, so the others' connecting is logged.
378        200
379    }
380
381    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
382        let logs = self.logs.clone();
383        let routed = if self.install {
384            logs.install()
385                .inspect_err(|e| {
386                    // Still kept: the application may feed it.
387                    logs.write(Level::Warn, "egui_pop", e);
388                })
389                .is_ok()
390        } else {
391            false
392        };
393        ctx.setting(
394            SETTING_LEVEL,
395            Descriptor::choice("Log level", &LEVELS, "info").description(
396                "How much the application writes to its log file: errors only, up to every detail.",
397            ),
398        )?;
399        let path = format!("settings/{SETTING_LEVEL}");
400        if let Some(level) = lock(&ctx.app().store())
401            .get(&path)
402            .and_then(|e| e.value.as_choice().and_then(parse_level))
403        {
404            logs.set_level(level);
405        }
406        let l = logs.clone();
407        ctx.on_change(&path, move |c| {
408            if let Value::Choice(v) = &c.new
409                && let Some(level) = parse_level(v)
410            {
411                l.set_level(level);
412            }
413        });
414        let dir = logs.dir().to_path_buf();
415        ctx.command(
416            CommandSpec::new(CMD_REVEAL, "Show the log folder", "Help")
417                .icon("folder")
418                .description("Opens the folder holding the application's log files."),
419            move |_| {
420                crate::dirs::reveal(&dir)?;
421                Ok(json!({ "dir": dir }))
422            },
423        )?;
424        let snap = logs.clone();
425        ctx.collector(
426            FnCollector::new("logs", "The log file, its level and its last lines.").snapshot(
427                move |_| {
428                    json!({
429                        "path": snap.path(),
430                        "level": snap.level().to_string().to_lowercase(),
431                        "tail": snap.tail(),
432                    })
433                },
434            ),
435        )?;
436        ctx.service(&LOGS, logs.clone())?;
437        let line = format!("logging to {}", logs.path().display());
438        if routed {
439            log::info!(target: "egui_pop", "{line}");
440        } else {
441            logs.write(Level::Info, "egui_pop", &line);
442        }
443        Ok(())
444    }
445
446    fn disconnect(&mut self, _ctx: &mut Ctx<'_>) {
447        if installed().is_some_and(|l| Arc::ptr_eq(&l.0, &self.logs.0)) {
448            self.logs.flush();
449            *ROUTER
450                .0
451                .write()
452                .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
453        }
454    }
455}