diff --git a/CHANGELOG.md b/CHANGELOG.md index 2234122..555cc8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to this project will be documented in this file. * Bump minimum supported Rust version (MSRV) to 1.91.0. * `logforth-append-opentelemetry` upgrades `opentelemetry`, `opentelemetry-otlp` and `opentelemetry_sdk` to 0.33.1. * Upgrade `jiff` to 1.0. +* Redesign `logforth_core::Error` without `anyhow`, boxing its payload and removing `with_context`, `sources`, `from_io_error`, and `from_fmt_error`. ## [0.30.1] 2026-06-03 diff --git a/Cargo.toml b/Cargo.toml index 9a37f98..0277e2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,6 @@ logforth-layout-logfmt = { version = "0.4.0", path = "layouts/logfmt" } logforth-layout-text = { version = "0.4.0", path = "layouts/text" } # Crates.io dependencies -anyhow = { version = "1.0" } clap = { version = "4.5.49", features = ["derive"] } colored = { version = "3.0" } ctor = { version = "1.0.6" } diff --git a/appenders/file/src/append.rs b/appenders/file/src/append.rs index f328fa9..5613492 100644 --- a/appenders/file/src/append.rs +++ b/appenders/file/src/append.rs @@ -164,13 +164,17 @@ impl Append for File { let mut bytes = self.layout.format(record, diags)?; bytes.push(b'\n'); let mut writer = self.writer(); - writer.write_all(&bytes).map_err(Error::from_io_error)?; + writer + .write_all(&bytes) + .map_err(|err| Error::new("failed to write log file").with_source(err))?; Ok(()) } fn flush(&self) -> Result<(), Error> { let mut writer = self.writer(); - writer.flush().map_err(Error::from_io_error)?; + writer + .flush() + .map_err(|err| Error::new("failed to flush log file").with_source(err))?; Ok(()) } } diff --git a/appenders/journald/src/lib.rs b/appenders/journald/src/lib.rs index 3e349e4..09a32dd 100644 --- a/appenders/journald/src/lib.rs +++ b/appenders/journald/src/lib.rs @@ -121,7 +121,8 @@ impl Journald { /// /// Fails if the journald socket couldn't be opened. pub fn new() -> Result { - let socket = UnixDatagram::unbound().map_err(Error::from_io_error)?; + let socket = UnixDatagram::unbound() + .map_err(|err| Error::new("failed to open journald socket").with_source(err))?; let sub = Self { socket, extra_fields: Vec::new(), @@ -216,7 +217,7 @@ impl Journald { if Some(libc::EMSGSIZE) == err.raw_os_error() { self.send_large_payload(payload) } else { - Err(Error::from_io_error(err)) + Err(Error::new("failed to send payload to journald").with_source(err)) } }) } diff --git a/appenders/syslog/src/lib.rs b/appenders/syslog/src/lib.rs index 3440935..4113044 100644 --- a/appenders/syslog/src/lib.rs +++ b/appenders/syslog/src/lib.rs @@ -298,13 +298,15 @@ impl Append for Syslog { let mut sender = self.sender(); sender .send_formatted(&message) - .map_err(Error::from_io_error)?; + .map_err(|err| Error::new("failed to send syslog message").with_source(err))?; Ok(()) } fn flush(&self) -> Result<(), Error> { let mut sender = self.sender(); - sender.flush().map_err(Error::from_io_error)?; + sender + .flush() + .map_err(|err| Error::new("failed to flush syslog writer").with_source(err))?; Ok(()) } } diff --git a/core/Cargo.toml b/core/Cargo.toml index 266dd72..44ab816 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -36,8 +36,6 @@ default = [] serde = ["dep:serde"] [dependencies] -anyhow = { workspace = true } - # Optional dependencies serde = { workspace = true, optional = true } diff --git a/core/src/append/stdio.rs b/core/src/append/stdio.rs index 693e15f..36d7bf2 100644 --- a/core/src/append/stdio.rs +++ b/core/src/append/stdio.rs @@ -68,12 +68,14 @@ impl Append for Stdout { bytes.push(b'\n'); std::io::stdout() .write_all(&bytes) - .map_err(Error::from_io_error)?; + .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(Error::from_io_error)?; + std::io::stdout() + .flush() + .map_err(|err| Error::new("failed to flush stdout").with_source(err))?; Ok(()) } } @@ -125,12 +127,14 @@ impl Append for Stderr { bytes.push(b'\n'); std::io::stderr() .write_all(&bytes) - .map_err(Error::from_io_error)?; + .map_err(|err| Error::new("failed to write to stderr").with_source(err))?; Ok(()) } fn flush(&self) -> Result<(), Error> { - std::io::stderr().flush().map_err(Error::from_io_error)?; + std::io::stderr() + .flush() + .map_err(|err| Error::new("failed to flush stderr").with_source(err))?; Ok(()) } } diff --git a/core/src/error.rs b/core/src/error.rs index 84c40f3..4e033f2 100644 --- a/core/src/error.rs +++ b/core/src/error.rs @@ -12,36 +12,52 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::borrow::Cow; +use std::error::Error as StdError; use std::fmt; -use std::io; -/// The error struct of logforth. +/// An error returned or reported by Logforth components. pub struct Error { - message: String, - source: Option, - context: Vec<(&'static str, String)>, + state: Box, +} + +struct ErrorState { + message: Cow<'static, str>, + source: Option>, +} + +impl Error { + /// Create a new [`Error`] with the given message. + pub fn new(message: impl Into>) -> Self { + Self { + state: Box::new(ErrorState { + message: message.into(), + source: None, + }), + } + } + + /// Return the error message. + pub fn message(&self) -> &str { + &self.state.message + } + + /// Attach or replace the underlying causal error. + pub fn with_source( + mut self, + src: impl Into>, + ) -> Self { + self.state.source = Some(src.into()); + self + } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.message)?; - - if !self.context.is_empty() { - write!(f, ", context: {{ ")?; - write!( - f, - "{}", - self.context - .iter() - .map(|(k, v)| format!("{k}: {v}")) - .collect::>() - .join(", ") - )?; - write!(f, " }}")?; - } + f.write_str(&self.state.message)?; - if let Some(source) = &self.source { - write!(f, ", source: {source}")?; + if let Some(source) = &self.state.source { + write!(f, ": {source}")?; } Ok(()) @@ -50,82 +66,113 @@ impl fmt::Display for Error { impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // If alternate has been specified, we will print like Debug. if f.alternate() { - let mut de = f.debug_struct("Error"); - de.field("message", &self.message); - de.field("context", &self.context); - de.field("sources", &self.source); - return de.finish(); + return f + .debug_struct("Error") + .field("message", &self.state.message) + .field("source", &self.state.source) + .finish(); } - write!(f, "{}", self.message)?; - writeln!(f)?; + write!(f, "{}", self.state.message)?; - if !self.context.is_empty() { + if let Some(source) = &self.state.source { writeln!(f)?; - writeln!(f, "Context:")?; - for (k, v) in self.context.iter() { - writeln!(f, " {k}: {v}")?; - } - } - - if let Some(source) = &self.source { writeln!(f)?; - writeln!(f, "Source:")?; - writeln!(f, " {source:#}")?; + writeln!(f, "Caused by:")?; + let mut curr: Option<&(dyn StdError + 'static)> = Some(source.as_ref()); + let mut index = 0usize; + while let Some(err) = curr { + if let Some(lf) = err.downcast_ref::() { + writeln!(f, " {index}: {}", lf.message())?; + } else { + writeln!(f, " {index}: {err}")?; + } + curr = err.source(); + index += 1; + } } Ok(()) } } -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - self.source.as_ref().map(|v| v.as_ref()) +impl StdError for Error { + fn source(&self) -> Option<&(dyn StdError + 'static)> { + self.state + .source + .as_deref() + .map(|err| err as &(dyn StdError + 'static)) } } -impl Error { - /// Create a new Error with error kind and message. - pub fn new(message: impl Into) -> Self { - Self { - message: message.into(), - source: None, - context: vec![], - } - } +#[cfg(test)] +mod tests { + use std::io; - /// Add one more context in error. - pub fn with_context(mut self, key: &'static str, value: impl ToString) -> Self { - self.context.push((key, value.to_string())); - self + use super::*; + + fn assert_send_sync_static() {} + + #[derive(Debug)] + struct TransportError { + detail: &'static str, + cause: io::Error, } - /// Set source for error. - /// - /// # Panics - /// - /// If the source has been set, we will raise a panic here. - pub fn with_source(mut self, src: impl Into) -> Self { - assert!(self.source.is_none(), "the source error has been set"); + impl fmt::Display for TransportError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.detail) + } + } - self.source = Some(src.into()); - self + impl StdError for TransportError { + fn source(&self) -> Option<&(dyn StdError + 'static)> { + Some(&self.cause) + } } - /// Return an iterator over all sources of this error. - pub fn sources(&self) -> impl ExactSizeIterator { - self.source.iter().map(|v| v.as_ref()) + #[test] + fn error_layout_and_auto_traits() { + assert_send_sync_static::(); + assert_eq!(size_of::(), size_of::()); + assert_eq!(size_of::>(), size_of::()); } - /// Default constructor for [`Error`] from [`io::Error`]. - pub fn from_io_error(err: io::Error) -> Error { - Error::new("failed to perform io").with_source(err) + #[test] + fn error_display_debug_and_downcast_chain() { + let leaf = io::Error::new(io::ErrorKind::BrokenPipe, "broken pipe"); + let transport = TransportError { + detail: "connection reset", + cause: leaf, + }; + let middle = Error::new("failed to export batch").with_source(transport); + let outer = Error::new("failed to flush appender").with_source(middle); + + assert_eq!(outer.message(), "failed to flush appender"); + assert_eq!( + outer.to_string(), + "failed to flush appender: failed to export batch: connection reset" + ); + + let debug = format!("{outer:?}"); + assert_eq!( + debug, + "failed to flush appender\n\nCaused by:\n 0: failed to export batch\n 1: connection reset\n 2: broken pipe\n" + ); + + let hop1 = outer.source().unwrap(); + let hop2 = hop1.source().unwrap(); + let hop3 = hop2.source().unwrap().downcast_ref::().unwrap(); + assert_eq!(hop3.kind(), io::ErrorKind::BrokenPipe); } - /// Default constructor for [`Error`] from [`fmt::Error`]. - pub fn from_fmt_error(err: fmt::Error) -> Error { - Error::new("failed to perform format").with_source(err) + #[test] + fn with_source_replaces_existing_source_without_panicking() { + let err = Error::new("operation failed") + .with_source("first cause") + .with_source("second cause"); + + assert_eq!(err.to_string(), "operation failed: second cause"); } } diff --git a/core/src/lib.rs b/core/src/lib.rs index dc5f75f..578f8bf 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -32,7 +32,7 @@ pub use self::layout::Layout; pub use self::trap::Trap; mod error; -pub use self::error::*; +pub use self::error::Error; mod logger; pub use self::logger::*;