pyo3-log-0.9.0/.cargo_vcs_info.json0000644000000001360000000000100125130ustar { "git": { "sha1": "6834c15fe2f4706b0bd992af89ee87a29c6a8275" }, "path_in_vcs": "" }pyo3-log-0.9.0/.github/codecov.yml000064400000000000000000000002151046102023000150060ustar 00000000000000comment: layout: "diff, flags, files" require_changes: true coverage: status: project: default: informational: true pyo3-log-0.9.0/.github/workflows/audit.yaml000064400000000000000000000005321046102023000166720ustar 00000000000000name: Security audit on: pull_request: push: branches: - main schedule: - cron: '0 0 * * 0' jobs: security_audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rs/audit-check@35b7b53b1e25b55642157ac01b4adceb5b9ebef3 with: token: ${{ secrets.GITHUB_TOKEN }} pyo3-log-0.9.0/.github/workflows/test.yaml000064400000000000000000000077221046102023000165530ustar 00000000000000name: test on: push: pull_request: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: full jobs: test: name: Build & test strategy: fail-fast: false matrix: os: - ubuntu-latest - macos-latest - windows-latest rust: - stable - beta - nightly python-version: - "3.7" - "3.8" - "3.9" - "3.10" - "3.11" runs-on: ${{ matrix.os }} steps: - name: checkout uses: actions/checkout@v3 - name: Install Rust ${{ matrix.rust }} uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.rust }} - name: Install Python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} architecture: x64 - name: Restore cache uses: Swatinem/rust-cache@v2 - name: Build & test run: cargo test --all-features test-minimal-versions: name: Build with the minimal supported versions runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: # MSRV as set in Cargo.toml toolchain: 1.48.0 default: true profile: minimal - name: Install Python uses: actions/setup-python@v2 with: python-version: "3.7" architecture: x64 - name: Restore cache uses: Swatinem/rust-cache@v1 - name: Install the minimal versions of dependencies env: # `-Z minimal-versions` is unstable, so we set # `RUSTC_BOOTSTRAP=1` to be able to use it on stable RUSTC_BOOTSTRAP: "1" run: cargo update -Z minimal-versions - name: Build & test run: cargo test --all-features rustfmt: name: Check formatting runs-on: ubuntu-latest steps: - name: checkout uses: actions/checkout@v3 - name: Install Rust uses: dtolnay/rust-toolchain@stable - run: cargo fmt --all -- --check links: name: Check documentation links runs-on: ubuntu-latest steps: - name: checkout uses: actions/checkout@v3 - name: Install Rust stable uses: dtolnay/rust-toolchain@stable - name: Restore cache uses: Swatinem/rust-cache@v2 - name: Check links run: cargo rustdoc --all-features -- -D warnings clippy: name: Clippy lints runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v3 - name: Install Rust stable uses: dtolnay/rust-toolchain@stable - name: Restore cache uses: Swatinem/rust-cache@v2 - name: Run clippy linter run: cargo clippy --all --tests -- -D clippy::all -D warnings coverage: name: Coverage runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v3 - name: Install Rust nightly uses: dtolnay/rust-toolchain@nightly - name: Restore cache uses: Swatinem/rust-cache@v2 - name: Download cargo-tarpaulin from the GitHub releases run: | mkdir -p "${HOME}/.local/bin" curl -sL https://github.com/xd009642/tarpaulin/releases/download/0.24.0/cargo-tarpaulin-x86_64-unknown-linux-gnu.tar.gz | tar xvz -C "${HOME}/.local/bin" echo "$HOME/.local/bin" >> $GITHUB_PATH - name: Run cargo-tarpaulin run: cargo tarpaulin --all-features --run-types Doctests,Tests --out Xml - name: Upload to codecov.io uses: codecov/codecov-action@d9f34f8cd5cb3b3eb79b3e4b5dae3a16df499a70 # v3.1.1 with: token: ${{ secrets.CODECOV_TOKEN }} - name: Archive code coverage results uses: actions/upload-artifact@v3 with: name: code-coverage-report path: cobertura.xml retention-days: 30 pyo3-log-0.9.0/.gitignore000064400000000000000000000000561046102023000132740ustar 00000000000000/target /Cargo.lock /examples/hello_world/env pyo3-log-0.9.0/CHANGELOG.md000064400000000000000000000017411046102023000131170ustar 00000000000000# 0.9.0 * Bump lowest allowed version of pyo3 to 0.15 ‒ this prevents linking multiple pyo3 versions together. # 0.8.4 * Allow pyo3 0.20. # 0.8.3 * LogRecord takes tuple as `args`, provide an empty one and not a `None` (#28). # 0.8.2 * Allow pyo3 0.19. # 0.8.1 * Don't insist on newest version of pyo3 as a dependency, allow older versions too. # 0.8.0 * Update to pyo3 0.18. # 0.7.0 * Update to pyo3 0.17. # 0.6.0 * Update to pyo3 0.16. # 0.5.0 * Update to pyo3 0.15. # 0.4.1 * Docs: Point out the need to handle GIL in around threads. # 0.4.0 * Upgrade to pyo3 0.14. # 0.3.1 * Don't confuse Trace level with NOTSET in python. # 0.3.0 * Upgrade to pyo3 0.13. # 0.2.2 * Fix of versioning of dependencies. # 0.2.1 * Internal dependency update (arc-swap on 1.0). # 0.2.0 * Bump version of pyo3 to 0.12. # 0.1.2 * Remove confusing/irrelevant copy-pasted part of README. # 0.1.1 * Bug: Remove stray println/dbgs from the code. # 0.1.0 * Initial release. pyo3-log-0.9.0/Cargo.toml0000644000000024120000000000100105100ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.48.0" name = "pyo3-log" version = "0.9.0" authors = ["Michal 'vorner' Vaner "] description = "Logging bridge from pyo3 native extension to python" documentation = "https://docs.rs/pyo3-log" readme = "README.md" keywords = [ "pyo3", "python", "logging", ] categories = ["development-tools::debugging"] license = "Apache-2.0 OR MIT" repository = "https://github.com/vorner/pyo3-log" [dependencies.arc-swap] version = "~1" [dependencies.log] version = "~0.4.4" features = ["std"] default-features = false [dependencies.pyo3] version = ">=0.15, <0.21" default-features = false [dev-dependencies.pyo3] version = ">=0.15, <0.21" features = [ "auto-initialize", "macros", ] default-features = false [dev-dependencies.syn] version = "~1.0.13" pyo3-log-0.9.0/Cargo.toml.orig000064400000000000000000000020621046102023000141720ustar 00000000000000[package] name = "pyo3-log" version = "0.9.0" authors = ["Michal 'vorner' Vaner "] description = "Logging bridge from pyo3 native extension to python" documentation = "https://docs.rs/pyo3-log" repository = "https://github.com/vorner/pyo3-log" readme = "README.md" keywords = ["pyo3", "python", "logging"] categories = ["development-tools::debugging"] edition = "2018" license = "Apache-2.0 OR MIT" rust-version = "1.48.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] arc-swap = "~1" # It's OK to ask for std on log, because pyo3 needs it too. log = { version = "~0.4.4", default-features = false, features = ["std"] } pyo3 = { version = ">=0.15, <0.21", default-features = false } [dev-dependencies] pyo3 = { version = ">=0.15, <0.21", default-features = false, features = ["auto-initialize", "macros"] } # `pyo3-macros` is lying about the minimal version for its `syn` dependency. # Because we're testing with `-Zminimal-versions`, we need to explicitly set it here. syn = "~1.0.13" pyo3-log-0.9.0/LICENSE-APACHE000064400000000000000000000251371046102023000132370ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pyo3-log-0.9.0/LICENSE-MIT000064400000000000000000000020471046102023000127420ustar 00000000000000Copyright (c) 2017 arc-swap developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pyo3-log-0.9.0/README.md000064400000000000000000000017671046102023000125750ustar 00000000000000# pyo3-log [![Actions Status](https://github.com/vorner/pyo3-log/workflows/test/badge.svg)](https://github.com/vorner/pyo3-log/actions) [![codecov](https://codecov.io/gh/vorner/pyo3-log/branch/main/graph/badge.svg?token=3KA3R2D9fV)](https://codecov.io/gh/vorner/pyo3-log) [![docs](https://docs.rs/pyo3-log/badge.svg)](https://docs.rs/pyo3-log) A bridge to send Rust's log messages over to Python. Meant to help logging from pyo3 native extensions. Read [the documentation](https://docs.rs/pyo3-log) before using. ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. pyo3-log-0.9.0/src/lib.rs000064400000000000000000000512411046102023000132110ustar 00000000000000#![forbid(unsafe_code)] #![doc( html_root_url = "https://docs.rs/pyo3-log/0.2.1/pyo3-log/", test(attr(deny(warnings))) )] #![warn(missing_docs)] //! A bridge from Rust to Python logging //! //! The library can be used to install a [logger][log::Log] into Rust that will send the messages //! over to the Python [logging](https://docs.python.org/3/library/logging.html). This can be //! useful when writing a native Python extension module in Rust and it is desirable to log from //! the Rust side too. //! //! The library internally depends on the [`pyo3`] crate. This is not exposed through the public //! API and it should work from extension modules not using [`pyo3`] directly. It'll nevertheless //! still bring the dependency in, so this might be considered if the module doesn't want to use //! it. //! //! # Simple usage //! //! Each extension module has its own global variables, therefore the used logger is also //! independent of other Rust native extensions. Therefore, it is up to each one to set a logger //! for itself if it wants one. //! //! By using [`init`] function from a place that's run only once (maybe from the top-level module //! of the extension), the logger is registered and the log messages (eg. [`info`][log::info]) send //! their messages over to the Python side. //! //! ```rust //! use log::info; //! use pyo3::prelude::*; //! //! #[pyfunction] //! fn log_something() { //! info!("Something!"); //! } //! //! #[pymodule] //! fn my_module(_py: Python<'_>, m: &PyModule) -> PyResult<()> { //! pyo3_log::init(); //! //! m.add_wrapped(wrap_pyfunction!(log_something))?; //! Ok(()) //! } //! ``` //! //! # Performance, Filtering and Caching //! //! Ideally, the logging system would always consult the Python loggers to know which messages //! should or should not be logged. However, one of the reasons of using Rust instead of Python is //! performance. Part of that is giving up the GIL in long-running computations to let other //! threads run at the same time. //! //! Therefore, acquiring the GIL and calling into the Python interpreter on each //! [`trace`][log::trace] message only to figure out it is not to be logged would be prohibitively //! slow. There are two techniques employed here. //! //! First, level filters are applied before consulting the Python side. By default, only the //! [`Debug`][Level::Debug] level and more severe is considered to be sent over to Python. This can //! be overridden using the [`filter`][Logger::filter] and [`filter_target`][Logger::filter_target] //! methods. //! //! Second, the Python loggers and their effective log levels are cached on the Rust side on the //! first use of the given module. This means that on a disabled level, only the first logging //! attempt in the given module will acquire GIL while the future ones will short-circuit before //! ever reaching Python. //! //! This is good for performance, but could lead to the incorrect messages to be logged or not //! logged in certain situations ‒ if Rust logs before the Python logging system is set up properly //! or when it is reconfigured at runtime. //! //! For these reasons it is possible to turn caching off on construction of the logger (at the cost //! of performance) and to clear the cache manually through the [`ResetHandle`]. //! //! To tune the caching and filtering, the logger needs to be created manually: //! //! ```rust //! # use log::LevelFilter; //! # use pyo3::prelude::*; //! # use pyo3_log::{Caching, Logger}; //! # //! # fn main() -> PyResult<()> { //! # Python::with_gil(|py| { //! let handle = Logger::new(py, Caching::LoggersAndLevels)? //! .filter(LevelFilter::Trace) //! .filter_target("my_module::verbose_submodule".to_owned(), LevelFilter::Warn) //! .install() //! .expect("Someone installed a logger before us :-("); //! //! // Some time in the future when logging changes, reset the caches: //! handle.reset(); //! # Ok(()) //! # }) //! # } //! ``` //! //! # Mapping //! //! The logging `target` is mapped into the name of the logger on the Python side, replacing all //! `::` occurrences with `.` (both form hierarchy in their respective language). //! //! Log levels are mapped to the same-named ones. The [`Trace`][Level::Trace] doesn't exist on the //! Python side, but is mapped to a level with value 5. //! //! # Interaction with Python GIL //! //! Under the hook, the logging routines call into Python. That means they need to acquire the //! Global Interpreter Lock of Python. //! //! This has several consequences. One of them is the above mentioned performance considerations. //! //! The other is a risk of deadlocks if threads are used from within the extension code without //! releasing the GIL. //! //! ```rust //! use std::thread; //! use log::info; //! use pyo3::prelude::*; //! //! #[pyfunction] //! fn deadlock() { //! info!("This logs fine"); //! //! let background_thread = thread::spawn(|| { //! info!("This'll deadlock"); //! }); //! //! background_thread.join().unwrap(); //! } //! # let _ = deadlock; //! ``` //! //! The above code will deadlock, because the `info` call in the background thread needs the GIL //! that's held by the deadlock function. One needs to give up the GIL to let the other threads //! run, something like this: //! //! ```rust //! use std::thread; //! use log::info; //! use pyo3::prelude::*; //! //! #[pyfunction] //! fn dont_deadlock(py: Python<'_>) { //! info!("This logs fine"); //! //! py.allow_threads(|| { //! let background_thread = thread::spawn(|| { //! info!("This'll not deadlock"); //! }); //! //! background_thread.join().unwrap(); //! }); //! } //! # let _ = dont_deadlock; //! ``` use std::cmp; use std::collections::HashMap; use std::sync::Arc; use arc_swap::ArcSwap; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use pyo3::prelude::*; use pyo3::types::PyTuple; /// A handle into a [`Logger`], able to reset its caches. /// /// This handle can be used to manipulate a [`Logger`] even after it has been installed. It's main /// purpose is to reset the internal caches, for example if the logging settings on the Python side /// changed. #[derive(Clone, Debug)] pub struct ResetHandle(Arc>); impl ResetHandle { /// Reset the internal logger caches. /// /// This removes all the cached loggers and levels (if there were any). Future logging calls /// may cache them again, using the current Python logging settings. pub fn reset(&self) { // Overwrite whatever is in the cache directly. This must win in case of any collisions // (the caching uses compare_and_swap to let the reset win). self.0.store(Default::default()); } } /// What the [`Logger`] can cache. #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[non_exhaustive] pub enum Caching { /// Disables caching. /// /// Every time a log message passes the filters, the code goes to the Python side to check if /// the message shall be logged. Nothing, /// Caches the Python `Logger` objects. /// /// The logger objects (which should stay the same during the lifetime of a Python application) /// are cached. However, the log levels are not. This means there's some amount of calling of /// Python code saved during a logging call, but the GIL still needs to be acquired even if the /// message doesn't eventually get output anywhere. Loggers, /// Caches both the Python `Logger` and their respective effective log levels. /// /// Therefore, once a `Logger` has been cached, it is possible to decide on the Rust side if a /// message would get logged or not. If the message is not to be logged, no Python code is /// called and the GIL doesn't have to be acquired. LoggersAndLevels, } impl Default for Caching { fn default() -> Self { Caching::LoggersAndLevels } } #[derive(Clone, Debug)] struct CacheEntry { filter: LevelFilter, logger: PyObject, } #[derive(Clone, Debug, Default)] struct CacheNode { local: Option, children: HashMap>, } impl CacheNode { fn store_to_cache_recursive<'a, P>(&self, mut path: P, entry: CacheEntry) -> Arc where P: Iterator, { let mut me = self.clone(); match path.next() { Some(segment) => { let child = me.children.entry(segment.to_owned()).or_default(); *child = child.store_to_cache_recursive(path, entry); } None => me.local = Some(entry), } Arc::new(me) } } /// The `Logger` /// /// The actual `Logger` that can be installed into the Rust side and will send messages over to /// Python. /// /// It can be either created directly and then installed, passed to other aggregating log systems, /// or the [`init`] or [`try_init`] functions may be used if defaults are good enough. #[derive(Clone, Debug)] pub struct Logger { /// Filter used as a fallback if none of the `filters` match. top_filter: LevelFilter, /// Mapping of filters to modules. /// /// The most specific one will be used, falling back to `top_filter` if none matches. Stored as /// full paths, with `::` separaters (eg. before converting them from Rust to Python). filters: HashMap, /// The imported Python `logging` module. logging: Py, /// Caching configuration. caching: Caching, /// The cache with loggers and level filters. /// /// The nodes form a tree ‒ each one potentially holding a cache entry (or not) and might have /// some children. /// /// When updating, the whole path from the root is cloned in a copy-on-write manner and the Arc /// here is switched. In case of collisions (eg. someone already replaced the root since /// starting the update), the update is just thrown away. cache: Arc>, } impl Logger { /// Creates a new logger. /// /// It defaults to having a filter for [`Debug`][LevelFilter::Debug]. pub fn new(py: Python<'_>, caching: Caching) -> PyResult { let logging = py.import("logging")?; Ok(Self { top_filter: LevelFilter::Debug, filters: HashMap::new(), logging: logging.into(), caching, cache: Default::default(), }) } /// Installs this logger as the global one. /// /// When installing, it also sets the corresponding [maximum level][log::set_max_level], /// constructed using the filters in this logger. pub fn install(self) -> Result { let handle = self.reset_handle(); let level = cmp::max( self.top_filter, self.filters .values() .copied() .max() .unwrap_or(LevelFilter::Off), ); log::set_boxed_logger(Box::new(self))?; log::set_max_level(level); Ok(handle) } /// Provides the reset handle of this logger. /// /// Note that installing the logger also returns a reset handle. This function is available if, /// for example, the logger will be passed to some other logging system that connects multiple /// loggers together. pub fn reset_handle(&self) -> ResetHandle { ResetHandle(Arc::clone(&self.cache)) } /// Configures the default logging filter. /// /// Log messages will be filtered according a filter. If one provided by a /// [`filter_target`][Logger::filter_target] matches, it takes preference. If none matches, /// this one is used. /// /// The default filter if none set is [`Debug`][LevelFilter::Debug]. pub fn filter(mut self, filter: LevelFilter) -> Self { self.top_filter = filter; self } /// Sets a filter for a specific target, overriding the default. /// /// This'll match targets with the same name and all the children in the module hierarchy. In /// case multiple match, the most specific one wins. /// /// With this configuration, modules will log in the following levels: /// /// ```rust /// # use log::LevelFilter; /// # use pyo3_log::Logger; /// /// Logger::default() /// .filter(LevelFilter::Warn) /// .filter_target("xy".to_owned(), LevelFilter::Debug) /// .filter_target("xy::aa".to_owned(), LevelFilter::Trace); /// ``` /// /// * `whatever` => `Warn` /// * `xy` => `Debug` /// * `xy::aa` => `Trace` /// * `xy::aabb` => `Debug` pub fn filter_target(mut self, target: String, filter: LevelFilter) -> Self { self.filters.insert(target, filter); self } /// Finds a node in the cache. /// /// The hierarchy separator is `::`. fn lookup(&self, target: &str) -> Option> { if self.caching == Caching::Nothing { return None; } let root = self.cache.load(); let mut node: &Arc = &root; for segment in target.split("::") { match node.children.get(segment) { Some(sub) => node = sub, None => return None, } } Some(Arc::clone(node)) } /// Logs stuff /// /// Returns a logger to be cached, if any. If it already found a cached logger or if caching is /// turned off, returns None. fn log_inner( &self, py: Python<'_>, record: &Record, cache: &Option>, ) -> PyResult> { let msg = format!("{}", record.args()); let log_level = map_level(record.level()); let target = record.target().replace("::", "."); let cached_logger = cache .as_ref() .and_then(|node| node.local.as_ref()) .map(|local| &local.logger); let (logger, cached) = match cached_logger { Some(cached) => (cached.as_ref(py), true), None => ( self.logging .as_ref(py) .getattr("getLogger")? .call1((&target,))?, false, ), }; // We need to check for this ourselves. For some reason, the logger.handle does not check // it. And besides, we can save ourselves few python calls if it's turned off. if is_enabled_for(logger, record.level())? { let none = py.None(); // TODO: kv pairs, if enabled as a feature? let record = logger.call_method1( "makeRecord", ( target, log_level, record.file(), record.line().unwrap_or_default(), msg, PyTuple::empty(py), // args &none, // exc_info ), )?; logger.call_method1("handle", (record,))?; } let cache_logger = if !cached && self.caching != Caching::Nothing { Some(logger.into()) } else { None }; Ok(cache_logger) } fn filter_for(&self, target: &str) -> LevelFilter { let mut start = 0; let mut filter = self.top_filter; while let Some(end) = target[start..].find("::") { if let Some(f) = self.filters.get(&target[..start + end]) { filter = *f; } start += end + 2; } if let Some(f) = self.filters.get(target) { filter = *f; } filter } fn enabled_inner(&self, metadata: &Metadata, cache: &Option>) -> bool { let cache_filter = cache .as_ref() .and_then(|node| node.local.as_ref()) .map(|local| local.filter) .unwrap_or_else(LevelFilter::max); metadata.level() <= cache_filter && metadata.level() <= self.filter_for(metadata.target()) } fn store_to_cache(&self, target: &str, entry: CacheEntry) { let path = target.split("::"); let orig = self.cache.load(); // Construct a new cache structure and insert the new root. let new = orig.store_to_cache_recursive(path, entry); // Note: In case of collision, the cache update is lost. This is fine, as we simply lose a // tiny bit of performance and will cache the thing next time. // // We err on the side of losing it here (instead of overwriting), because if the cache is // reset, we don't want to re-insert the old value we have. self.cache.compare_and_swap(orig, new); } } impl Default for Logger { fn default() -> Self { Python::with_gil(|py| { Self::new(py, Caching::LoggersAndLevels).expect("Failed to initialize python logging") }) } } impl Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool { let cache = self.lookup(metadata.target()); self.enabled_inner(metadata, &cache) } fn log(&self, record: &Record) { let cache = self.lookup(record.target()); let mut store_to_cache = None; if self.enabled_inner(record.metadata(), &cache) { Python::with_gil(|py| match self.log_inner(py, record, &cache) { Ok(Some(logger)) => { let filter = match self.caching { Caching::Nothing => unreachable!(), Caching::Loggers => LevelFilter::max(), Caching::LoggersAndLevels => { extract_max_level(py, &logger).unwrap_or_else(|e| { e.print(py); LevelFilter::max() }) } }; store_to_cache = Some((logger, filter)); } Ok(None) => (), Err(e) => e.print(py), }) } // Note: no more GIL here. Not needed for storing to cache. if let Some((logger, filter)) = store_to_cache { let entry = CacheEntry { filter, logger }; self.store_to_cache(record.target(), entry); } } fn flush(&self) {} } fn map_level(level: Level) -> usize { match level { Level::Error => 40, Level::Warn => 30, Level::Info => 20, Level::Debug => 10, Level::Trace => 5, } } fn is_enabled_for(logger: &PyAny, level: Level) -> PyResult { let level = map_level(level); logger.call_method1("isEnabledFor", (level,))?.is_true() } fn extract_max_level(py: Python<'_>, logger: &PyObject) -> PyResult { use Level::*; let logger = logger.as_ref(py); for l in &[Trace, Debug, Info, Warn, Error] { if is_enabled_for(logger, *l)? { return Ok(l.to_level_filter()); } } Ok(LevelFilter::Off) } /// Installs a default instance of the logger. /// /// In case a logger is already installed, an error is returned. On success, a handle to reset the /// internal caches is returned. /// /// The default logger has a filter set to [`Debug`][LevelFilter::Debug] and caching enabled to /// [`LoggersAndLevels`][Caching::LoggersAndLevels]. pub fn try_init() -> Result { Logger::default().install() } /// Similar to [`try_init`], but panics if there's a previous logger already installed. pub fn init() -> ResetHandle { try_init().unwrap() } #[cfg(test)] mod tests { use super::*; #[test] fn default_filter() { let logger = Logger::default(); assert_eq!(logger.filter_for("hello_world"), LevelFilter::Debug); assert_eq!(logger.filter_for("hello_world::sub"), LevelFilter::Debug); } #[test] fn set_filter() { let logger = Logger::default().filter(LevelFilter::Info); assert_eq!(logger.filter_for("hello_world"), LevelFilter::Info); assert_eq!(logger.filter_for("hello_world::sub"), LevelFilter::Info); } #[test] fn filter_specific() { let logger = Logger::default() .filter(LevelFilter::Warn) .filter_target("hello_world".to_owned(), LevelFilter::Debug) .filter_target("hello_world::sub".to_owned(), LevelFilter::Trace); assert_eq!(logger.filter_for("hello_world"), LevelFilter::Debug); assert_eq!(logger.filter_for("hello_world::sub"), LevelFilter::Trace); assert_eq!( logger.filter_for("hello_world::sub::multi::level"), LevelFilter::Trace ); assert_eq!( logger.filter_for("hello_world::another"), LevelFilter::Debug ); assert_eq!( logger.filter_for("hello_world::another::level"), LevelFilter::Debug ); assert_eq!(logger.filter_for("other"), LevelFilter::Warn); } }