Skip to content
Open
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: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ All significant changes to this project will be documented in this file.
* Remove the `anyhow` dependency from `logforth-core` and redesign `Error`: `Error::new` now accepts `impl Into<Cow<'static, str>>`, `Error::with_source` accepts `impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>` instead of `impl Into<anyhow::Error>` and replaces any existing source instead of panicking, and `Error::{with_context, sources, from_io_error, from_fmt_error}` are removed. Walk `.source()` for causal chains and construct descriptive `Error::new(...).with_source(...)` values at call sites.
* Replace `Trap`, `trap::BestEffortTrap`, `AsyncBuilder::trap`, and `FileBuilder::trap` with `ErrorSink` and `error::{StderrErrorSink, BlackHoleErrorSink}` across `logforth-core`, `logforth`, `logforth-append-async`, and `logforth-append-file`. Configure runtime error handling via `LoggerBuilder::error_sink`, `DispatchBuilder::error_sink`, `AsyncBuilder::error_sink`, or `starter_log` builders instead.
* Replace `&[Box<dyn Diagnostic>]` with `&dyn Diagnostic` across `Filter::{enabled, matches}`, `Layout::format`, `Append::append`, and `MakeBody::create` in `logforth-core`, `logforth`, and peripheral crates, and relax the `'static` supertrait bound on `Diagnostic` to the `Box<dyn Diagnostic>` registration boundary; traverse diagnostics via `diags.visit(&mut visitor)` instead of iterating a slice, and pass `&()` for an empty diagnostic context.
* `LogBridge::new` in `logforth-bridge-log` now accepts `Logger` by value instead of `impl Into<Arc<Logger>>`; pass `logger.clone()` when retaining another handle.
* `FutureExt::with_task_local_context` in `logforth-diagnostic-task-local` now accepts `IntoIterator<Item = (K, V)>` where `K: Into<KeyOwned>` and `V: Into<ValueOwned>` instead of `IntoIterator<Item = (String, String)>`, preserving typed values instead of converting them to strings; pass keys and values directly without `.into()` where type inference would otherwise be ambiguous.
* `File` in `logforth-append-file` now writes directly to target segment files instead of writing to an unnumbered active file and shifting reverse-numbered archives on rollover. Unrotated output remains `<filename>[.<suffix>]`, time-only rotation writes `<filename>.<period>[.<suffix>]`, and size rotation numbers segments in ascending order from `1` (oldest) as `<filename>[.<period>].<seq>[.<suffix>]`; `max_log_files` counts the active file toward the retention limit, and files created under the previous naming scheme are ignored or ordered by ascending sequence number until moved or removed.
* `FileBuilder::rollover_size` in `logforth-append-file` now takes `NonZeroU64` instead of `NonZeroUsize` and rotates before a write would exceed the size limit rather than after; update callers passing `NonZeroUsize` to pass `NonZeroU64`.
Expand All @@ -20,6 +21,7 @@ All significant changes to this project will be documented in this file.
### New features

* Add `Error::message` in `logforth-core` to borrow the error's own message string.
* Make `Logger` a pointer-sized `Clone` and `Default` handle over a shared pipeline and add `const fn Logger::noop()` in `logforth-core`, and implement `Clone` for `LogBridge` in `logforth-bridge-log`.
* Add `LoggerBuilder::error_sink`, `DispatchBuilder::error_sink`, and `starter_log::{LogStarterBuilder, LogStarterTestingBuilder, LogStarterStdStreamBuilder}::error_sink` to configure runtime error handling.
* Implement `Append`, `ErrorSink`, `Filter`, and `Layout` in `logforth-core`, and `MakeBody` in `logforth-append-opentelemetry`, for `Arc<T>` and `&'static T` where `T: ?Sized`, and implement `Diagnostic` for `&T`, `Arc<T>`, `()`, `Option<T>`, slices, arrays, and `Vec`.
* Add `FileBuilder::timezone` in `logforth-append-file` (and re-export `jiff`) to configure the timezone used for rotation boundaries and segment filenames, defaulting to the system timezone.
Expand Down
15 changes: 6 additions & 9 deletions bridges/log/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,22 @@
#![deny(missing_docs)]

use std::ops::Deref;
use std::sync::Arc;

use log::Metadata;
use log::Record;
use logforth_core::Logger;
use logforth_core::record::FilterCriteria;

/// Adapter to use a `logforth` logger instance as a `log` crate logger.
#[derive(Debug)]
/// Adapter to use a [`Logger`] instance as a `log` crate logger.
#[derive(Debug, Clone)]
pub struct LogBridge {
logger: Arc<Logger>,
logger: Logger,
}

