diff --git a/src/format.rs b/src/format.rs index 94caa1c..8f9f76d 100644 --- a/src/format.rs +++ b/src/format.rs @@ -1,6 +1,6 @@ #[cfg(feature = "ansi")] use crate::nu_ansi_term::{Color, Style}; -use std::{fmt, io}; +use std::{ffi::OsStr, fmt, io, path::Path}; use time::{format_description::FormatItem, formatting::Formattable, OffsetDateTime}; use tracing::{Level, Metadata}; use tracing_subscriber::fmt::{format::Writer, time::FormatTime}; @@ -208,13 +208,34 @@ pub(crate) struct FormatProcessData<'a> { pub(crate) with_target: bool, #[cfg(feature = "ansi")] pub(crate) ansi: bool, + pub(crate) with_trimmed_directory: bool, + pub(crate) with_strip_prefix: &'a Option, } impl<'a> fmt::Display for FormatProcessData<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let thread_name = self.thread_name; let target = self.metadata.target(); - let file = self.metadata.file().unwrap_or(""); + let file = self + .metadata + .file() + .map(|f| { + if self.with_trimmed_directory { + let path = Path::new(f); + path.file_name() + .map(OsStr::to_str) + .unwrap_or(Some(f)) + .unwrap_or(f) + } else if let Some(prefix) = &self.with_strip_prefix { + Path::new(f) + .strip_prefix(prefix) + .map(|path| path.to_str().unwrap()) + .unwrap_or(f) + } else { + f + } + }) + .unwrap_or(""); let line = match self.metadata.line() { Some(line) => format!("{}", line), None => String::new(), diff --git a/src/lib.rs b/src/lib.rs index 540b965..aed3f20 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -150,6 +150,8 @@ pub struct Glog { with_span_context: bool, with_thread_names: bool, with_target: bool, + with_trimmed_directory: bool, + with_strip_prefix: Option, } impl Glog { @@ -168,6 +170,8 @@ impl Glog { with_thread_names: self.with_thread_names, with_target: self.with_target, with_span_context: self.with_span_context, + with_trimmed_directory: self.with_trimmed_directory, + with_strip_prefix: self.with_strip_prefix, } } @@ -185,6 +189,20 @@ impl Glog { } } + pub fn with_trimmed_directory(self, with_trimmed_directory: bool) -> Glog { + Glog { + with_trimmed_directory, + ..self + } + } + + pub fn with_strip_prefix(self, with_strip_prefix: Option) -> Glog { + Glog { + with_strip_prefix: with_strip_prefix.map(|s|s.to_string()), + ..self + } + } + /// Sets whether or not the span context is included. Defaults to true. /// /// By default, formatters building atop of [`mod@tracing_subscriber::fmt`] @@ -220,6 +238,8 @@ impl Default for Glog { with_thread_names: false, with_target: false, with_span_context: true, + with_trimmed_directory: false, + with_strip_prefix: None, } } } @@ -265,6 +285,8 @@ where with_target: self.with_target, #[cfg(feature = "ansi")] ansi: writer.has_ansi_escapes(), + with_trimmed_directory: self.with_trimmed_directory, + with_strip_prefix: &self.with_strip_prefix, }; write!(writer, "{}] ", data)?;