Skip to content

Commit c3435e2

Browse files
committed
Retain source location from log crate if they are &'static
1 parent 85eff17 commit c3435e2

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

spdlog/src/record.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,7 @@ impl<'a> Record<'a> {
125125
},
126126
inner: Cow::Owned(RecordInner {
127127
level: record.level().into(),
128-
// `module_path` and `file` in `log::Record` are not `'static`
129-
source_location: None,
128+
source_location: SourceLocation::from_log_crate_record(record),
130129
time,
131130
}),
132131
}

spdlog/src/source_location.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,26 @@ impl SourceLocation {
6767
pub fn column(&self) -> u32 {
6868
self.column
6969
}
70+
71+
#[cfg(feature = "log")]
72+
#[must_use]
73+
pub(crate) fn from_log_crate_record(record: &log::Record) -> Option<Self> {
74+
let (module_path, file, line) = (
75+
record.module_path_static(),
76+
record.file_static(),
77+
record.line(),
78+
);
79+
80+
match (module_path, file, line) {
81+
(None, None, None) => None,
82+
_ => Some(Self {
83+
module_path: module_path.unwrap_or(""),
84+
file: file.unwrap_or(""),
85+
line: line.unwrap_or(0),
86+
column: 0,
87+
}),
88+
}
89+
}
7090
}
7191

7292
/// Constructs a [`SourceLocation`] with current source location.

spdlog/tests/log_crate_proxy.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
use std::sync::Arc;
2+
3+
use spdlog::{
4+
formatter::{pattern, PatternFormatter},
5+
prelude::*,
6+
sink::WriteSink,
7+
};
8+
9+
#[cfg(feature = "log")]
10+
#[test]
11+
fn test_source_location() {
12+
let formatter = Box::new(PatternFormatter::new(pattern!(
13+
"({module_path}::{file_name}) {payload}{eol}"
14+
)));
15+
let sink = Arc::new(
16+
WriteSink::builder()
17+
.formatter(formatter)
18+
.target(Vec::new())
19+
.build()
20+
.unwrap(),
21+
);
22+
let logger = Arc::new(Logger::builder().sink(sink.clone()).build().unwrap());
23+
24+
spdlog::init_log_crate_proxy().unwrap();
25+
spdlog::log_crate_proxy().set_logger(Some(logger));
26+
log::set_max_level(log::LevelFilter::Trace);
27+
28+
log::info!("text");
29+
assert_eq!(
30+
String::from_utf8(sink.clone_target()).unwrap(),
31+
"(log_crate_proxy::log_crate_proxy.rs) text\n"
32+
);
33+
}

0 commit comments

Comments
 (0)