Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Logforth separates three concerns into distinct primitives:
- Logging pipelines must never panic on runtime operational failures such as out-of-range timestamps, broken pipes, closed descriptors, log rotation or retention errors, or fallible wire serialization. Leaf components return structured `Error`s (committing active record writes before surfacing post-write rollover or cleanup errors), synchronous execution roots route recoverable `Error`s to `ErrorSink` while asynchronous workers additionally isolate unwind panics via `ErrorSink`, and `ErrorSink` implementations silently absorb their own delivery failures without panicking or routing records back into their owning `Logger`.
- User `Display` and `Debug` formatting and value destruction execute outside appender I/O locks.
- Thread-local and task-local diagnostics access thread-local storage exclusively via fallible lookups (`LocalKey::try_with`) so logging during thread teardown degrades to an empty context instead of aborting.
- Because Rust does not run destructors on `static` items at process exit, buffered and asynchronous pipelines require an explicit `flush()` before shutdown.
- Because Rust does not run destructors on `static` items at process exit, asynchronous or batching sinks expose dedicated lifecycle handles (such as `AsyncGuard` or external SDK providers) bound in `main` so in-flight records drain deterministically on shutdown even when `Logger` handles live in statics.

## Ecosystem Interop

Expand Down
4 changes: 0 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ fn main() {
.build();

logforth::info!(logger, ["port" = 8080, "tls" = false], "server listening");
logger.flush();
}
```

Expand Down Expand Up @@ -92,7 +91,6 @@ fn main() -> Result<(), logforth::Error> {
logforth::info!(logger, ["order_id" = 42], "order accepted");
logforth::warn!(logger, ["order_id" = 42, "retry" = 1], "payment gateway slow");

logger.flush();
Ok(())
}
```
Expand All @@ -118,7 +116,6 @@ fn main() {
logforth::starter_log::stderr().install();

log::info!(port = 8080; "server started");
log::logger().flush();
}
```

Expand All @@ -134,7 +131,6 @@ fn main() {
.install();

log::info!("routed through a custom Logforth pipeline");
log::logger().flush();
}
```

Expand Down
12 changes: 6 additions & 6 deletions appenders/async/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Logforth Async Appender

