diff --git a/spdlog/src/record.rs b/spdlog/src/record.rs index f6bb4385..ed1a41f1 100644 --- a/spdlog/src/record.rs +++ b/spdlog/src/record.rs @@ -125,8 +125,7 @@ impl<'a> Record<'a> { }, inner: Cow::Owned(RecordInner { level: record.level().into(), - // `module_path` and `file` in `log::Record` are not `'static` - source_location: None, + source_location: SourceLocation::from_log_crate_record(record), time, }), } diff --git a/spdlog/src/source_location.rs b/spdlog/src/source_location.rs index 23836ca1..ad47fcf4 100644 --- a/spdlog/src/source_location.rs +++ b/spdlog/src/source_location.rs @@ -67,6 +67,26 @@ impl SourceLocation { pub fn column(&self) -> u32 { self.column } + + #[cfg(feature = "log")] + #[must_use] + pub(crate) fn from_log_crate_record(record: &log::Record) -> Option { + let (module_path, file, line) = ( + record.module_path_static(), + record.file_static(), + record.line(), + ); + + match (module_path, file, line) { + (None, None, None) => None, + _ => Some(Self { + module_path: module_path.unwrap_or(""), + file: file.unwrap_or(""), + line: line.unwrap_or(0), + column: 0, + }), + } + } } /// Constructs a [`SourceLocation`] with current source location. diff --git a/spdlog/tests/log_crate_proxy.rs b/spdlog/tests/log_crate_proxy.rs new file mode 100644 index 00000000..45592831 --- /dev/null +++ b/spdlog/tests/log_crate_proxy.rs @@ -0,0 +1,33 @@ +use std::sync::Arc; + +use spdlog::{ + formatter::{pattern, PatternFormatter}, + prelude::*, + sink::WriteSink, +}; + +#[cfg(feature = "log")] +#[test] +fn test_source_location() { + let formatter = Box::new(PatternFormatter::new(pattern!( + "({module_path}::{file_name}) {payload}{eol}" + ))); + let sink = Arc::new( + WriteSink::builder() + .formatter(formatter) + .target(Vec::new()) + .build() + .unwrap(), + ); + let logger = Arc::new(Logger::builder().sink(sink.clone()).build().unwrap()); + + spdlog::init_log_crate_proxy().unwrap(); + spdlog::log_crate_proxy().set_logger(Some(logger)); + log::set_max_level(log::LevelFilter::Trace); + + log::info!("text"); + assert_eq!( + String::from_utf8(sink.clone_target()).unwrap(), + "(log_crate_proxy::log_crate_proxy.rs) text\n" + ); +}