Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retain source location from log crate if they are &'static #23

Merged
merged 1 commit into from
Feb 6, 2023
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
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"
);
}