Skip to content

Commit

Permalink
Retain source location from log crate if they are &'static
Browse files Browse the repository at this point in the history
  • Loading branch information
SpriteOvO committed Feb 6, 2023
1 parent 85eff17 commit c3435e2
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
3 changes: 1 addition & 2 deletions spdlog/src/record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}),
}
Expand Down
20 changes: 20 additions & 0 deletions spdlog/src/source_location.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self> {
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.
Expand Down
33 changes: 33 additions & 0 deletions spdlog/tests/log_crate_proxy.rs
Original file line number Diff line number Diff line change
@@ -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"
);
}

0 comments on commit c3435e2

Please sign in to comment.