Skip to main content

tuwunel_core/log/capture/
util.rs

1//! Callback constructors for formatting captured log events.
2//!
3//! Helpers append HTML or Markdown lines to a shared formatter. A generic
4//! constructor accepts compatible formatting functions.
5
6use std::sync::{Arc, Mutex};
7
8use super::{
9	super::{Level, fmt},
10	Closure, Data,
11};
12use crate::Result;
13
14/// Builds a capture callback that appends HTML log lines.
15///
16/// Each event locks the shared output and formats its level, current span, and
17/// message. The callback owns the supplied output handle and panics if the lock
18/// is poisoned or formatting fails.
19pub fn fmt_html<S>(out: Arc<Mutex<S>>) -> Box<Closure>
20where
21	S: std::fmt::Write + Send + 'static,
22{
23	fmt(fmt::html, out)
24}
25
26/// Builds a capture callback that appends Markdown log lines.
27///
28/// Each event locks the shared output and formats its level, current span, and
29/// message. The callback owns the supplied output handle and panics if the lock
30/// is poisoned or formatting fails.
31pub fn fmt_markdown<S>(out: Arc<Mutex<S>>) -> Box<Closure>
32where
33	S: std::fmt::Write + Send + 'static,
34{
35	fmt(fmt::markdown, out)
36}
37
38/// Builds a capture callback around a compatible formatting function.
39///
40/// The output is locked for each event before the formatter is called. The
41/// returned callback panics if the lock is poisoned or the formatter returns an
42/// error.
43pub fn fmt<F, S>(fun: F, out: Arc<Mutex<S>>) -> Box<Closure>
44where
45	F: Fn(&mut S, &Level, &str, &str) -> Result + Send + Sync + Copy + 'static,
46	S: std::fmt::Write + Send + 'static,
47{
48	Box::new(move |data| call(fun, &mut *out.lock().expect("locked"), &data))
49}
50
51fn call<F, S>(fun: F, out: &mut S, data: &Data<'_>)
52where
53	F: Fn(&mut S, &Level, &str, &str) -> Result,
54	S: std::fmt::Write,
55{
56	fun(out, &data.level(), data.span_name(), data.message()).expect("log line appended");
57}