impl LogBridge {
/// Create a new `LogBridge` instance.
pub fn new(logger: impl Into<Arc<Logger>>) -> Self {
Self {
logger: logger.into(),
}
/// Creates a new [`LogBridge`] wrapping `logger`.
pub const fn new(logger: Logger) -> Self {
Self { logger }
}
}

Expand Down
173 changes: 58 additions & 115 deletions core/src/logger/log_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::Arc;

use crate::Append;
use crate::Diagnostic;
use crate::Error;
Expand All @@ -21,54 +23,86 @@ use crate::filter::FilterResult;
use crate::record::FilterCriteria;
use crate::record::Record;

/// A logger that dispatches log records to one or more dispatcher.
#[derive(Debug)]
/// A lightweight handle to a shared logging pipeline.
///
/// Cloning a `Logger` increments an internal reference count without duplicating dispatches or
/// appenders. Use [`Logger::noop`] (or [`Logger::default`]) for a zero-allocation logger that
/// discards all records.
#[derive(Debug, Clone, Default)]
pub struct Logger {
dispatches: Vec<Dispatch>,
state: Option<Arc<LoggerState>>,
}

#[derive(Debug)]
struct LoggerState {
dispatches: Box<[Dispatch]>,
error_sink: Box<dyn ErrorSink>,
}

impl Logger {
/// Creates a zero-allocation no-op [`Logger`] that discards all records.
///
/// # Examples
///
/// ```
/// use logforth_core::Logger;
/// use logforth_core::record::Record;
///
/// const NOOP: Logger = Logger::noop();
/// NOOP.log(&Record::builder().payload(format_args!("ignored")).build());
/// ```
pub const fn noop() -> Self {
Self { state: None }
}

pub(super) fn new(dispatches: Vec<Dispatch>, error_sink: Box<dyn ErrorSink>) -> Self {
Self {
dispatches,
error_sink,
if dispatches.is_empty() {
Self::noop()
} else {
Self {
state: Some(Arc::new(LoggerState {
dispatches: dispatches.into_boxed_slice(),
error_sink,
})),
}
}
}
}

impl Logger {
/// Determine if a log message with the specified metadata would be logged.
/// Returns `true` if at least one dispatch accepts `criteria`.
pub fn enabled(&self, criteria: &FilterCriteria) -> bool {
self.dispatches
let Some(state) = self.state.as_deref() else {
return false;
};
state
.dispatches
.iter()
.any(|dispatch| dispatch.enabled(criteria))
}

/// Log the [`Record`].
/// Dispatches `record` across all configured branches.
pub fn log(&self, record: &Record) {
let default_error_sink = &*self.error_sink;
for dispatch in &self.dispatches {
let Some(state) = self.state.as_deref() else {
return;
};
let default_error_sink = &*state.error_sink;
for dispatch in &state.dispatches {
dispatch.log(record, default_error_sink);
}
}

/// Flush any buffered records.
/// Flushes all appenders across all configured branches.
pub fn flush(&self) {
let default_error_sink = &*self.error_sink;
for dispatch in &self.dispatches {
let Some(state) = self.state.as_deref() else {
return;
};
let default_error_sink = &*state.error_sink;
for dispatch in &state.dispatches {
dispatch.flush(default_error_sink);
}
}
}

/// A grouped set of appenders and filters.
///
/// The [`Logger`] facade dispatches log records to one or more [`Dispatch`] instances.
/// Each [`Dispatch`] instance contains a set of filters and appenders.
///
/// `filters` are used to determine whether a log record should be passed to the appenders.
/// `appends` are used to write log records to a destination.
/// A grouped set of filters, diagnostics, and appenders.
#[derive(Debug)]
pub(super) struct Dispatch {
filters: Vec<Box<dyn Filter>>,
Expand All @@ -86,7 +120,7 @@ impl Dispatch {
) -> Self {
debug_assert!(
!appends.is_empty(),
"A Dispatch must have at least one filter"
"A Dispatch must have at least one appender"
);

Self {
Expand Down Expand Up @@ -137,94 +171,3 @@ impl Dispatch {
}
}
}

#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::Mutex;

use super::*;
use crate::builder;
use crate::error::BlackHoleErrorSink;

#[derive(Debug)]
struct FailingAppender(&'static str);

impl Append for FailingAppender {
fn append(&self, _: &Record, _: &dyn Diagnostic) -> Result<(), Error> {
Err(Error::new(self.0))
}

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

#[derive(Debug)]
struct RecordingAppender(Arc<Mutex<Vec<String>>>);

impl Append for RecordingAppender {
fn append(&self, record: &Record, _: &dyn Diagnostic) -> Result<(), Error> {
self.0.lock().unwrap().push(record.payload().to_string());
Ok(())
}

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

#[derive(Debug, Default)]
struct RecordingErrorSink {
errors: Mutex<Vec<String>>,
}

impl ErrorSink for RecordingErrorSink {
fn sink(&self, err: &Error) {
self.errors.lock().unwrap().push(format!("{err:#}"));
}
}

#[test]
fn logger_routes_errors_with_dispatch_fallback_and_override() {
let logger_errors = Arc::new(RecordingErrorSink::default());
let override_errors = Arc::new(RecordingErrorSink::default());
let delivered = Arc::new(Mutex::new(Vec::new()));

let logger = builder()
.error_sink(logger_errors.clone())
.dispatch(|d| {
d.append(FailingAppender("primary failed"))
.append(RecordingAppender(delivered.clone()))
})
.dispatch(|d| {
d.error_sink(BlackHoleErrorSink::new())
.append(FailingAppender("silenced failed"))
})
.dispatch(|d| {
d.error_sink(override_errors.clone())
.append(FailingAppender("override failed"))
})
.build();

let record = Record::builder().payload(format_args!("hello")).build();
logger.log(&record);
logger.flush();

assert_eq!(&*delivered.lock().unwrap(), &["hello"]);
assert_eq!(
&*logger_errors.errors.lock().unwrap(),
&[
"failed to append record: primary failed",
"failed to flush appender: primary failed",
]
);
assert_eq!(
&*override_errors.errors.lock().unwrap(),
&[
"failed to append record: override failed",
"failed to flush appender: override failed",
]
);
}
}
Loading
Loading