Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
8 changes: 6 additions & 2 deletions appenders/file/src/append.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
}
Expand Down
5 changes: 3 additions & 2 deletions appenders/journald/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ impl Journald {
///
/// Fails if the journald socket couldn't be opened.
pub fn new() -> Result<Self, Error> {
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(),
Expand Down Expand Up @@ -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))
}
})
}
Expand Down
6 changes: 4 additions & 2 deletions appenders/syslog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
}
Expand Down
2 changes: 0 additions & 2 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ default = []
serde = ["dep:serde"]

[dependencies]
anyhow = { workspace = true }

# Optional dependencies
serde = { workspace = true, optional = true }

Expand Down
12 changes: 8 additions & 4 deletions core/src/append/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
}
Expand Down Expand Up @@ -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(())
}
}
195 changes: 121 additions & 74 deletions core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<anyhow::Error>,
context: Vec<(&'static str, String)>,
state: Box<ErrorState>,
}

struct ErrorState {
message: Cow<'static, str>,
source: Option<Box<dyn StdError + Send + Sync + 'static>>,
}

impl Error {
/// Create a new [`Error`] with the given message.
pub fn new(message: impl Into<Cow<'static, str>>) -> 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<Box<dyn StdError + Send + Sync + 'static>>,
) -> 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::<Vec<_>>()
.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(())
Expand All @@ -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::<Error>() {
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<String>) -> 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<T: 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<anyhow::Error>) -> 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<Item = &(dyn std::error::Error + 'static)> {
self.source.iter().map(|v| v.as_ref())
#[test]
fn error_layout_and_auto_traits() {
assert_send_sync_static::<Error>();
assert_eq!(size_of::<Error>(), size_of::<usize>());
assert_eq!(size_of::<Result<(), Error>>(), size_of::<usize>());
}

/// 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::<io::Error>().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");
}
}
2 changes: 1 addition & 1 deletion core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down
Loading