`logforth-append-async` provides [`Async`](https://docs.rs/logforth-append-async/0.5.0/logforth_append_async/struct.Async.html) and [`AsyncBuilder`](https://docs.rs/logforth-append-async/0.5.0/logforth_append_async/struct.AsyncBuilder.html), a composable background-thread `logforth_core::Append` decorator that decouples caller threads from downstream I/O.
`logforth-append-async` provides [`Async`](https://docs.rs/logforth-append-async/0.5.0/logforth_append_async/struct.Async.html), [`AsyncGuard`](https://docs.rs/logforth-append-async/0.5.0/logforth_append_async/struct.AsyncGuard.html), and [`AsyncBuilder`](https://docs.rs/logforth-append-async/0.5.0/logforth_append_async/struct.AsyncBuilder.html), a composable background-thread `logforth_core::Append` decorator that decouples caller threads from downstream I/O.

Most applications can enable this crate through the [`logforth`](https://crates.io/crates/logforth) facade crate with the `append-async` feature (exposed as `logforth::append::Async` and `logforth::append::asynchronous::AsyncBuilder`). Depend on `logforth-append-async` directly when composing split `logforth-*` crates onto `logforth-core`.
Most applications can enable this crate through the [`logforth`](https://crates.io/crates/logforth) facade crate with the `append-async` feature (exposed as `logforth::append::{Async, AsyncGuard}` and `logforth::append::asynchronous::AsyncBuilder`). Depend on `logforth-append-async` directly when composing split `logforth-*` crates onto `logforth-core`.

## Quick start

Expand All @@ -18,7 +18,7 @@ use logforth_core::LoggerBuilder;
use logforth_core::append::Stderr;

fn main() -> Result<(), logforth_core::Error> {
let async_append = AsyncBuilder::new("logforth-async")
let (async_append, _guard) = AsyncBuilder::new("logforth-async")
.max_buffered_records(NonZeroUsize::new(1024).unwrap())
.overflow_drop_incoming()
.append(Stderr::new())
Expand All @@ -29,7 +29,6 @@ fn main() -> Result<(), logforth_core::Error> {
.build();

logforth_core::info!(logger, ["port" = 8080], "server listening");
logger.flush();
Ok(())
}
```
Expand All @@ -48,8 +47,9 @@ On each `Append::append` call, `Async` snapshots the record payload, structured

## Flushing and shutdown

- `Append::flush` enqueues a barrier onto the worker queue (blocking even under `overflow_drop_incoming`) and waits until all preceding records have been processed and every inner appender has completed `Append::flush`.
- Dropping `Async` closes the queue, drains all pending records, flushes every inner appender, and joins the worker thread (unless dropped on the worker thread itself). Because Rust does not run `Drop` on `static` items at process exit, call `logger.flush()` explicitly before shutdown when storing a logger in a `static`.
- `Async` is cheaply `Clone`able so multiple dispatch branches or channel loggers can share one worker queue without wrapping `Async` in an `Arc`.
- `AsyncGuard::flush` (and `Append::flush` on `Async`) enqueues a barrier onto the worker queue (blocking even under `overflow_drop_incoming`) and waits until all preceding records have been processed and every inner appender has completed `Append::flush`.
- Dropping `AsyncGuard` signals shutdown, drains all pending records, flushes every inner appender, and joins the worker thread (unless dropped on the worker thread itself), even when `Logger` handles remain alive in `static` items at process exit.

The single-worker queue design is adapted from [`spdlog-rs`'s `AsyncPoolSink`](https://docs.rs/spdlog-rs/0.5.3/spdlog/sink/struct.AsyncPoolSink.html), simplified to a single ordered drain thread with synchronous `flush` barriers.

Expand Down
185 changes: 125 additions & 60 deletions appenders/async/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,8 @@
//! routed to [`AsyncBuilder::error_sink`] (default: [`StderrErrorSink`]) without terminating the
//! worker thread.
//! - **Ordered flushing and shutdown**: [`Append::flush`] waits for all queued records ahead of it
//! to be written and flushed; dropping [`Async`] drains remaining queued records, flushes all
//! inner appenders, and joins the worker thread. Because Rust does not run destructors on
//! `static` items at process exit, call `flush()` explicitly before shutdown when [`Async`] lives
//! in a `static` logger.
//! to be written and flushed; dropping [`AsyncGuard`] drains pending records, flushes the inner
//! appenders, and joins the worker when dropped outside the worker thread.
//!
//! # Examples
//!
Expand All @@ -43,18 +41,17 @@
//! use logforth_core::LoggerBuilder;
//! use logforth_core::append::Testing;
//!
//! let async_append = AsyncBuilder::new("logforth-async")
//! let (async_appender, _guard) = AsyncBuilder::new("logforth-async")
//! .max_buffered_records(NonZeroUsize::new(1024).unwrap())
//! .overflow_drop_incoming()
//! .append(Testing::new())
//! .build()?;
//!
//! let logger = LoggerBuilder::new()
//! .dispatch(|d| d.append(async_append))
//! .dispatch(|d| d.append(async_appender))
//! .build();
//!
//! logforth_core::info!(logger, ["port" = 8080], "server started");
//! logger.flush();
//! # Ok::<(), logforth_core::Error>(())
//! ```

Expand All @@ -65,6 +62,9 @@ use std::any::Any;
use std::num::NonZeroUsize;
use std::panic::AssertUnwindSafe;
use std::panic::catch_unwind;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use std::thread;
use std::thread::JoinHandle;
Expand All @@ -85,34 +85,33 @@ use logforth_core::record::RecordOwned;
/// # Flushing and Shutdown
///
/// [`Append::flush`] enqueues a barrier and blocks until all previously queued records have been
/// appended and every inner appender has been flushed. Dropping [`Async`] closes the queue, drains
/// all pending records, flushes every inner appender, and joins the worker thread (unless dropped
/// on the worker thread itself).
///
/// Because Rust does not run [`Drop`] on `static` items at process exit, applications storing a
/// [`Logger`][logforth_core::Logger] in a `static` should call `flush()` before exiting so buffered
/// records are not lost.
/// appended and every inner appender has been flushed. Keep the associated [`AsyncGuard`] in `main`
/// to drain pending records at shutdown, including when the logger lives in a `static`. After the
/// guard is dropped, appending through any clone returns an error.
///
/// # Examples
///
/// ```
/// use logforth_append_async::AsyncBuilder;
/// use logforth_core::append::Stderr;
///
/// let async_append = AsyncBuilder::new("logforth-async-append")
/// let (async_appender, _guard) = AsyncBuilder::new("logforth-async-append")
/// .overflow_drop_incoming()
/// .append(Stderr::new())
/// .build()?;
/// # Ok::<(), logforth_core::Error>(())
/// ```
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct Async {
sender: Option<TaskSender>,
handle: Option<JoinHandle<()>>,
shutdown: Arc<AtomicBool>,
}

impl Append for Async {
fn append(&self, record: &Record, diags: &dyn Diagnostic) -> Result<(), Error> {
if self.shutdown.load(Ordering::Acquire) {
return Err(Error::new("failed to send log task to async appender"));
}
let Some(sender) = &self.sender else {
return Ok(());
};
Expand All @@ -131,28 +130,69 @@ impl Append for Async {
}

fn flush(&self) -> Result<(), Error> {
let Some(sender) = &self.sender else {
if self.shutdown.load(Ordering::Acquire) {
return Ok(());
};

let (done_tx, done_rx) = mpsc::sync_channel(1);
}
flush_worker(self.sender.as_ref())
}
}

sender
.send_blocking(Task::Flush { done: done_tx })
.map_err(|_| Error::new("failed to send flush task to async appender"))?;
/// Owns the async worker's lifetime. Dropping the guard drains pending records and flushes
/// downstream appenders. The caller waits for the worker to exit unless it is the worker itself.
#[must_use = "dropping the guard flushes pending records and joins the async worker thread; bind it in main (for example, `let _guard = ...`)"]
#[derive(Debug)]
pub struct AsyncGuard {
sender: Option<TaskSender>,
shutdown: Arc<AtomicBool>,
handle: Option<JoinHandle<()>>,
}

done_rx
.recv()
.map_err(|err| Error::new("worker exited before completing flush").with_source(err))
impl AsyncGuard {
/// Waits until all previously queued records are processed and inner appenders are flushed.
///
/// # Errors
///
/// Returns an error if the worker exits before acknowledging the flush.
pub fn flush(&self) -> Result<(), Error> {
flush_worker(self.sender.as_ref())
}
}

impl Drop for Async {
fn flush_worker(sender: Option<&TaskSender>) -> Result<(), Error> {
let Some(sender) = sender else {
return Ok(());
};
let (done, done_rx) = mpsc::sync_channel(1);
sender
.send_blocking(Task::Flush { done })
.map_err(|_| Error::new("failed to send flush task to async appender"))?;
done_rx
.recv()
.map_err(|err| Error::new("worker exited before completing flush").with_source(err))
}

impl Drop for AsyncGuard {
fn drop(&mut self) {
drop(self.sender.take());
if let Some(handle) = self.handle.take()
&& handle.thread().id() != thread::current().id()
{
self.shutdown.store(true, Ordering::Release);
let on_worker = self
.handle
.as_ref()
.is_some_and(|h| h.thread().id() == thread::current().id());
if let Some(sender) = self.sender.take() {
if on_worker {
match sender {
TaskSender::Unbounded(tx) => {
let _ = tx.send(Task::Shutdown);
}
TaskSender::BoundedBlock(tx) | TaskSender::BoundedDrop(tx) => {
let _ = tx.try_send(Task::Shutdown);
}
}
return;
}
let _ = sender.send_blocking(Task::Shutdown);
}
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
Expand Down Expand Up @@ -227,7 +267,7 @@ impl AsyncBuilder {
self
}

/// Validates configuration and spawns the background worker thread.
/// Builds a cloneable appender and the guard that shuts down its worker.
///
/// If no inner appenders were registered via [`AsyncBuilder::append`], returns an inert
/// [`Async`] instance without spawning a thread.
Expand All @@ -236,7 +276,7 @@ impl AsyncBuilder {
///
/// Returns an [`Error`] if `thread_name` contains a NUL (`\0`) byte or if spawning the OS
/// worker thread fails.
pub fn build(self) -> Result<Async, Error> {
pub fn build(self) -> Result<(Async, AsyncGuard), Error> {
let Self {
thread_name,
appends,
Expand All @@ -251,11 +291,19 @@ impl AsyncBuilder {
));
}

let shutdown = Arc::new(AtomicBool::new(false));
if appends.is_empty() {
return Ok(Async {
sender: None,
handle: None,
});
return Ok((
Async {
sender: None,
shutdown: shutdown.clone(),
},
AsyncGuard {
sender: None,
shutdown,
handle: None,
},
));
}

let (sender, receiver) = match (max_buffered_records, overflow) {
Expand All @@ -273,15 +321,23 @@ impl AsyncBuilder {
}
};

let worker_shutdown = shutdown.clone();
let handle = thread::Builder::new()
.name(thread_name)
.spawn(move || run_worker(receiver, appends, error_sink))
.spawn(move || run_worker(receiver, appends, error_sink, worker_shutdown))
.map_err(|err| Error::new("failed to spawn async worker thread").with_source(err))?;

Ok(Async {
sender: Some(sender),
handle: Some(handle),
})
Ok((
Async {
sender: Some(sender.clone()),
shutdown: shutdown.clone(),
},
AsyncGuard {
sender: Some(sender),
shutdown,
handle: Some(handle),
},
))
}
}

Expand All @@ -291,7 +347,7 @@ enum Overflow {
DropIncoming,
}

#[derive(Debug)]
#[derive(Clone, Debug)]
enum TaskSender {
Unbounded(mpsc::Sender<Task>),
BoundedBlock(mpsc::SyncSender<Task>),
Expand Down Expand Up @@ -329,6 +385,7 @@ struct LogTask {
enum Task {
Log(Box<LogTask>),
Flush { done: mpsc::SyncSender<()> },
Shutdown,
}

#[derive(Debug)]
Expand Down Expand Up @@ -360,24 +417,32 @@ fn run_worker(
receiver: mpsc::Receiver<Task>,
appends: Vec<Box<dyn Append>>,
error_sink: Box<dyn ErrorSink>,
shutdown: Arc<AtomicBool>,
) {
while let Ok(task) = receiver.recv() {
match task {
Task::Log(log_task) => {
let LogTask { record, diags } = *log_task;
record.with(|record| {
for append in &appends {
if let Err(err) = catch_panic(|| append.append(&record, &diags)) {
let err = Error::new("failed to append record").with_source(err);
sink_error(&*error_sink, &err);
}
let process = |task| match task {
Task::Log(log_task) => {
let LogTask { record, diags } = *log_task;
record.with(|record| {
for append in &appends {
if let Err(err) = catch_panic(|| append.append(&record, &diags)) {
let err = Error::new("failed to append record").with_source(err);
sink_error(&*error_sink, &err);
}
});
}
Task::Flush { done } => {
flush_appends(&appends, &*error_sink);
let _ = done.send(());
}
}
});
}
Task::Flush { done } => {
flush_appends(&appends, &*error_sink);
let _ = done.send(());
}
Task::Shutdown => {}
};
while let Ok(task) = receiver.recv() {
let stop = matches!(task, Task::Shutdown);
process(task);
if stop || shutdown.load(Ordering::Acquire) {
receiver.try_iter().for_each(process);
break;
}
}
flush_appends(&appends, &*error_sink);
Expand Down
Loading
Loading