dylanbstorey / pyo3-pylogger

log messages for pyo3 embedded Python applications using the logging module
Apache License 2.0
3 stars 2 forks source link

Some log levels are not replicated on Rust side #2

Closed spitfire05 closed 1 year ago

spitfire05 commented 1 year ago

Expanding on the readme's example:

bin.rs:

use log::{info, warn};
use pyo3::prelude::*;
fn main() {
    // register the host handler with python logger, providing a logger target
    pyo3_pylogger::register("example_application_py_logger");

    // initialize up a logger
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init();
    //just show the logger working from Rust.
    info!("Just some normal information!");
    warn!("Something spooky happened!");

    // Ask pyo3 to set up embedded Python interpreter
    pyo3::prepare_freethreaded_python();
    Python::with_gil(|py| {
        // Python code can now `import logging` as usual
        py.run("import logging", None, None).unwrap();
        py.run("logging.debug('DEBUG')", None, None).unwrap();
        py.run("logging.info('INFO')", None, None).unwrap();
        py.run("logging.warning('WARNING')", None, None).unwrap();
        py.run("logging.error('ERROR')", None, None).unwrap();
        py.run("logging.critical('CRITICAL')", None, None).unwrap();
    });
}

Cargo.toml

[package]
name = "pyo3-pylogger-test"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
env_logger = "0.10.0"
log = "0.4.17"
pyo3 = "0.17"
pyo3-pylogger = "0.2.0"

All messages above WARNING level will not be logged on the host side:

pyo3-pylogger-test [ master][?][📦 v0.1.0][🦀 v1.67.1]
❯ RUST_LOG=trace cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.11s
     Running `target/debug/pyo3-pylogger-test`
[2023-03-06T16:48:58Z INFO  pyo3_pylogger_test] Just some normal information!
[2023-03-06T16:48:58Z WARN  pyo3_pylogger_test] Something spooky happened!
[2023-03-06T16:48:58Z WARN  example_application_py_logger] WARNING
[2023-03-06T16:48:58Z ERROR example_application_py_logger] ERROR
[2023-03-06T16:48:58Z ERROR example_application_py_logger] CRITICAL
dylanbstorey commented 1 year ago

Python's root logger defaults to "WARNING", so running something like should handle that. I've updated the code sample and readme appropriately.

py.run("logging.getLogger().setLevel(0)", None, None).unwrap();