Skip to content

Commit d23b98a

Browse files
authored
Allow the specficiation of a logging prefix when setting up a logger (#70)
Allow the specficiation of a logging prefix when setting up a logger
1 parent 042aac9 commit d23b98a

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

examples/hello_world/src/lib.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ fn log_hello() {
1515

1616
#[pymodule]
1717
fn hello_world(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
18-
let _ = Logger::new(py, Caching::LoggersAndLevels)?.install();
18+
let _ = Logger::new(py, Caching::LoggersAndLevels)?
19+
.set_prefix("test_prefix")
20+
.install();
1921

2022
m.add_wrapped(wrap_pyfunction!(log_hello))?;
2123

src/lib.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,9 @@ pub struct Logger {
303303
/// full paths, with `::` separaters (eg. before converting them from Rust to Python).
304304
filters: HashMap<String, LevelFilter>,
305305

306+
/// The prefix to prepend to all log targets
307+
prefix: Option<String>,
308+
306309
/// The imported Python `logging` module.
307310
logging: Py<PyModule>,
308311

@@ -329,6 +332,7 @@ impl Logger {
329332
Ok(Self {
330333
top_filter: LevelFilter::Debug,
331334
filters: HashMap::new(),
335+
prefix: None,
332336
logging: logging.into(),
333337
caching,
334338
cache: Default::default(),
@@ -401,6 +405,15 @@ impl Logger {
401405
self
402406
}
403407

408+
/// Sets a prefix to prepend to log targets before sending log messages to Python.
409+
///
410+
/// This allows for Python-side arrangements where logging configurations are only
411+
/// attached to logging names other than the root.
412+
pub fn set_prefix(mut self, prefix: &str) -> Self {
413+
self.prefix = Some(prefix.replace("::", "."));
414+
self
415+
}
416+
404417
/// Finds a node in the cache.
405418
///
406419
/// The hierarchy separator is `::`.
@@ -433,7 +446,11 @@ impl Logger {
433446
) -> PyResult<Option<Py<PyAny>>> {
434447
let msg = format!("{}", record.args());
435448
let log_level = map_level(record.level());
436-
let target = record.target().replace("::", ".");
449+
let mut target = record.target().replace("::", ".");
450+
target = match &self.prefix {
451+
Some(prefix) => format!("{}.{}", prefix, target),
452+
None => target,
453+
};
437454
let cached_logger = cache
438455
.as_ref()
439456
.and_then(|node| node.local.as_ref())

0 commit comments

Comments
 (0)