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
10 changes: 5 additions & 5 deletions appenders/async/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ On each `Append::append` call, `Async` snapshots the record payload, structured
| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
| `max_buffered_records(n)` | Limits buffered pending records to `n` (`NonZeroUsize`). When omitted, buffering is unbounded. |
| `overflow_block()` | Blocks the calling thread when the record buffer is full until space frees up (default). |
| `overflow_drop_incoming()` | Drops incoming log records without error when the record buffer is full; `flush` still blocks until all previously buffered records complete. |
| `error_sink(sink)` | Routes worker-side `Append` errors and caught panics to `sink` (default: `StderrErrorSink`) without terminating the worker thread. |
| `append(appender)` | Registers a downstream `Append` driven sequentially on the worker thread (skipping thread creation when no appenders are registered). |
| `overflow_drop_incoming()` | Drops incoming log records without error when the record buffer is full; `AsyncGuard::flush` still blocks until all previously buffered records complete. |
| `error_sink(sink)` | Routes worker-side `Append` errors and caught panics to `sink` (default: `StderrErrorSink`) without terminating the worker thread. |
| `append(appender)` | Registers a downstream `Append` driven sequentially on the worker thread (skipping thread creation when no appenders are registered). |

## Flushing and shutdown

- `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.
- `AsyncGuard::flush` enqueues a barrier onto the worker queue (blocking even under `overflow_drop_incoming`) and waits until all preceding records have been processed.
- Dropping `AsyncGuard` signals shutdown, drains all pending records, 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
44 changes: 13 additions & 31 deletions appenders/async/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
//! - **Fault isolation**: operational errors and panics inside worker-side appenders are caught and
//! 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 [`AsyncGuard`] drains pending records, flushes the inner
//! appenders, and joins the worker when dropped outside the worker thread.
//! - **Queue draining and shutdown**: [`AsyncGuard::flush`] waits for the worker to process all
//! previously queued records. Dropping [`AsyncGuard`] drains pending records and joins the worker
//! when dropped outside the worker thread.
//!
//! # Examples
//!
Expand Down Expand Up @@ -84,10 +84,10 @@ 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. 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.
/// [`AsyncGuard::flush`] waits for the worker to process all previously queued records.
/// 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
///
Expand Down Expand Up @@ -128,18 +128,11 @@ impl Append for Async {
}));
sender.send_log(task)
}

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

/// 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 = ...`)"]
/// Owns the async worker's lifetime. Dropping the guard drains pending records and joins the
/// worker thread unless the guard is dropped on the worker itself.
#[must_use = "dropping the guard drains pending records and joins the async worker thread; bind it in main (for example, `let _guard = ...`)"]
#[derive(Debug)]
pub struct AsyncGuard {
sender: Option<TaskSender>,
Expand All @@ -148,7 +141,7 @@ pub struct AsyncGuard {
}

impl AsyncGuard {
/// Waits until all previously queued records are processed and inner appenders are flushed.
/// Waits until all previously queued records have been processed by the worker.
///
/// # Errors
///
Expand Down Expand Up @@ -245,8 +238,8 @@ impl AsyncBuilder {
/// Configures [`Append::append`] to drop incoming records without error when the record buffer
/// is full.
///
/// [`Append::flush`] still blocks until space is available and all previously buffered records
/// have been processed. Has no effect when [`AsyncBuilder::max_buffered_records`] is not set.
/// [`AsyncGuard::flush`] still waits for the worker to process all previously queued records.
/// This policy has no effect when [`AsyncBuilder::max_buffered_records`] is not set.
pub fn overflow_drop_incoming(mut self) -> Self {
self.overflow = Overflow::DropIncoming;
self
Expand Down Expand Up @@ -404,15 +397,6 @@ fn sink_error(error_sink: &dyn ErrorSink, err: &Error) {
let _ = catch_unwind(AssertUnwindSafe(|| error_sink.sink(err)));
}

fn flush_appends(appends: &[Box<dyn Append>], error_sink: &dyn ErrorSink) {
for append in appends {
if let Err(err) = catch_panic(|| append.flush()) {
let err = Error::new("failed to flush appender").with_source(err);
sink_error(error_sink, &err);
}
}
}

fn run_worker(
receiver: mpsc::Receiver<Task>,
appends: Vec<Box<dyn Append>>,
Expand All @@ -432,7 +416,6 @@ fn run_worker(
});
}
Task::Flush { done } => {
flush_appends(&appends, &*error_sink);
let _ = done.send(());
}
Task::Shutdown => {}
Expand All @@ -445,7 +428,6 @@ fn run_worker(
break;
}
}
flush_appends(&appends, &*error_sink);
}

fn catch_panic(f: impl FnOnce() -> Result<(), Error>) -> Result<(), Error> {
Expand Down
2 changes: 1 addition & 1 deletion appenders/opentelemetry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ By default, `OpentelemetryLog` enforces unique top-level attribute keys per the
## Usage notes

- **Sharing a provider and custom processors**: Configure `Resource`, `SimpleLogProcessor`, or `BatchLogProcessor` (`BatchConfigBuilder`) on `SdkLoggerProvider::builder()`, then clone `provider` into each `OpentelemetryLog::new(scope, provider.clone())` channel.
- **Provider lifecycle and `static` loggers**: Retain a `provider` clone to call `provider.force_flush()` on demand or `provider.shutdown()` before process exit (`Append::flush` also delegates to `SdkLoggerProvider::force_flush`). While `SdkLoggerProvider` shuts down automatically when its last reference drops, `static` loggers never drop at exit and therefore require an explicit `provider.shutdown()`.
- **Provider lifecycle and `static` loggers**: Retain a `provider` clone to call `provider.force_flush()` on demand or `provider.shutdown()` before process exit. While `SdkLoggerProvider` shuts down automatically when its last reference drops, `static` loggers never drop at exit and therefore require an explicit `provider.shutdown()`.
- **Trace-log correlation**: Pair `OpentelemetryLog` with [`logforth-diagnostic-fastrace`](https://crates.io/crates/logforth-diagnostic-fastrace) (`FastraceDiagnostic`) or any `Diagnostic` emitting `"trace_id"` (32-digit non-zero hex) and `"span_id"` (16-digit non-zero hex), plus optional boolean `"sampled"`, to populate `LogRecord::set_trace_context`.
- **Filter exporter transport targets at `DEBUG` / `TRACE`**: When bridging global `log` output at `DEBUG` or `TRACE`, raise thresholds for your exporter's transport crates (such as `reqwest`, `h2`, `hyper`, `tonic`, and `tower`) to `WARN` to avoid log amplification outside the SDK batch worker thread.
- **Custom body construction (`MakeBody` vs. `MakeBodyLayout`)**: `MakeBody` can construct any `AnyValue` (`String`, `Map`, `ListAny`, `Bytes`, or scalar). Because `Layout::format` outputs `Vec<u8>`, `MakeBodyLayout` emits `AnyValue::Bytes` (OTLP `bytes_value`, rendered as Base64 in backends like Grafana Loki); implement `MakeBody` directly to emit UTF-8 `AnyValue::String` or structured `AnyValue` bodies.
Expand Down
8 changes: 0 additions & 8 deletions appenders/opentelemetry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ const KEY_SAMPLED: &str = "sampled";
#[derive(Debug)]
pub struct OpentelemetryLog {
logger: SdkLogger,
provider: SdkLoggerProvider,
make_body: Option<Box<dyn MakeBody>>,
allow_duplicate_keys: bool,
}
Expand Down Expand Up @@ -141,7 +140,6 @@ impl OpentelemetryLog {
let logger = provider.logger_with_scope(scope);
OpentelemetryLog {
logger,
provider,
make_body: None,
allow_duplicate_keys: false,
}
Expand Down Expand Up @@ -290,12 +288,6 @@ impl Append for OpentelemetryLog {
self.logger.emit(log_record);
Ok(())
}

fn flush(&self) -> Result<(), Error> {
self.provider
.force_flush()
.map_err(|err| Error::new("failed to flush records").with_source(err))
}
}

fn add_source_location(
Expand Down
8 changes: 0 additions & 8 deletions appenders/syslog/src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,14 +348,6 @@ impl Append for SocketSyslog {
.send(&wire_buf)
.map_err(|err| Error::new("failed to send syslog message").with_source(err))
}

fn flush(&self) -> Result<(), Error> {
self.sender
.lock()
.unwrap_or_else(|e| e.into_inner())
.flush()
.map_err(|err| Error::new("failed to flush syslog sender").with_source(err))
}
}

impl Drop for SocketSyslog {
Expand Down
17 changes: 0 additions & 17 deletions core/src/append/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,6 @@ pub trait Append: fmt::Debug + Send + Sync + 'static {
///
/// Returns an [`Error`] if formatting, encoding, or writing the record fails.
fn append(&self, record: &Record, diags: &dyn Diagnostic) -> Result<(), Error>;

/// Flushes any buffered records to the underlying destination. The default does nothing.
///
/// # Errors
///
/// Returns an [`Error`] if flushing buffered output fails.
fn flush(&self) -> Result<(), Error> {
Ok(())
}
}

impl<T: Append> From<T> for Box<dyn Append> {
Expand All @@ -68,18 +59,10 @@ impl<T: Append + ?Sized> Append for Arc<T> {
fn append(&self, record: &Record, diags: &dyn Diagnostic) -> Result<(), Error> {
(**self).append(record, diags)
}

fn flush(&self) -> Result<(), Error> {
(**self).flush()
}
}

impl<T: Append + ?Sized> Append for &'static T {
fn append(&self, record: &Record, diags: &dyn Diagnostic) -> Result<(), Error> {
(**self).append(record, diags)
}

fn flush(&self) -> Result<(), Error> {
(**self).flush()
}
}
7 changes: 0 additions & 7 deletions core/src/append/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,6 @@ impl Append for Stdout {
.map_err(|err| Error::new("failed to write to stdout").with_source(err))?;
Ok(())
}

fn flush(&self) -> Result<(), Error> {
std::io::stdout()
.flush()
.map_err(|err| Error::new("failed to flush stdout").with_source(err))?;
Ok(())
}
}

/// An appender that writes formatted log records followed by `\n` to standard error.
Expand Down
2 changes: 1 addition & 1 deletion core/src/error/sink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::Error;
/// A terminal sink that processes internal runtime errors produced by the logging pipeline.
///
/// Logging operations are designed not to crash the host application at runtime. When an appender
/// fails to emit or flush records, execution roots such as [`Logger`](crate::Logger) or asynchronous
/// fails to emit records, execution roots such as [`Logger`](crate::Logger) or asynchronous
/// workers forward the resulting [`Error`] to their configured [`ErrorSink`].
///
/// Because [`ErrorSink`] is the final stage of error handling, implementations operate on a
Expand Down
2 changes: 1 addition & 1 deletion core/src/logger/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl LoggerBuilder {
self
}

/// Sets the logger's [`ErrorSink`] for append and flush failures.
/// Sets the logger's [`ErrorSink`] for append failures.
///
/// Defaults to [`StderrErrorSink`].
///
Expand Down
23 changes: 2 additions & 21 deletions tests-integration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

use logforth_core::Append;
use logforth_core::Diagnostic;
Expand Down Expand Up @@ -48,10 +46,9 @@ pub struct CapturedEvent {
struct RecordingState {
layout: Box<dyn Layout>,
events: Mutex<Vec<CapturedEvent>>,
flushes: AtomicUsize,
}

/// A thread-safe in-memory [`Append`] test double that records events and flush calls.
/// A thread-safe in-memory [`Append`] test double that records events.
#[derive(Debug, Clone)]
pub struct RecordingAppender {
state: Arc<RecordingState>,
Expand All @@ -70,7 +67,6 @@ impl RecordingAppender {
state: Arc::new(RecordingState {
layout: layout.into(),
events: Mutex::new(Vec::new()),
flushes: AtomicUsize::new(0),
}),
}
}
Expand Down Expand Up @@ -105,11 +101,6 @@ impl RecordingAppender {
})
.collect()
}

/// Returns the number of `flush` calls observed.
pub fn flush_count(&self) -> usize {
self.state.flushes.load(Ordering::Acquire)
}
}

impl Append for RecordingAppender {
Expand All @@ -126,11 +117,6 @@ impl Append for RecordingAppender {
self.state.events.lock().unwrap().push(event);
Ok(())
}

fn flush(&self) -> Result<(), Error> {
self.state.flushes.fetch_add(1, Ordering::Release);
Ok(())
}
}

/// An [`Append`] test double that always fails with a fixed message.
Expand All @@ -140,8 +126,7 @@ pub struct FailingAppender {
}

impl FailingAppender {
/// Creates a new [`FailingAppender`] that returns `Error::new(message)` on `append` and
/// `flush`.
/// Creates a new [`FailingAppender`] that returns `Error::new(message)` on `append`.
pub const fn new(message: &'static str) -> Self {
Self { message }
}
Expand All @@ -151,10 +136,6 @@ impl Append for FailingAppender {
fn append(&self, _: &Record, _: &dyn Diagnostic) -> Result<(), Error> {
Err(Error::new(self.message))
}

fn flush(&self) -> Result<(), Error> {
Err(Error::new(self.message))
}
}

/// A [`Diagnostic`] test double that always fails with a fixed message.
Expand Down
Loading
Loading