From 442e17f9a8fa5617eb0f257c29b1e506acbe9377 Mon Sep 17 00:00:00 2001 From: "Christoph J. Scherr" Date: Fri, 30 Aug 2024 17:39:10 +0200 Subject: [PATCH] fix: let logger use the crate name of the end-crate #91 --- members/libpt-core/src/lib.rs | 13 +++++++++++++ members/libpt-log/src/lib.rs | 8 +++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/members/libpt-core/src/lib.rs b/members/libpt-core/src/lib.rs index 848cd5c..93e71fd 100644 --- a/members/libpt-core/src/lib.rs +++ b/members/libpt-core/src/lib.rs @@ -8,3 +8,16 @@ /// macros to make things faster in your code pub mod macros; + +/// ## Get the name of the crate that uses your library +/// +/// Let's say you're writing the library `foo` and need the name of the crate that uses `foo`. With +/// this function, you can get the name of the crate that uses `foo`. +/// +/// Will return [None] if [`std::env::current_exe()`] errors or if conversion to [String] from [std::ffi::OsStr] fails. +pub fn get_crate_name() -> Option { + if let Ok(exe) = std::env::current_exe() { + return Some(exe.file_stem()?.to_str()?.to_string()); + } + None +} diff --git a/members/libpt-log/src/lib.rs b/members/libpt-log/src/lib.rs index fa5c697..e5f7f8b 100644 --- a/members/libpt-log/src/lib.rs +++ b/members/libpt-log/src/lib.rs @@ -480,5 +480,11 @@ impl Default for Logger { } fn new_file_appender(log_dir: PathBuf) -> tracing_appender::rolling::RollingFileAppender { - tracing_appender::rolling::daily(log_dir, format!("{}.log", env!("CARGO_CRATE_NAME"))) + tracing_appender::rolling::daily( + log_dir, + format!( + "{}.log", + libpt_core::get_crate_name().unwrap_or_else(|| "logfile".to_string()) + ), + ) }