log-0.4.11/.cargo_vcs_info.json0000644000000001121370372515000117330ustar { "git": { "sha1": "aa4c0375cd94ed4d1b5de7ce0bb3369262dae7e2" } } log-0.4.11/.github/workflows/main.yml000064400000000000000000000047521370372502000155570ustar 00000000000000name: CI on: [push, pull_request] jobs: test: name: Test runs-on: ${{ matrix.os }} strategy: matrix: build: [stable, beta, nightly, macos, win32, win64, mingw] include: - build: stable os: ubuntu-latest rust: stable - build: beta os: ubuntu-latest rust: beta - build: nightly os: ubuntu-latest rust: nightly - build: macos os: macos-latest rust: stable - build: win32 os: windows-latest rust: stable-i686 - build: win64 os: windows-latest rust: stable-x86_64 - build: mingw os: windows-latest rust: stable-x86_64-gnu steps: - uses: actions/checkout@master - name: Install Rust (rustup) run: | rustup update ${{ matrix.rust }} --no-self-update rustup default ${{ matrix.rust }} - run: cargo test --verbose - run: cargo test --verbose --features serde - run: cargo test --verbose --features std - run: cargo test --verbose --features kv_unstable - run: cargo test --verbose --features "kv_unstable std" - run: cargo test --verbose --features "kv_unstable_sval" - run: cargo run --verbose --manifest-path test_max_level_features/Cargo.toml - run: cargo run --verbose --manifest-path test_max_level_features/Cargo.toml --release rustfmt: name: Rustfmt runs-on: ubuntu-latest steps: - uses: actions/checkout@master - name: Install Rust run: | rustup update stable --no-self-update rustup default stable rustup component add rustfmt - run: cargo fmt -- --check msrv: name: MSRV runs-on: ubuntu-latest steps: - uses: actions/checkout@master - name: Install Rust run: | rustup update 1.31.0 --no-self-update rustup default 1.31.0 - run: cargo build --verbose - run: cargo build --verbose --features serde - run: cargo build --verbose --features std embedded: name: Embedded runs-on: ubuntu-latest steps: - uses: actions/checkout@master - name: Install Rust run: | rustup update stable --no-self-update rustup default stable - run: rustup target add thumbv6m-none-eabi - run: cargo build --verbose --target=thumbv6m-none-eabi log-0.4.11/.gitignore000064400000000000000000000000251346047754400125070ustar 00000000000000target/ Cargo.lock log-0.4.11/CHANGELOG.md000064400000000000000000000165171370372502000123260ustar 00000000000000# Change Log ## [Unreleased] ## [0.4.11] - 2020-07-09 ### New * Support coercing structured values into concrete types. * Reference the `win_dbg_logger` in the readme. ### Fixed * Updates a few deprecated items used internally. * Fixed issues in docs and expands sections. * Show the correct build badge in the readme. * Fix up a possible inference breakage with structured value errors. * Respect formatting flags in structured value formatting. ## [0.4.10] - 2019-12-16 (yanked) ### Fixed * Fixed the `log!` macros so they work in expression context (this regressed in `0.4.9`, which has been yanked). ## [0.4.9] - 2019-12-12 (yanked) ### Minimum Supported Rust Version This release bumps the minimum compiler version to `1.31.0`. This was mainly needed for `cfg-if`, but between `1.16.0` and `1.31.0` there are a lot of language and library improvements we now take advantage of. ### New * Unstable support for capturing key-value pairs in a record using the `log!` macros ### Improved * Better documentation for max level filters. * Internal updates to line up with bumped MSRV ## [0.4.8] - 2019-07-28 ### New * Support attempting to get `Record` fields as static strings. ## [0.4.7] - 2019-07-06 ### New * Support for embedded environments with thread-unsafe initialization. * Initial unstable support for capturing structured data under the `kv_unstable` feature gate. This new API doesn't affect existing users and may change in future patches (so those changes may not appear in the changelog until it stabilizes). ### Improved * Docs for using `log` with the 2018 edition. * Error messages for macros missing arguments. ## [0.4.6] - 2018-10-27 ### Improved * Support 2018-style macro import for the `log_enabled!` macro. ## [0.4.5] - 2018-09-03 ### Improved * Make `log`'s internal helper macros less likely to conflict with user-defined macros. ## [0.4.4] - 2018-08-17 ### Improved * Support 2018-style imports of the log macros. ## [0.4.3] - 2018-06-29 ### Improved * More code generation improvements. ## [0.4.2] - 2018-06-05 ### Improved * Log invocations now generate less code. ### Fixed * Example Logger implementations now properly set the max log level. ## [0.4.1] - 2017-12-30 ### Fixed * Some doc links were fixed. ## [0.4.0] - 2017-12-24 The changes in this release include cleanup of some obscure functionality and a more robust public API designed to support bridges to other logging systems, and provide more flexibility to new features in the future. ### Compatibility Vast portions of the Rust ecosystem use the 0.3.x release series of log, and we don't want to force the community to go through the pain of upgrading every crate to 0.4.x at the exact same time. Along with 0.4.0, we've published a new 0.3.9 release which acts as a "shim" over 0.4.0. This will allow crates using either version to coexist without losing messages from one side or the other. There is one caveat - a log message generated by a crate using 0.4.x but consumed by a logging implementation using 0.3.x will not have a file name or module path. Applications affected by this can upgrade their logging implementations to one using 0.4.x to avoid losing this information. The other direction does not lose any information, fortunately! **TL;DR** Libraries should feel comfortable upgrading to 0.4.0 without treating that as a breaking change. Applications may need to update their logging implementation (e.g. env-logger) to a newer version using log 0.4.x to avoid losing module and file information. ### New * The crate is now `no_std` by default. * `Level` and `LevelFilter` now implement `Serialize` and `Deserialize` when the `serde` feature is enabled. * The `Record` and `Metadata` types can now be constructed by third-party code via a builder API. * The `logger` free function returns a reference to the logger implementation. This, along with the ability to construct `Record`s, makes it possible to bridge from another logging framework to this one without digging into the private internals of the crate. The standard `error!` `warn!`, etc, macros now exclusively use the public API of the crate rather than "secret" internal APIs. * `Log::flush` has been added to allow crates to tell the logging implementation to ensure that all "in flight" log events have been persisted. This can be used, for example, just before an application exits to ensure that asynchronous log sinks finish their work. ### Removed * The `shutdown` and `shutdown_raw` functions have been removed. Supporting shutdown significantly complicated the implementation and imposed a performance cost on each logging operation. * The `log_panics` function and its associated `nightly` Cargo feature have been removed. Use the [log-panics](https://crates.io/crates/log-panics) instead. ### Changed * The `Log` prefix has been removed from type names. For example, `LogLevelFilter` is now `LevelFilter`, and `LogRecord` is now `Record`. * The `MaxLogLevelFilter` object has been removed in favor of a `set_max_level` free function. * The `set_logger` free functions have been restructured. The logger is now directly passed to the functions rather than a closure which returns the logger. `set_logger` now takes a `&'static Log` and is usable in `no_std` contexts in place of the old `set_logger_raw`. `set_boxed_logger` is a convenience function which takes a `Box` but otherwise acts like `set_logger`. It requires the `std` feature. * The `file` and `module_path` values in `Record` no longer have the `'static` lifetime to support integration with other logging frameworks that don't provide a `'static` lifetime for the equivalent values. * The `file`, `line`, and `module_path` values in `Record` are now `Option`s to support integration with other logging frameworks that don't provide those values. ### In the Future * We're looking to add support for *structured* logging - the inclusion of extra key-value pairs of information in a log event in addition to the normal string message. This should be able to be added in a backwards compatible manner to the 0.4.x series when the design is worked out. ## Older Look at the [release tags] for information about older releases. [Unreleased]: https://github.com/rust-lang-nursery/log/compare/0.4.11...HEAD [0.4.11]: https://github.com/rust-lang-nursery/log/compare/0.4.10...0.4.11 [0.4.10]: https://github.com/rust-lang-nursery/log/compare/0.4.9...0.4.10 [0.4.9]: https://github.com/rust-lang-nursery/log/compare/0.4.8...0.4.9 [0.4.8]: https://github.com/rust-lang-nursery/log/compare/0.4.7...0.4.8 [0.4.7]: https://github.com/rust-lang-nursery/log/compare/0.4.6...0.4.7 [0.4.6]: https://github.com/rust-lang-nursery/log/compare/0.4.5...0.4.6 [0.4.5]: https://github.com/rust-lang-nursery/log/compare/0.4.4...0.4.5 [0.4.4]: https://github.com/rust-lang-nursery/log/compare/0.4.3...0.4.4 [0.4.3]: https://github.com/rust-lang-nursery/log/compare/0.4.2...0.4.3 [0.4.2]: https://github.com/rust-lang-nursery/log/compare/0.4.1...0.4.2 [0.4.1]: https://github.com/rust-lang-nursery/log/compare/0.4.0...0.4.1 [0.4.0]: https://github.com/rust-lang-nursery/log/compare/0.3.8...0.4.0 [release tags]: https://github.com/rust-lang-nursery/log/releases log-0.4.11/Cargo.toml0000644000000033771370372515000077510ustar # 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "log" version = "0.4.11" authors = ["The Rust Project Developers"] build = "build.rs" exclude = ["rfcs/**/*", "/.travis.yml", "/appveyor.yml"] description = "A lightweight logging facade for Rust\n" documentation = "https://docs.rs/log" readme = "README.md" keywords = ["logging"] categories = ["development-tools::debugging"] license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/log" [package.metadata.docs.rs] features = ["std", "serde", "kv_unstable_sval"] [[test]] name = "filters" harness = false [[test]] name = "macros" harness = true [dependencies.cfg-if] version = "0.1.2" [dependencies.serde] version = "1.0" optional = true default-features = false [dependencies.sval] version = "0.5.2" optional = true default-features = false [dev-dependencies.serde_test] version = "1.0" [dev-dependencies.sval] version = "0.5.2" features = ["test"] [features] kv_unstable = [] kv_unstable_sval = ["kv_unstable", "sval/fmt"] max_level_debug = [] max_level_error = [] max_level_info = [] max_level_off = [] max_level_trace = [] max_level_warn = [] release_max_level_debug = [] release_max_level_error = [] release_max_level_info = [] release_max_level_off = [] release_max_level_trace = [] release_max_level_warn = [] std = [] log-0.4.11/Cargo.toml.orig000064400000000000000000000026071370372502000133770ustar 00000000000000[package] name = "log" version = "0.4.11" # remember to update html_root_url authors = ["The Rust Project Developers"] license = "MIT OR Apache-2.0" readme = "README.md" repository = "https://github.com/rust-lang/log" documentation = "https://docs.rs/log" description = """ A lightweight logging facade for Rust """ categories = ["development-tools::debugging"] keywords = ["logging"] exclude = ["rfcs/**/*", "/.travis.yml", "/appveyor.yml"] build = "build.rs" [package.metadata.docs.rs] features = ["std", "serde", "kv_unstable_sval"] [[test]] name = "filters" harness = false [[test]] name = "macros" harness = true [features] max_level_off = [] max_level_error = [] max_level_warn = [] max_level_info = [] max_level_debug = [] max_level_trace = [] release_max_level_off = [] release_max_level_error = [] release_max_level_warn = [] release_max_level_info = [] release_max_level_debug = [] release_max_level_trace = [] std = [] # requires the latest stable # this will have a tighter MSRV before stabilization kv_unstable = [] kv_unstable_sval = ["kv_unstable", "sval/fmt"] [dependencies] cfg-if = "0.1.2" serde = { version = "1.0", optional = true, default-features = false } sval = { version = "0.5.2", optional = true, default-features = false } [dev-dependencies] serde_test = "1.0" sval = { version = "0.5.2", features = ["test"] } log-0.4.11/LICENSE-APACHE000064400000000000000000000254501346047754400124540ustar 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. log-0.4.11/LICENSE-MIT000064400000000000000000000021101346047754400121500ustar 00000000000000Copyright (c) 2014 The Rust Project 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. log-0.4.11/README.md000064400000000000000000000063661370145502000117730ustar 00000000000000log === A Rust library providing a lightweight logging *facade*. [![Build status](https://img.shields.io/github/workflow/status/rust-lang/log/CI/master)](https://github.com/rust-lang/log/actions) [![Latest version](https://img.shields.io/crates/v/log.svg)](https://crates.io/crates/log) [![Documentation](https://docs.rs/log/badge.svg)](https://docs.rs/log) ![License](https://img.shields.io/crates/l/log.svg) * [`log` documentation](https://docs.rs/log) A logging facade provides a single logging API that abstracts over the actual logging implementation. Libraries can use the logging API provided by this crate, and the consumer of those libraries can choose the logging implementation that is most suitable for its use case. ## Minimum supported `rustc` `1.31.0+` This version is explicitly tested in CI and may be bumped in any release as needed. Maintaining compatibility with older compilers is a priority though, so the bar for bumping the minimum supported version is set very high. Any changes to the supported minimum version will be called out in the release notes. ## Usage ## In libraries Libraries should link only to the `log` crate, and use the provided macros to log whatever information will be useful to downstream consumers: ```toml [dependencies] log = "0.4" ``` ```rust use log::{info, trace, warn}; pub fn shave_the_yak(yak: &mut Yak) { trace!("Commencing yak shaving"); loop { match find_a_razor() { Ok(razor) => { info!("Razor located: {}", razor); yak.shave(razor); break; } Err(err) => { warn!("Unable to locate a razor: {}, retrying", err); } } } } ``` ## In executables In order to produce log output, executables have to use a logger implementation compatible with the facade. There are many available implementations to choose from, here are some of the most popular ones: * Simple minimal loggers: * [`env_logger`](https://docs.rs/env_logger/*/env_logger/) * [`simple_logger`](https://github.com/borntyping/rust-simple_logger) * [`simplelog`](https://github.com/drakulix/simplelog.rs) * [`pretty_env_logger`](https://docs.rs/pretty_env_logger/*/pretty_env_logger/) * [`stderrlog`](https://docs.rs/stderrlog/*/stderrlog/) * [`flexi_logger`](https://docs.rs/flexi_logger/*/flexi_logger/) * Complex configurable frameworks: * [`log4rs`](https://docs.rs/log4rs/*/log4rs/) * [`fern`](https://docs.rs/fern/*/fern/) * Adaptors for other facilities: * [`syslog`](https://docs.rs/syslog/*/syslog/) * [`slog-stdlog`](https://docs.rs/slog-stdlog/*/slog_stdlog/) * [`android_log`](https://docs.rs/android_log/*/android_log/) * [`win_dbg_logger`](https://docs.rs/win_dbg_logger/*/win_dbg_logger/) * For WebAssembly binaries: * [`console_log`](https://docs.rs/console_log/*/console_log/) Executables should choose a logger implementation and initialize it early in the runtime of the program. Logger implementations will typically include a function to do this. Any log messages generated before the logger is initialized will be ignored. The executable itself may use the `log` crate to log as well. log-0.4.11/build.rs000064400000000000000000000005451370145501200121530ustar 00000000000000//! This build script detects target platforms that lack proper support for //! atomics and sets `cfg` flags accordingly. use std::env; fn main() { let target = env::var("TARGET").unwrap(); if !target.starts_with("thumbv6") { println!("cargo:rustc-cfg=atomic_cas"); } println!("cargo:rerun-if-changed=build.rs"); } log-0.4.11/src/kv/error.rs000064400000000000000000000027721370145502000134170ustar 00000000000000use std::fmt; /// An error encountered while working with structured data. #[derive(Debug)] pub struct Error { inner: Inner, } #[derive(Debug)] enum Inner { #[cfg(feature = "std")] Boxed(std_support::BoxedError), Msg(&'static str), Fmt, } impl Error { /// Create an error from a message. pub fn msg(msg: &'static str) -> Self { Error { inner: Inner::Msg(msg), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Inner::*; match &self.inner { #[cfg(feature = "std")] &Boxed(ref err) => err.fmt(f), &Msg(ref msg) => msg.fmt(f), &Fmt => fmt::Error.fmt(f), } } } impl From for Error { fn from(_: fmt::Error) -> Self { Error { inner: Inner::Fmt } } } #[cfg(feature = "std")] mod std_support { use super::*; use std::{error, io}; pub(super) type BoxedError = Box; impl Error { /// Create an error from a standard error type. pub fn boxed(err: E) -> Self where E: Into, { Error { inner: Inner::Boxed(err.into()), } } } impl error::Error for Error {} impl From for Error { fn from(err: io::Error) -> Self { Error::boxed(err) } } } log-0.4.11/src/kv/key.rs000064400000000000000000000052051356152575200130660ustar 00000000000000//! Structured keys. use std::borrow::Borrow; use std::cmp; use std::fmt; use std::hash; /// A type that can be converted into a [`Key`](struct.Key.html). pub trait ToKey { /// Perform the conversion. fn to_key(&self) -> Key; } impl<'a, T> ToKey for &'a T where T: ToKey + ?Sized, { fn to_key(&self) -> Key { (**self).to_key() } } impl<'k> ToKey for Key<'k> { fn to_key(&self) -> Key { Key { key: self.key } } } impl ToKey for str { fn to_key(&self) -> Key { Key::from_str(self) } } /// A key in a structured key-value pair. #[derive(Clone)] pub struct Key<'k> { key: &'k str, } impl<'k> Key<'k> { /// Get a key from a borrowed string. pub fn from_str(key: &'k str) -> Self { Key { key: key } } /// Get a borrowed string from this key. pub fn as_str(&self) -> &str { self.key } } impl<'k> fmt::Debug for Key<'k> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.key.fmt(f) } } impl<'k> fmt::Display for Key<'k> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.key.fmt(f) } } impl<'k> hash::Hash for Key<'k> { fn hash(&self, state: &mut H) where H: hash::Hasher, { self.as_str().hash(state) } } impl<'k, 'ko> PartialEq> for Key<'k> { fn eq(&self, other: &Key<'ko>) -> bool { self.as_str().eq(other.as_str()) } } impl<'k> Eq for Key<'k> {} impl<'k, 'ko> PartialOrd> for Key<'k> { fn partial_cmp(&self, other: &Key<'ko>) -> Option { self.as_str().partial_cmp(other.as_str()) } } impl<'k> Ord for Key<'k> { fn cmp(&self, other: &Self) -> cmp::Ordering { self.as_str().cmp(other.as_str()) } } impl<'k> AsRef for Key<'k> { fn as_ref(&self) -> &str { self.as_str() } } impl<'k> Borrow for Key<'k> { fn borrow(&self) -> &str { self.as_str() } } impl<'k> From<&'k str> for Key<'k> { fn from(s: &'k str) -> Self { Key::from_str(s) } } #[cfg(feature = "std")] mod std_support { use super::*; use std::borrow::Cow; impl ToKey for String { fn to_key(&self) -> Key { Key::from_str(self) } } impl<'a> ToKey for Cow<'a, str> { fn to_key(&self) -> Key { Key::from_str(self) } } } #[cfg(test)] mod tests { use super::*; #[test] fn key_from_string() { assert_eq!("a key", Key::from_str("a key").as_str()); } } log-0.4.11/src/kv/mod.rs000064400000000000000000000011611356152575200130520ustar 00000000000000//! **UNSTABLE:** Structured key-value pairs. //! //! This module is unstable and breaking changes may be made //! at any time. See [the tracking issue](https://github.com/rust-lang-nursery/log/issues/328) //! for more details. //! //! Add the `kv_unstable` feature to your `Cargo.toml` to enable //! this module: //! //! ```toml //! [dependencies.log] //! features = ["kv_unstable"] //! ``` mod error; mod key; mod source; pub mod value; pub use self::error::Error; pub use self::key::{Key, ToKey}; pub use self::source::{Source, Visitor}; #[doc(inline)] pub use self::value::{ToValue, Value}; log-0.4.11/src/kv/source.rs000064400000000000000000000253111361466760600136020ustar 00000000000000//! Sources for key-value pairs. use kv::{Error, Key, ToKey, ToValue, Value}; use std::fmt; /// A source of key-value pairs. /// /// The source may be a single pair, a set of pairs, or a filter over a set of pairs. /// Use the [`Visitor`](trait.Visitor.html) trait to inspect the structured data /// in a source. pub trait Source { /// Visit key-value pairs. /// /// A source doesn't have to guarantee any ordering or uniqueness of key-value pairs. /// If the given visitor returns an error then the source may early-return with it, /// even if there are more key-value pairs. /// /// # Implementation notes /// /// A source should yield the same key-value pairs to a subsequent visitor unless /// that visitor itself fails. fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error>; /// Get the value for a given key. /// /// If the key appears multiple times in the source then which key is returned /// is implementation specific. /// /// # Implementation notes /// /// A source that can provide a more efficient implementation of this method /// should override it. fn get<'v>(&'v self, key: Key) -> Option> { struct Get<'k, 'v> { key: Key<'k>, found: Option>, } impl<'k, 'kvs> Visitor<'kvs> for Get<'k, 'kvs> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { if self.key == key { self.found = Some(value); } Ok(()) } } let mut get = Get { key, found: None }; let _ = self.visit(&mut get); get.found } /// Count the number of key-value pairs that can be visited. /// /// # Implementation notes /// /// A source that knows the number of key-value pairs upfront may provide a more /// efficient implementation. /// /// A subsequent call to `visit` should yield the same number of key-value pairs /// to the visitor, unless that visitor fails part way through. fn count(&self) -> usize { struct Count(usize); impl<'kvs> Visitor<'kvs> for Count { fn visit_pair(&mut self, _: Key<'kvs>, _: Value<'kvs>) -> Result<(), Error> { self.0 += 1; Ok(()) } } let mut count = Count(0); let _ = self.visit(&mut count); count.0 } } impl<'a, T> Source for &'a T where T: Source + ?Sized, { fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { Source::visit(&**self, visitor) } fn get<'v>(&'v self, key: Key) -> Option> { Source::get(&**self, key) } fn count(&self) -> usize { Source::count(&**self) } } impl Source for (K, V) where K: ToKey, V: ToValue, { fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { visitor.visit_pair(self.0.to_key(), self.1.to_value()) } fn get<'v>(&'v self, key: Key) -> Option> { if self.0.to_key() == key { Some(self.1.to_value()) } else { None } } fn count(&self) -> usize { 1 } } impl Source for [S] where S: Source, { fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { for source in self { source.visit(visitor)?; } Ok(()) } fn count(&self) -> usize { self.len() } } impl Source for Option where S: Source, { fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { if let Some(ref source) = *self { source.visit(visitor)?; } Ok(()) } fn count(&self) -> usize { self.as_ref().map(Source::count).unwrap_or(0) } } /// A visitor for the key-value pairs in a [`Source`](trait.Source.html). pub trait Visitor<'kvs> { /// Visit a key-value pair. fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error>; } impl<'a, 'kvs, T> Visitor<'kvs> for &'a mut T where T: Visitor<'kvs> + ?Sized, { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { (**self).visit_pair(key, value) } } impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugMap<'a, 'b> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { self.entry(&key, &value); Ok(()) } } impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugList<'a, 'b> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { self.entry(&(key, value)); Ok(()) } } impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugSet<'a, 'b> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { self.entry(&(key, value)); Ok(()) } } impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugTuple<'a, 'b> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { self.field(&key); self.field(&value); Ok(()) } } #[cfg(feature = "std")] mod std_support { use super::*; use std::borrow::Borrow; use std::collections::{BTreeMap, HashMap}; use std::hash::{BuildHasher, Hash}; impl Source for Box where S: Source + ?Sized, { fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { Source::visit(&**self, visitor) } fn get<'v>(&'v self, key: Key) -> Option> { Source::get(&**self, key) } fn count(&self) -> usize { Source::count(&**self) } } impl Source for Vec where S: Source, { fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { Source::visit(&**self, visitor) } fn get<'v>(&'v self, key: Key) -> Option> { Source::get(&**self, key) } fn count(&self) -> usize { Source::count(&**self) } } impl<'kvs, V> Visitor<'kvs> for Box where V: Visitor<'kvs> + ?Sized, { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { (**self).visit_pair(key, value) } } impl Source for HashMap where K: ToKey + Borrow + Eq + Hash, V: ToValue, S: BuildHasher, { fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { for (key, value) in self { visitor.visit_pair(key.to_key(), value.to_value())?; } Ok(()) } fn get<'v>(&'v self, key: Key) -> Option> { HashMap::get(self, key.as_str()).map(|v| v.to_value()) } fn count(&self) -> usize { self.len() } } impl Source for BTreeMap where K: ToKey + Borrow + Ord, V: ToValue, { fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { for (key, value) in self { visitor.visit_pair(key.to_key(), value.to_value())?; } Ok(()) } fn get<'v>(&'v self, key: Key) -> Option> { BTreeMap::get(self, key.as_str()).map(|v| v.to_value()) } fn count(&self) -> usize { self.len() } } #[cfg(test)] mod tests { use super::*; use kv::value::test::Token; use std::collections::{BTreeMap, HashMap}; #[test] fn count() { assert_eq!(1, Source::count(&Box::new(("a", 1)))); assert_eq!(2, Source::count(&vec![("a", 1), ("b", 2)])); } #[test] fn get() { let source = vec![("a", 1), ("b", 2), ("a", 1)]; assert_eq!( Token::I64(1), Source::get(&source, Key::from_str("a")).unwrap().to_token() ); let source = Box::new(Option::None::<(&str, i32)>); assert!(Source::get(&source, Key::from_str("a")).is_none()); } #[test] fn hash_map() { let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); assert_eq!(2, Source::count(&map)); assert_eq!( Token::I64(1), Source::get(&map, Key::from_str("a")).unwrap().to_token() ); } #[test] fn btree_map() { let mut map = BTreeMap::new(); map.insert("a", 1); map.insert("b", 2); assert_eq!(2, Source::count(&map)); assert_eq!( Token::I64(1), Source::get(&map, Key::from_str("a")).unwrap().to_token() ); } } } #[cfg(test)] mod tests { use super::*; use kv::value::test::Token; #[test] fn source_is_object_safe() { fn _check(_: &dyn Source) {} } #[test] fn visitor_is_object_safe() { fn _check(_: &dyn Visitor) {} } #[test] fn count() { struct OnePair { key: &'static str, value: i32, } impl Source for OnePair { fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { visitor.visit_pair(self.key.to_key(), self.value.to_value()) } } assert_eq!(1, Source::count(&("a", 1))); assert_eq!(2, Source::count(&[("a", 1), ("b", 2)] as &[_])); assert_eq!(0, Source::count(&Option::None::<(&str, i32)>)); assert_eq!(1, Source::count(&OnePair { key: "a", value: 1 })); } #[test] fn get() { let source = &[("a", 1), ("b", 2), ("a", 1)] as &[_]; assert_eq!( Token::I64(1), Source::get(source, Key::from_str("a")).unwrap().to_token() ); assert_eq!( Token::I64(2), Source::get(source, Key::from_str("b")).unwrap().to_token() ); assert!(Source::get(&source, Key::from_str("c")).is_none()); let source = Option::None::<(&str, i32)>; assert!(Source::get(&source, Key::from_str("a")).is_none()); } } log-0.4.11/src/kv/value/fill.rs000064400000000000000000000077551370145502000143360ustar 00000000000000//! Lazy value initialization. use std::fmt; use super::internal::{Erased, Inner, Visitor}; use super::{Error, Value}; impl<'v> Value<'v> { /// Get a value from a fillable slot. pub fn from_fill(value: &'v T) -> Self where T: Fill + 'static, { Value { inner: Inner::Fill(unsafe { Erased::new_unchecked::(value) }), } } } /// A type that requires extra work to convert into a [`Value`](struct.Value.html). /// /// This trait is a more advanced initialization API than [`ToValue`](trait.ToValue.html). /// It's intended for erased values coming from other logging frameworks that may need /// to perform extra work to determine the concrete type to use. pub trait Fill { /// Fill a value. fn fill(&self, slot: &mut Slot) -> Result<(), Error>; } impl<'a, T> Fill for &'a T where T: Fill + ?Sized, { fn fill(&self, slot: &mut Slot) -> Result<(), Error> { (**self).fill(slot) } } /// A value slot to fill using the [`Fill`](trait.Fill.html) trait. pub struct Slot<'s, 'f> { filled: bool, visitor: &'s mut dyn Visitor<'f>, } impl<'s, 'f> fmt::Debug for Slot<'s, 'f> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Slot").finish() } } impl<'s, 'f> Slot<'s, 'f> { pub(super) fn new(visitor: &'s mut dyn Visitor<'f>) -> Self { Slot { visitor, filled: false, } } pub(super) fn fill(&mut self, f: F) -> Result<(), Error> where F: FnOnce(&mut dyn Visitor<'f>) -> Result<(), Error>, { assert!(!self.filled, "the slot has already been filled"); self.filled = true; f(self.visitor) } /// Fill the slot with a value. /// /// The given value doesn't need to satisfy any particular lifetime constraints. /// /// # Panics /// /// Calling more than a single `fill` method on this slot will panic. pub fn fill_any(&mut self, value: T) -> Result<(), Error> where T: Into>, { self.fill(|visitor| value.into().inner.visit(visitor)) } } #[cfg(test)] mod tests { use super::*; #[test] fn fill_value_borrowed() { struct TestFill; impl Fill for TestFill { fn fill(&self, slot: &mut Slot) -> Result<(), Error> { let dbg: &dyn fmt::Debug = &1; slot.fill_debug(&dbg) } } assert_eq!("1", Value::from_fill(&TestFill).to_string()); } #[test] fn fill_value_owned() { struct TestFill; impl Fill for TestFill { fn fill(&self, slot: &mut Slot) -> Result<(), Error> { slot.fill_any("a string") } } } #[test] #[should_panic] fn fill_multiple_times_panics() { struct BadFill; impl Fill for BadFill { fn fill(&self, slot: &mut Slot) -> Result<(), Error> { slot.fill_any(42)?; slot.fill_any(6789)?; Ok(()) } } let _ = Value::from_fill(&BadFill).to_string(); } #[test] fn fill_cast() { struct TestFill; impl Fill for TestFill { fn fill(&self, slot: &mut Slot) -> Result<(), Error> { slot.fill_any("a string") } } assert_eq!( "a string", Value::from_fill(&TestFill) .to_borrowed_str() .expect("invalid value") ); } #[test] fn fill_debug() { struct TestFill; impl Fill for TestFill { fn fill(&self, slot: &mut Slot) -> Result<(), Error> { slot.fill_any(42u64) } } assert_eq!( format!("{:04?}", 42u64), format!("{:04?}", Value::from_fill(&TestFill)), ) } } log-0.4.11/src/kv/value/impls.rs000064400000000000000000000100531370145502000145150ustar 00000000000000//! Converting standard types into `Value`s. //! //! This module provides `ToValue` implementations for commonly //! logged types from the standard library. use std::fmt; use super::{Primitive, ToValue, Value}; macro_rules! impl_into_owned { ($($into_ty:ty => $convert:ident,)*) => { $( impl ToValue for $into_ty { fn to_value(&self) -> Value { Value::from(*self) } } impl<'v> From<$into_ty> for Value<'v> { fn from(value: $into_ty) -> Self { Value::from_primitive(value as $convert) } } )* }; } impl<'v> ToValue for &'v str { fn to_value(&self) -> Value { Value::from(*self) } } impl<'v> From<&'v str> for Value<'v> { fn from(value: &'v str) -> Self { Value::from_primitive(value) } } impl<'v> ToValue for fmt::Arguments<'v> { fn to_value(&self) -> Value { Value::from(*self) } } impl<'v> From> for Value<'v> { fn from(value: fmt::Arguments<'v>) -> Self { Value::from_primitive(value) } } impl ToValue for () { fn to_value(&self) -> Value { Value::from_primitive(Primitive::None) } } impl ToValue for Option where T: ToValue, { fn to_value(&self) -> Value { match *self { Some(ref value) => value.to_value(), None => Value::from_primitive(Primitive::None), } } } impl_into_owned! [ usize => u64, u8 => u64, u16 => u64, u32 => u64, u64 => u64, isize => i64, i8 => i64, i16 => i64, i32 => i64, i64 => i64, f32 => f64, f64 => f64, char => char, bool => bool, ]; #[cfg(feature = "std")] mod std_support { use super::*; use std::borrow::Cow; impl ToValue for Box where T: ToValue + ?Sized, { fn to_value(&self) -> Value { (**self).to_value() } } impl ToValue for String { fn to_value(&self) -> Value { Value::from_primitive(Primitive::Str(&*self)) } } impl<'v> ToValue for Cow<'v, str> { fn to_value(&self) -> Value { Value::from_primitive(Primitive::Str(&*self)) } } } #[cfg(test)] mod tests { use super::*; use kv::value::test::Token; #[test] fn test_to_value_display() { assert_eq!(42u64.to_value().to_string(), "42"); assert_eq!(42i64.to_value().to_string(), "42"); assert_eq!(42.01f64.to_value().to_string(), "42.01"); assert_eq!(true.to_value().to_string(), "true"); assert_eq!('a'.to_value().to_string(), "a"); assert_eq!( format_args!("a {}", "value").to_value().to_string(), "a value" ); assert_eq!("a loong string".to_value().to_string(), "a loong string"); assert_eq!(Some(true).to_value().to_string(), "true"); assert_eq!(().to_value().to_string(), "None"); assert_eq!(Option::None::.to_value().to_string(), "None"); } #[test] fn test_to_value_structured() { assert_eq!(42u64.to_value().to_token(), Token::U64(42)); assert_eq!(42i64.to_value().to_token(), Token::I64(42)); assert_eq!(42.01f64.to_value().to_token(), Token::F64(42.01)); assert_eq!(true.to_value().to_token(), Token::Bool(true)); assert_eq!('a'.to_value().to_token(), Token::Char('a')); assert_eq!( format_args!("a {}", "value").to_value().to_token(), Token::Str("a value".into()) ); assert_eq!( "a loong string".to_value().to_token(), Token::Str("a loong string".into()) ); assert_eq!(Some(true).to_value().to_token(), Token::Bool(true)); assert_eq!(().to_value().to_token(), Token::None); assert_eq!(Option::None::.to_value().to_token(), Token::None); } } log-0.4.11/src/kv/value/internal/cast.rs000064400000000000000000000355641370145501200161560ustar 00000000000000//! Coerce a `Value` into some concrete types. //! //! These operations are cheap when the captured value is a simple primitive, //! but may end up executing arbitrary caller code if the value is complex. //! They will also attempt to downcast erased types into a primitive where possible. use std::any::TypeId; use std::fmt; use super::{Erased, Inner, Primitive, Visitor}; use crate::kv::value::{Error, Value}; impl<'v> Value<'v> { /// Try get a `usize` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_usize(&self) -> Option { self.inner .cast() .into_primitive() .into_u64() .map(|v| v as usize) } /// Try get a `u8` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_u8(&self) -> Option { self.inner .cast() .into_primitive() .into_u64() .map(|v| v as u8) } /// Try get a `u16` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_u16(&self) -> Option { self.inner .cast() .into_primitive() .into_u64() .map(|v| v as u16) } /// Try get a `u32` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_u32(&self) -> Option { self.inner .cast() .into_primitive() .into_u64() .map(|v| v as u32) } /// Try get a `u64` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_u64(&self) -> Option { self.inner.cast().into_primitive().into_u64() } /// Try get a `isize` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_isize(&self) -> Option { self.inner .cast() .into_primitive() .into_i64() .map(|v| v as isize) } /// Try get a `i8` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_i8(&self) -> Option { self.inner .cast() .into_primitive() .into_i64() .map(|v| v as i8) } /// Try get a `i16` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_i16(&self) -> Option { self.inner .cast() .into_primitive() .into_i64() .map(|v| v as i16) } /// Try get a `i32` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_i32(&self) -> Option { self.inner .cast() .into_primitive() .into_i64() .map(|v| v as i32) } /// Try get a `i64` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_i64(&self) -> Option { self.inner.cast().into_primitive().into_i64() } /// Try get a `f32` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_f32(&self) -> Option { self.inner .cast() .into_primitive() .into_f64() .map(|v| v as f32) } /// Try get a `f64` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_f64(&self) -> Option { self.inner.cast().into_primitive().into_f64() } /// Try get a `bool` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_bool(&self) -> Option { self.inner.cast().into_primitive().into_bool() } /// Try get a `char` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. pub fn to_char(&self) -> Option { self.inner.cast().into_primitive().into_char() } /// Try get a `str` from this value. /// /// This method is cheap for primitive types. It won't allocate an owned /// `String` if the value is a complex type. pub fn to_borrowed_str(&self) -> Option<&str> { self.inner.cast().into_primitive().into_borrowed_str() } } impl<'v> Inner<'v> { /// Cast the inner value to another type. fn cast(self) -> Cast<'v> { struct CastVisitor<'v>(Cast<'v>); impl<'v> Visitor<'v> for CastVisitor<'v> { fn debug(&mut self, _: &dyn fmt::Debug) -> Result<(), Error> { Ok(()) } fn u64(&mut self, v: u64) -> Result<(), Error> { self.0 = Cast::Primitive(Primitive::Unsigned(v)); Ok(()) } fn i64(&mut self, v: i64) -> Result<(), Error> { self.0 = Cast::Primitive(Primitive::Signed(v)); Ok(()) } fn f64(&mut self, v: f64) -> Result<(), Error> { self.0 = Cast::Primitive(Primitive::Float(v)); Ok(()) } fn bool(&mut self, v: bool) -> Result<(), Error> { self.0 = Cast::Primitive(Primitive::Bool(v)); Ok(()) } fn char(&mut self, v: char) -> Result<(), Error> { self.0 = Cast::Primitive(Primitive::Char(v)); Ok(()) } fn borrowed_str(&mut self, v: &'v str) -> Result<(), Error> { self.0 = Cast::Primitive(Primitive::Str(v)); Ok(()) } #[cfg(not(feature = "std"))] fn str(&mut self, _: &str) -> Result<(), Error> { Ok(()) } #[cfg(feature = "std")] fn str(&mut self, v: &str) -> Result<(), Error> { self.0 = Cast::String(v.into()); Ok(()) } fn none(&mut self) -> Result<(), Error> { self.0 = Cast::Primitive(Primitive::None); Ok(()) } #[cfg(feature = "kv_unstable_sval")] fn sval(&mut self, v: &dyn super::sval::Value) -> Result<(), Error> { self.0 = super::sval::cast(v); Ok(()) } } // Try downcast an erased value first // It also lets us avoid the Visitor infrastructure for simple primitives let primitive = match self { Inner::Primitive(value) => Some(value), Inner::Fill(value) => value.downcast_primitive(), Inner::Debug(value) => value.downcast_primitive(), Inner::Display(value) => value.downcast_primitive(), #[cfg(feature = "sval")] Inner::Sval(value) => value.downcast_primitive(), }; primitive.map(Cast::Primitive).unwrap_or_else(|| { // If the erased value isn't a primitive then we visit it let mut cast = CastVisitor(Cast::Primitive(Primitive::None)); let _ = self.visit(&mut cast); cast.0 }) } } pub(super) enum Cast<'v> { Primitive(Primitive<'v>), #[cfg(feature = "std")] String(String), } impl<'v> Cast<'v> { fn into_primitive(self) -> Primitive<'v> { match self { Cast::Primitive(value) => value, #[cfg(feature = "std")] _ => Primitive::None, } } } impl<'v> Primitive<'v> { fn into_borrowed_str(self) -> Option<&'v str> { if let Primitive::Str(value) = self { Some(value) } else { None } } fn into_u64(self) -> Option { match self { Primitive::Unsigned(value) => Some(value), Primitive::Signed(value) => Some(value as u64), Primitive::Float(value) => Some(value as u64), _ => None, } } fn into_i64(self) -> Option { match self { Primitive::Signed(value) => Some(value), Primitive::Unsigned(value) => Some(value as i64), Primitive::Float(value) => Some(value as i64), _ => None, } } fn into_f64(self) -> Option { match self { Primitive::Float(value) => Some(value), Primitive::Unsigned(value) => Some(value as f64), Primitive::Signed(value) => Some(value as f64), _ => None, } } fn into_char(self) -> Option { if let Primitive::Char(value) = self { Some(value) } else { None } } fn into_bool(self) -> Option { if let Primitive::Bool(value) = self { Some(value) } else { None } } } impl<'v, T: ?Sized + 'static> Erased<'v, T> { // NOTE: This function is a perfect candidate for memoization // The outcome could be stored in a `Cell` fn downcast_primitive(self) -> Option> { macro_rules! type_ids { ($($value:ident : $ty:ty => $cast:expr,)*) => {{ struct TypeIds; impl TypeIds { fn downcast_primitive<'v, T: ?Sized>(&self, value: Erased<'v, T>) -> Option> { $( if TypeId::of::<$ty>() == value.type_id { let $value = unsafe { value.downcast_unchecked::<$ty>() }; return Some(Primitive::from($cast)); } )* None } } TypeIds }}; } let type_ids = type_ids![ value: usize => *value as u64, value: u8 => *value as u64, value: u16 => *value as u64, value: u32 => *value as u64, value: u64 => *value, value: isize => *value as i64, value: i8 => *value as i64, value: i16 => *value as i64, value: i32 => *value as i64, value: i64 => *value, value: f32 => *value as f64, value: f64 => *value, value: char => *value, value: bool => *value, value: &str => *value, ]; type_ids.downcast_primitive(self) } } #[cfg(feature = "std")] mod std_support { use super::*; use std::borrow::Cow; impl<'v> Value<'v> { /// Try get a `usize` from this value. /// /// This method is cheap for primitive types, but may call arbitrary /// serialization implementations for complex ones. If the serialization /// implementation produces a short lived string it will be allocated. pub fn to_str(&self) -> Option> { self.inner.cast().into_str() } } impl<'v> Cast<'v> { pub(super) fn into_str(self) -> Option> { match self { Cast::Primitive(Primitive::Str(value)) => Some(value.into()), Cast::String(value) => Some(value.into()), _ => None, } } } #[cfg(test)] mod tests { use crate::kv::ToValue; #[test] fn primitive_cast() { assert_eq!( "a string", "a string" .to_owned() .to_value() .to_borrowed_str() .expect("invalid value") ); assert_eq!( "a string", &*"a string".to_value().to_str().expect("invalid value") ); assert_eq!( "a string", &*"a string" .to_owned() .to_value() .to_str() .expect("invalid value") ); } } } #[cfg(test)] mod tests { use crate::kv::ToValue; #[test] fn primitive_cast() { assert_eq!( "a string", "a string" .to_value() .to_borrowed_str() .expect("invalid value") ); assert_eq!( "a string", Some("a string") .to_value() .to_borrowed_str() .expect("invalid value") ); assert_eq!(1u8, 1u64.to_value().to_u8().expect("invalid value")); assert_eq!(1u16, 1u64.to_value().to_u16().expect("invalid value")); assert_eq!(1u32, 1u64.to_value().to_u32().expect("invalid value")); assert_eq!(1u64, 1u64.to_value().to_u64().expect("invalid value")); assert_eq!(1usize, 1u64.to_value().to_usize().expect("invalid value")); assert_eq!(-1i8, -1i64.to_value().to_i8().expect("invalid value")); assert_eq!(-1i16, -1i64.to_value().to_i16().expect("invalid value")); assert_eq!(-1i32, -1i64.to_value().to_i32().expect("invalid value")); assert_eq!(-1i64, -1i64.to_value().to_i64().expect("invalid value")); assert_eq!(-1isize, -1i64.to_value().to_isize().expect("invalid value")); assert!(1f32.to_value().to_f32().is_some(), "invalid value"); assert!(1f64.to_value().to_f64().is_some(), "invalid value"); assert_eq!(1u32, 1i64.to_value().to_u32().expect("invalid value")); assert_eq!(1i32, 1u64.to_value().to_i32().expect("invalid value")); assert!(1f32.to_value().to_i32().is_some(), "invalid value"); assert_eq!('a', 'a'.to_value().to_char().expect("invalid value")); assert_eq!(true, true.to_value().to_bool().expect("invalid value")); } } log-0.4.11/src/kv/value/internal/fmt.rs000064400000000000000000000151451370145502000160020ustar 00000000000000//! Integration between `Value` and `std::fmt`. //! //! This module allows any `Value` to implement the `fmt::Debug` and `fmt::Display` traits, //! and for any `fmt::Debug` or `fmt::Display` to be captured as a `Value`. use std::fmt; use super::{Erased, Inner, Visitor}; use crate::kv; use crate::kv::value::{Error, Slot}; impl<'v> kv::Value<'v> { /// Get a value from a debuggable type. pub fn from_debug(value: &'v T) -> Self where T: fmt::Debug + 'static, { kv::Value { inner: Inner::Debug(unsafe { Erased::new_unchecked::(value) }), } } /// Get a value from a displayable type. pub fn from_display(value: &'v T) -> Self where T: fmt::Display + 'static, { kv::Value { inner: Inner::Display(unsafe { Erased::new_unchecked::(value) }), } } } impl<'s, 'f> Slot<'s, 'f> { /// Fill the slot with a debuggable value. /// /// The given value doesn't need to satisfy any particular lifetime constraints. /// /// # Panics /// /// Calling more than a single `fill` method on this slot will panic. pub fn fill_debug(&mut self, value: T) -> Result<(), Error> where T: fmt::Debug, { self.fill(|visitor| visitor.debug(&value)) } /// Fill the slot with a displayable value. /// /// The given value doesn't need to satisfy any particular lifetime constraints. /// /// # Panics /// /// Calling more than a single `fill` method on this slot will panic. pub fn fill_display(&mut self, value: T) -> Result<(), Error> where T: fmt::Display, { self.fill(|visitor| visitor.display(&value)) } } pub(in kv::value) use self::fmt::{Arguments, Debug, Display}; impl<'v> fmt::Debug for kv::Value<'v> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct DebugVisitor<'a, 'b: 'a>(&'a mut fmt::Formatter<'b>); impl<'a, 'b: 'a, 'v> Visitor<'v> for DebugVisitor<'a, 'b> { fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error> { fmt::Debug::fmt(v, self.0)?; Ok(()) } fn display(&mut self, v: &dyn fmt::Display) -> Result<(), Error> { fmt::Display::fmt(v, self.0)?; Ok(()) } fn u64(&mut self, v: u64) -> Result<(), Error> { fmt::Debug::fmt(&v, self.0)?; Ok(()) } fn i64(&mut self, v: i64) -> Result<(), Error> { fmt::Debug::fmt(&v, self.0)?; Ok(()) } fn f64(&mut self, v: f64) -> Result<(), Error> { fmt::Debug::fmt(&v, self.0)?; Ok(()) } fn bool(&mut self, v: bool) -> Result<(), Error> { fmt::Debug::fmt(&v, self.0)?; Ok(()) } fn char(&mut self, v: char) -> Result<(), Error> { fmt::Debug::fmt(&v, self.0)?; Ok(()) } fn str(&mut self, v: &str) -> Result<(), Error> { fmt::Debug::fmt(&v, self.0)?; Ok(()) } fn none(&mut self) -> Result<(), Error> { self.debug(&format_args!("None")) } #[cfg(feature = "kv_unstable_sval")] fn sval(&mut self, v: &dyn super::sval::Value) -> Result<(), Error> { super::sval::fmt(self.0, v) } } self.visit(&mut DebugVisitor(f)).map_err(|_| fmt::Error)?; Ok(()) } } impl<'v> fmt::Display for kv::Value<'v> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct DisplayVisitor<'a, 'b: 'a>(&'a mut fmt::Formatter<'b>); impl<'a, 'b: 'a, 'v> Visitor<'v> for DisplayVisitor<'a, 'b> { fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error> { fmt::Debug::fmt(v, self.0)?; Ok(()) } fn display(&mut self, v: &dyn fmt::Display) -> Result<(), Error> { fmt::Display::fmt(v, self.0)?; Ok(()) } fn u64(&mut self, v: u64) -> Result<(), Error> { fmt::Display::fmt(&v, self.0)?; Ok(()) } fn i64(&mut self, v: i64) -> Result<(), Error> { fmt::Display::fmt(&v, self.0)?; Ok(()) } fn f64(&mut self, v: f64) -> Result<(), Error> { fmt::Display::fmt(&v, self.0)?; Ok(()) } fn bool(&mut self, v: bool) -> Result<(), Error> { fmt::Display::fmt(&v, self.0)?; Ok(()) } fn char(&mut self, v: char) -> Result<(), Error> { fmt::Display::fmt(&v, self.0)?; Ok(()) } fn str(&mut self, v: &str) -> Result<(), Error> { fmt::Display::fmt(&v, self.0)?; Ok(()) } fn none(&mut self) -> Result<(), Error> { self.debug(&format_args!("None")) } #[cfg(feature = "kv_unstable_sval")] fn sval(&mut self, v: &dyn super::sval::Value) -> Result<(), Error> { super::sval::fmt(self.0, v) } } self.visit(&mut DisplayVisitor(f)).map_err(|_| fmt::Error)?; Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::kv::value::ToValue; #[test] fn fmt_cast() { assert_eq!( 42u32, kv::Value::from_debug(&42u64) .to_u32() .expect("invalid value") ); assert_eq!( "a string", kv::Value::from_display(&"a string") .to_borrowed_str() .expect("invalid value") ); } #[test] fn fmt_debug() { assert_eq!( format!("{:?}", "a string"), format!("{:?}", "a string".to_value()), ); assert_eq!( format!("{:04?}", 42u64), format!("{:04?}", 42u64.to_value()), ); } #[test] fn fmt_display() { assert_eq!( format!("{}", "a string"), format!("{}", "a string".to_value()), ); assert_eq!(format!("{:04}", 42u64), format!("{:04}", 42u64.to_value()),); } } log-0.4.11/src/kv/value/internal/mod.rs000064400000000000000000000120171370145501200157670ustar 00000000000000//! The internal `Value` serialization API. //! //! This implementation isn't intended to be public. It may need to change //! for optimizations or to support new external serialization frameworks. use std::any::TypeId; use super::{Error, Fill, Slot}; pub(super) mod cast; pub(super) mod fmt; #[cfg(feature = "kv_unstable_sval")] pub(super) mod sval; /// A container for a structured value for a specific kind of visitor. #[derive(Clone, Copy)] pub(super) enum Inner<'v> { /// A simple primitive value that can be copied without allocating. Primitive(Primitive<'v>), /// A value that can be filled. Fill(Erased<'v, dyn Fill + 'static>), /// A debuggable value. Debug(Erased<'v, dyn fmt::Debug + 'static>), /// A displayable value. Display(Erased<'v, dyn fmt::Display + 'static>), #[cfg(feature = "kv_unstable_sval")] /// A structured value from `sval`. Sval(Erased<'v, dyn sval::Value + 'static>), } impl<'v> Inner<'v> { pub(super) fn visit(self, visitor: &mut dyn Visitor<'v>) -> Result<(), Error> { match self { Inner::Primitive(value) => value.visit(visitor), Inner::Fill(value) => value.get().fill(&mut Slot::new(visitor)), Inner::Debug(value) => visitor.debug(value.get()), Inner::Display(value) => visitor.display(value.get()), #[cfg(feature = "kv_unstable_sval")] Inner::Sval(value) => visitor.sval(value.get()), } } } /// The internal serialization contract. pub(super) trait Visitor<'v> { fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error>; fn display(&mut self, v: &dyn fmt::Display) -> Result<(), Error> { self.debug(&format_args!("{}", v)) } fn u64(&mut self, v: u64) -> Result<(), Error>; fn i64(&mut self, v: i64) -> Result<(), Error>; fn f64(&mut self, v: f64) -> Result<(), Error>; fn bool(&mut self, v: bool) -> Result<(), Error>; fn char(&mut self, v: char) -> Result<(), Error>; fn str(&mut self, v: &str) -> Result<(), Error>; fn borrowed_str(&mut self, v: &'v str) -> Result<(), Error> { self.str(v) } fn none(&mut self) -> Result<(), Error>; #[cfg(feature = "kv_unstable_sval")] fn sval(&mut self, v: &dyn sval::Value) -> Result<(), Error>; } /// A captured primitive value. /// /// These values are common and cheap to copy around. #[derive(Clone, Copy)] pub(super) enum Primitive<'v> { Signed(i64), Unsigned(u64), Float(f64), Bool(bool), Char(char), Str(&'v str), Fmt(fmt::Arguments<'v>), None, } impl<'v> Primitive<'v> { fn visit(self, visitor: &mut dyn Visitor<'v>) -> Result<(), Error> { match self { Primitive::Signed(value) => visitor.i64(value), Primitive::Unsigned(value) => visitor.u64(value), Primitive::Float(value) => visitor.f64(value), Primitive::Bool(value) => visitor.bool(value), Primitive::Char(value) => visitor.char(value), Primitive::Str(value) => visitor.borrowed_str(value), Primitive::Fmt(value) => visitor.debug(&value), Primitive::None => visitor.none(), } } } impl<'v> From for Primitive<'v> { fn from(v: u64) -> Self { Primitive::Unsigned(v) } } impl<'v> From for Primitive<'v> { fn from(v: i64) -> Self { Primitive::Signed(v) } } impl<'v> From for Primitive<'v> { fn from(v: f64) -> Self { Primitive::Float(v) } } impl<'v> From for Primitive<'v> { fn from(v: bool) -> Self { Primitive::Bool(v) } } impl<'v> From for Primitive<'v> { fn from(v: char) -> Self { Primitive::Char(v) } } impl<'v> From<&'v str> for Primitive<'v> { fn from(v: &'v str) -> Self { Primitive::Str(v) } } impl<'v> From> for Primitive<'v> { fn from(v: fmt::Arguments<'v>) -> Self { Primitive::Fmt(v) } } /// A downcastable dynamic type. pub(super) struct Erased<'v, T: ?Sized> { type_id: TypeId, inner: &'v T, } impl<'v, T: ?Sized> Clone for Erased<'v, T> { fn clone(&self) -> Self { Erased { type_id: self.type_id, inner: self.inner, } } } impl<'v, T: ?Sized> Copy for Erased<'v, T> {} impl<'v, T: ?Sized> Erased<'v, T> { // SAFETY: `U: Unsize` and the underlying value `T` must not change // We could add a safe variant of this method with the `Unsize` trait pub(super) unsafe fn new_unchecked(inner: &'v T) -> Self where U: 'static, T: 'static, { Erased { type_id: TypeId::of::(), inner, } } pub(super) fn get(self) -> &'v T { self.inner } // SAFETY: The underlying type of `T` is `U` pub(super) unsafe fn downcast_unchecked(self) -> &'v U { &*(self.inner as *const T as *const U) } } log-0.4.11/src/kv/value/internal/sval.rs000064400000000000000000000133721370145502000161610ustar 00000000000000//! Integration between `Value` and `sval`. //! //! This module allows any `Value` to implement the `sval::Value` trait, //! and for any `sval::Value` to be captured as a `Value`. extern crate sval; use std::fmt; use super::cast::Cast; use super::{Erased, Inner, Primitive, Visitor}; use crate::kv; use crate::kv::value::{Error, Slot}; impl<'v> kv::Value<'v> { /// Get a value from a structured type. pub fn from_sval(value: &'v T) -> Self where T: sval::Value + 'static, { kv::Value { inner: Inner::Sval(unsafe { Erased::new_unchecked::(value) }), } } } impl<'s, 'f> Slot<'s, 'f> { /// Fill the slot with a structured value. /// /// The given value doesn't need to satisfy any particular lifetime constraints. /// /// # Panics /// /// Calling more than a single `fill` method on this slot will panic. pub fn fill_sval(&mut self, value: T) -> Result<(), Error> where T: sval::Value, { self.fill(|visitor| visitor.sval(&value)) } } impl<'v> sval::Value for kv::Value<'v> { fn stream(&self, s: &mut sval::value::Stream) -> sval::value::Result { struct SvalVisitor<'a, 'b: 'a>(&'a mut sval::value::Stream<'b>); impl<'a, 'b: 'a, 'v> Visitor<'v> for SvalVisitor<'a, 'b> { fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error> { self.0 .fmt(format_args!("{:?}", v)) .map_err(Error::from_sval) } fn u64(&mut self, v: u64) -> Result<(), Error> { self.0.u64(v).map_err(Error::from_sval) } fn i64(&mut self, v: i64) -> Result<(), Error> { self.0.i64(v).map_err(Error::from_sval) } fn f64(&mut self, v: f64) -> Result<(), Error> { self.0.f64(v).map_err(Error::from_sval) } fn bool(&mut self, v: bool) -> Result<(), Error> { self.0.bool(v).map_err(Error::from_sval) } fn char(&mut self, v: char) -> Result<(), Error> { self.0.char(v).map_err(Error::from_sval) } fn str(&mut self, v: &str) -> Result<(), Error> { self.0.str(v).map_err(Error::from_sval) } fn none(&mut self) -> Result<(), Error> { self.0.none().map_err(Error::from_sval) } fn sval(&mut self, v: &dyn sval::Value) -> Result<(), Error> { self.0.any(v).map_err(Error::from_sval) } } self.visit(&mut SvalVisitor(s)).map_err(Error::into_sval)?; Ok(()) } } pub(in kv::value) use self::sval::Value; pub(super) fn fmt(f: &mut fmt::Formatter, v: &dyn sval::Value) -> Result<(), Error> { sval::fmt::debug(f, v)?; Ok(()) } pub(super) fn cast<'v>(v: &dyn sval::Value) -> Cast<'v> { struct CastStream<'v>(Cast<'v>); impl<'v> sval::Stream for CastStream<'v> { fn u64(&mut self, v: u64) -> sval::stream::Result { self.0 = Cast::Primitive(Primitive::Unsigned(v)); Ok(()) } fn i64(&mut self, v: i64) -> sval::stream::Result { self.0 = Cast::Primitive(Primitive::Signed(v)); Ok(()) } fn f64(&mut self, v: f64) -> sval::stream::Result { self.0 = Cast::Primitive(Primitive::Float(v)); Ok(()) } fn char(&mut self, v: char) -> sval::stream::Result { self.0 = Cast::Primitive(Primitive::Char(v)); Ok(()) } fn bool(&mut self, v: bool) -> sval::stream::Result { self.0 = Cast::Primitive(Primitive::Bool(v)); Ok(()) } #[cfg(feature = "std")] fn str(&mut self, s: &str) -> sval::stream::Result { self.0 = Cast::String(s.into()); Ok(()) } } let mut cast = CastStream(Cast::Primitive(Primitive::None)); let _ = sval::stream(&mut cast, v); cast.0 } impl Error { fn from_sval(_: sval::value::Error) -> Self { Error::msg("`sval` serialization failed") } fn into_sval(self) -> sval::value::Error { sval::value::Error::msg("`sval` serialization failed") } } #[cfg(test)] mod tests { use super::*; use kv::value::test::Token; #[test] fn test_from_sval() { assert_eq!(kv::Value::from_sval(&42u64).to_token(), Token::Sval); } #[test] fn test_sval_structured() { let value = kv::Value::from(42u64); let expected = vec![sval::test::Token::Unsigned(42)]; assert_eq!(sval::test::tokens(value), expected); } #[test] fn sval_cast() { assert_eq!( 42u32, kv::Value::from_sval(&42u64) .to_u32() .expect("invalid value") ); assert_eq!( "a string", kv::Value::from_sval(&"a string") .to_borrowed_str() .expect("invalid value") ); #[cfg(feature = "std")] assert_eq!( "a string", kv::Value::from_sval(&"a string") .to_str() .expect("invalid value") ); } #[test] fn sval_debug() { struct TestSval; impl sval::Value for TestSval { fn stream(&self, stream: &mut sval::value::Stream) -> sval::value::Result { stream.u64(42) } } assert_eq!( format!("{:04?}", 42u64), format!("{:04?}", kv::Value::from_sval(&TestSval)), ); } } log-0.4.11/src/kv/value/mod.rs000064400000000000000000000022211370145501200141470ustar 00000000000000//! Structured values. mod fill; mod impls; mod internal; #[cfg(test)] pub(in kv) mod test; pub use self::fill::{Fill, Slot}; pub use kv::Error; use self::internal::{Inner, Primitive, Visitor}; /// A type that can be converted into a [`Value`](struct.Value.html). pub trait ToValue { /// Perform the conversion. fn to_value(&self) -> Value; } impl<'a, T> ToValue for &'a T where T: ToValue + ?Sized, { fn to_value(&self) -> Value { (**self).to_value() } } impl<'v> ToValue for Value<'v> { fn to_value(&self) -> Value { Value { inner: self.inner } } } /// A value in a structured key-value pair. pub struct Value<'v> { inner: Inner<'v>, } impl<'v> Value<'v> { /// Get a value from an internal primitive. fn from_primitive(value: T) -> Self where T: Into>, { Value { inner: Inner::Primitive(value.into()), } } /// Visit the value using an internal visitor. fn visit<'a>(&'a self, visitor: &mut dyn Visitor<'a>) -> Result<(), Error> { self.inner.visit(visitor) } } log-0.4.11/src/kv/value/test.rs000064400000000000000000000041241366165217300143670ustar 00000000000000// Test support for inspecting Values use std::fmt; use std::str; use super::internal; use super::{Error, Value}; #[derive(Debug, PartialEq)] pub(in kv) enum Token { U64(u64), I64(i64), F64(f64), Char(char), Bool(bool), Str(String), None, #[cfg(feature = "kv_unstable_sval")] Sval, } #[cfg(test)] impl<'v> Value<'v> { pub(in kv) fn to_token(&self) -> Token { struct TestVisitor(Option); impl<'v> internal::Visitor<'v> for TestVisitor { fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error> { self.0 = Some(Token::Str(format!("{:?}", v))); Ok(()) } fn u64(&mut self, v: u64) -> Result<(), Error> { self.0 = Some(Token::U64(v)); Ok(()) } fn i64(&mut self, v: i64) -> Result<(), Error> { self.0 = Some(Token::I64(v)); Ok(()) } fn f64(&mut self, v: f64) -> Result<(), Error> { self.0 = Some(Token::F64(v)); Ok(()) } fn bool(&mut self, v: bool) -> Result<(), Error> { self.0 = Some(Token::Bool(v)); Ok(()) } fn char(&mut self, v: char) -> Result<(), Error> { self.0 = Some(Token::Char(v)); Ok(()) } fn str(&mut self, v: &str) -> Result<(), Error> { self.0 = Some(Token::Str(v.into())); Ok(()) } fn none(&mut self) -> Result<(), Error> { self.0 = Some(Token::None); Ok(()) } #[cfg(feature = "kv_unstable_sval")] fn sval(&mut self, _: &dyn internal::sval::Value) -> Result<(), Error> { self.0 = Some(Token::Sval); Ok(()) } } let mut visitor = TestVisitor(None); self.visit(&mut visitor).unwrap(); visitor.0.unwrap() } } log-0.4.11/src/lib.rs000064400000000000000000001503061370372502000124130ustar 00000000000000// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A lightweight logging facade. //! //! The `log` crate provides a single logging API that abstracts over the //! actual logging implementation. Libraries can use the logging API provided //! by this crate, and the consumer of those libraries can choose the logging //! implementation that is most suitable for its use case. //! //! If no logging implementation is selected, the facade falls back to a "noop" //! implementation that ignores all log messages. The overhead in this case //! is very small - just an integer load, comparison and jump. //! //! A log request consists of a _target_, a _level_, and a _body_. A target is a //! string which defaults to the module path of the location of the log request, //! though that default may be overridden. Logger implementations typically use //! the target to filter requests based on some user configuration. //! //! # Use //! //! The basic use of the log crate is through the five logging macros: [`error!`], //! [`warn!`], [`info!`], [`debug!`] and [`trace!`] //! where `error!` represents the highest-priority log messages //! and `trace!` the lowest. The log messages are filtered by configuring //! the log level to exclude messages with a lower priority. //! Each of these macros accept format strings similarly to [`println!`]. //! //! //! [`error!`]: ./macro.error.html //! [`warn!`]: ./macro.warn.html //! [`info!`]: ./macro.info.html //! [`debug!`]: ./macro.debug.html //! [`trace!`]: ./macro.trace.html //! [`println!`]: https://doc.rust-lang.org/stable/std/macro.println.html //! //! ## In libraries //! //! Libraries should link only to the `log` crate, and use the provided //! macros to log whatever information will be useful to downstream consumers. //! //! ### Examples //! //! ```edition2018 //! # #[derive(Debug)] pub struct Yak(String); //! # impl Yak { fn shave(&mut self, _: u32) {} } //! # fn find_a_razor() -> Result { Ok(1) } //! use log::{info, warn}; //! //! pub fn shave_the_yak(yak: &mut Yak) { //! info!(target: "yak_events", "Commencing yak shaving for {:?}", yak); //! //! loop { //! match find_a_razor() { //! Ok(razor) => { //! info!("Razor located: {}", razor); //! yak.shave(razor); //! break; //! } //! Err(err) => { //! warn!("Unable to locate a razor: {}, retrying", err); //! } //! } //! } //! } //! # fn main() {} //! ``` //! //! ## In executables //! //! Executables should choose a logging implementation and initialize it early in the //! runtime of the program. Logging implementations will typically include a //! function to do this. Any log messages generated before //! the implementation is initialized will be ignored. //! //! The executable itself may use the `log` crate to log as well. //! //! ### Warning //! //! The logging system may only be initialized once. //! //! # Available logging implementations //! //! In order to produce log output executables have to use //! a logger implementation compatible with the facade. //! There are many available implementations to choose from, //! here are some of the most popular ones: //! //! * Simple minimal loggers: //! * [env_logger] //! * [simple_logger] //! * [simplelog] //! * [pretty_env_logger] //! * [stderrlog] //! * [flexi_logger] //! * Complex configurable frameworks: //! * [log4rs] //! * [fern] //! * Adaptors for other facilities: //! * [syslog] //! * [slog-stdlog] //! //! # Implementing a Logger //! //! Loggers implement the [`Log`] trait. Here's a very basic example that simply //! logs all messages at the [`Error`][level_link], [`Warn`][level_link] or //! [`Info`][level_link] levels to stdout: //! //! ```edition2018 //! use log::{Record, Level, Metadata}; //! //! struct SimpleLogger; //! //! impl log::Log for SimpleLogger { //! fn enabled(&self, metadata: &Metadata) -> bool { //! metadata.level() <= Level::Info //! } //! //! fn log(&self, record: &Record) { //! if self.enabled(record.metadata()) { //! println!("{} - {}", record.level(), record.args()); //! } //! } //! //! fn flush(&self) {} //! } //! //! # fn main() {} //! ``` //! //! Loggers are installed by calling the [`set_logger`] function. The maximum //! log level also needs to be adjusted via the [`set_max_level`] function. The //! logging facade uses this as an optimization to improve performance of log //! messages at levels that are disabled. It's important to set it, as it //! defaults to [`Off`][filter_link], so no log messages will ever be captured! //! In the case of our example logger, we'll want to set the maximum log level //! to [`Info`][filter_link], since we ignore any [`Debug`][level_link] or //! [`Trace`][level_link] level log messages. A logging implementation should //! provide a function that wraps a call to [`set_logger`] and //! [`set_max_level`], handling initialization of the logger: //! //! ```edition2018 //! # use log::{Level, Metadata}; //! # struct SimpleLogger; //! # impl log::Log for SimpleLogger { //! # fn enabled(&self, _: &Metadata) -> bool { false } //! # fn log(&self, _: &log::Record) {} //! # fn flush(&self) {} //! # } //! # fn main() {} //! use log::{SetLoggerError, LevelFilter}; //! //! static LOGGER: SimpleLogger = SimpleLogger; //! //! pub fn init() -> Result<(), SetLoggerError> { //! log::set_logger(&LOGGER) //! .map(|()| log::set_max_level(LevelFilter::Info)) //! } //! ``` //! //! Implementations that adjust their configurations at runtime should take care //! to adjust the maximum log level as well. //! //! # Use with `std` //! //! `set_logger` requires you to provide a `&'static Log`, which can be hard to //! obtain if your logger depends on some runtime configuration. The //! `set_boxed_logger` function is available with the `std` Cargo feature. It is //! identical to `set_logger` except that it takes a `Box` rather than a //! `&'static Log`: //! //! ```edition2018 //! # use log::{Level, LevelFilter, Log, SetLoggerError, Metadata}; //! # struct SimpleLogger; //! # impl log::Log for SimpleLogger { //! # fn enabled(&self, _: &Metadata) -> bool { false } //! # fn log(&self, _: &log::Record) {} //! # fn flush(&self) {} //! # } //! # fn main() {} //! # #[cfg(feature = "std")] //! pub fn init() -> Result<(), SetLoggerError> { //! log::set_boxed_logger(Box::new(SimpleLogger)) //! .map(|()| log::set_max_level(LevelFilter::Info)) //! } //! ``` //! //! # Compile time filters //! //! Log levels can be statically disabled at compile time via Cargo features. Log invocations at //! disabled levels will be skipped and will not even be present in the resulting binary. //! This level is configured separately for release and debug builds. The features are: //! //! * `max_level_off` //! * `max_level_error` //! * `max_level_warn` //! * `max_level_info` //! * `max_level_debug` //! * `max_level_trace` //! * `release_max_level_off` //! * `release_max_level_error` //! * `release_max_level_warn` //! * `release_max_level_info` //! * `release_max_level_debug` //! * `release_max_level_trace` //! //! These features control the value of the `STATIC_MAX_LEVEL` constant. The logging macros check //! this value before logging a message. By default, no levels are disabled. //! //! Libraries should avoid using the max level features because they're global and can't be changed //! once they're set. //! //! For example, a crate can disable trace level logs in debug builds and trace, debug, and info //! level logs in release builds with the following configuration: //! //! ```toml //! [dependencies] //! log = { version = "0.4", features = ["max_level_debug", "release_max_level_warn"] } //! ``` //! # Crate Feature Flags //! //! The following crate feature flags are available in addition to the filters. They are //! configured in your `Cargo.toml`. //! //! * `std` allows use of `std` crate instead of the default `core`. Enables using `std::error` and //! `set_boxed_logger` functionality. //! * `serde` enables support for serialization and deserialization of `Level` and `LevelFilter`. //! //! ```toml //! [dependencies] //! log = { version = "0.4", features = ["std", "serde"] } //! ``` //! //! # Version compatibility //! //! The 0.3 and 0.4 versions of the `log` crate are almost entirely compatible. Log messages //! made using `log` 0.3 will forward transparently to a logger implementation using `log` 0.4. Log //! messages made using `log` 0.4 will forward to a logger implementation using `log` 0.3, but the //! module path and file name information associated with the message will unfortunately be lost. //! //! [`Log`]: trait.Log.html //! [level_link]: enum.Level.html //! [filter_link]: enum.LevelFilter.html //! [`set_logger`]: fn.set_logger.html //! [`set_max_level`]: fn.set_max_level.html //! [`try_set_logger_raw`]: fn.try_set_logger_raw.html //! [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html //! [env_logger]: https://docs.rs/env_logger/*/env_logger/ //! [simple_logger]: https://github.com/borntyping/rust-simple_logger //! [simplelog]: https://github.com/drakulix/simplelog.rs //! [pretty_env_logger]: https://docs.rs/pretty_env_logger/*/pretty_env_logger/ //! [stderrlog]: https://docs.rs/stderrlog/*/stderrlog/ //! [flexi_logger]: https://docs.rs/flexi_logger/*/flexi_logger/ //! [syslog]: https://docs.rs/syslog/*/syslog/ //! [slog-stdlog]: https://docs.rs/slog-stdlog/*/slog_stdlog/ //! [log4rs]: https://docs.rs/log4rs/*/log4rs/ //! [fern]: https://docs.rs/fern/*/fern/ #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://www.rust-lang.org/favicon.ico", html_root_url = "https://docs.rs/log/0.4.11" )] #![warn(missing_docs)] #![deny(missing_debug_implementations)] #![cfg_attr(all(not(feature = "std"), not(test)), no_std)] // When compiled for the rustc compiler itself we want to make sure that this is // an unstable crate #![cfg_attr(rustbuild, feature(staged_api, rustc_private))] #![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))] #[cfg(all(not(feature = "std"), not(test)))] extern crate core as std; #[macro_use] extern crate cfg_if; use std::cmp; #[cfg(feature = "std")] use std::error; use std::fmt; use std::mem; use std::str::FromStr; use std::sync::atomic::{AtomicUsize, Ordering}; #[macro_use] mod macros; mod serde; #[cfg(feature = "kv_unstable")] pub mod kv; // The LOGGER static holds a pointer to the global logger. It is protected by // the STATE static which determines whether LOGGER has been initialized yet. static mut LOGGER: &dyn Log = &NopLogger; static STATE: AtomicUsize = AtomicUsize::new(0); // There are three different states that we care about: the logger's // uninitialized, the logger's initializing (set_logger's been called but // LOGGER hasn't actually been set yet), or the logger's active. const UNINITIALIZED: usize = 0; const INITIALIZING: usize = 1; const INITIALIZED: usize = 2; static MAX_LOG_LEVEL_FILTER: AtomicUsize = AtomicUsize::new(0); static LOG_LEVEL_NAMES: [&str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"]; static SET_LOGGER_ERROR: &str = "attempted to set a logger after the logging system \ was already initialized"; static LEVEL_PARSE_ERROR: &str = "attempted to convert a string that doesn't match an existing log level"; /// An enum representing the available verbosity levels of the logger. /// /// Typical usage includes: checking if a certain `Level` is enabled with /// [`log_enabled!`](macro.log_enabled.html), specifying the `Level` of /// [`log!`](macro.log.html), and comparing a `Level` directly to a /// [`LevelFilter`](enum.LevelFilter.html). #[repr(usize)] #[derive(Copy, Eq, Debug, Hash)] pub enum Level { /// The "error" level. /// /// Designates very serious errors. // This way these line up with the discriminants for LevelFilter below // This works because Rust treats field-less enums the same way as C does: // https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-field-less-enumerations Error = 1, /// The "warn" level. /// /// Designates hazardous situations. Warn, /// The "info" level. /// /// Designates useful information. Info, /// The "debug" level. /// /// Designates lower priority information. Debug, /// The "trace" level. /// /// Designates very low priority, often extremely verbose, information. Trace, } impl Clone for Level { #[inline] fn clone(&self) -> Level { *self } } impl PartialEq for Level { #[inline] fn eq(&self, other: &Level) -> bool { *self as usize == *other as usize } } impl PartialEq for Level { #[inline] fn eq(&self, other: &LevelFilter) -> bool { *self as usize == *other as usize } } impl PartialOrd for Level { #[inline] fn partial_cmp(&self, other: &Level) -> Option { Some(self.cmp(other)) } #[inline] fn lt(&self, other: &Level) -> bool { (*self as usize) < *other as usize } #[inline] fn le(&self, other: &Level) -> bool { *self as usize <= *other as usize } #[inline] fn gt(&self, other: &Level) -> bool { *self as usize > *other as usize } #[inline] fn ge(&self, other: &Level) -> bool { *self as usize >= *other as usize } } impl PartialOrd for Level { #[inline] fn partial_cmp(&self, other: &LevelFilter) -> Option { Some((*self as usize).cmp(&(*other as usize))) } #[inline] fn lt(&self, other: &LevelFilter) -> bool { (*self as usize) < *other as usize } #[inline] fn le(&self, other: &LevelFilter) -> bool { *self as usize <= *other as usize } #[inline] fn gt(&self, other: &LevelFilter) -> bool { *self as usize > *other as usize } #[inline] fn ge(&self, other: &LevelFilter) -> bool { *self as usize >= *other as usize } } impl Ord for Level { #[inline] fn cmp(&self, other: &Level) -> cmp::Ordering { (*self as usize).cmp(&(*other as usize)) } } fn ok_or(t: Option, e: E) -> Result { match t { Some(t) => Ok(t), None => Err(e), } } // Reimplemented here because std::ascii is not available in libcore fn eq_ignore_ascii_case(a: &str, b: &str) -> bool { fn to_ascii_uppercase(c: u8) -> u8 { if c >= b'a' && c <= b'z' { c - b'a' + b'A' } else { c } } if a.len() == b.len() { a.bytes() .zip(b.bytes()) .all(|(a, b)| to_ascii_uppercase(a) == to_ascii_uppercase(b)) } else { false } } impl FromStr for Level { type Err = ParseLevelError; fn from_str(level: &str) -> Result { ok_or( LOG_LEVEL_NAMES .iter() .position(|&name| eq_ignore_ascii_case(name, level)) .into_iter() .filter(|&idx| idx != 0) .map(|idx| Level::from_usize(idx).unwrap()) .next(), ParseLevelError(()), ) } } impl fmt::Display for Level { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.pad(LOG_LEVEL_NAMES[*self as usize]) } } impl Level { fn from_usize(u: usize) -> Option { match u { 1 => Some(Level::Error), 2 => Some(Level::Warn), 3 => Some(Level::Info), 4 => Some(Level::Debug), 5 => Some(Level::Trace), _ => None, } } /// Returns the most verbose logging level. #[inline] pub fn max() -> Level { Level::Trace } /// Converts the `Level` to the equivalent `LevelFilter`. #[inline] pub fn to_level_filter(&self) -> LevelFilter { LevelFilter::from_usize(*self as usize).unwrap() } } /// An enum representing the available verbosity level filters of the logger. /// /// A `LevelFilter` may be compared directly to a [`Level`]. Use this type /// to get and set the maximum log level with [`max_level()`] and [`set_max_level`]. /// /// [`Level`]: enum.Level.html /// [`max_level()`]: fn.max_level.html /// [`set_max_level`]: fn.set_max_level.html #[repr(usize)] #[derive(Copy, Eq, Debug, Hash)] pub enum LevelFilter { /// A level lower than all log levels. Off, /// Corresponds to the `Error` log level. Error, /// Corresponds to the `Warn` log level. Warn, /// Corresponds to the `Info` log level. Info, /// Corresponds to the `Debug` log level. Debug, /// Corresponds to the `Trace` log level. Trace, } // Deriving generates terrible impls of these traits impl Clone for LevelFilter { #[inline] fn clone(&self) -> LevelFilter { *self } } impl PartialEq for LevelFilter { #[inline] fn eq(&self, other: &LevelFilter) -> bool { *self as usize == *other as usize } } impl PartialEq for LevelFilter { #[inline] fn eq(&self, other: &Level) -> bool { other.eq(self) } } impl PartialOrd for LevelFilter { #[inline] fn partial_cmp(&self, other: &LevelFilter) -> Option { Some(self.cmp(other)) } #[inline] fn lt(&self, other: &LevelFilter) -> bool { (*self as usize) < *other as usize } #[inline] fn le(&self, other: &LevelFilter) -> bool { *self as usize <= *other as usize } #[inline] fn gt(&self, other: &LevelFilter) -> bool { *self as usize > *other as usize } #[inline] fn ge(&self, other: &LevelFilter) -> bool { *self as usize >= *other as usize } } impl PartialOrd for LevelFilter { #[inline] fn partial_cmp(&self, other: &Level) -> Option { Some((*self as usize).cmp(&(*other as usize))) } #[inline] fn lt(&self, other: &Level) -> bool { (*self as usize) < *other as usize } #[inline] fn le(&self, other: &Level) -> bool { *self as usize <= *other as usize } #[inline] fn gt(&self, other: &Level) -> bool { *self as usize > *other as usize } #[inline] fn ge(&self, other: &Level) -> bool { *self as usize >= *other as usize } } impl Ord for LevelFilter { #[inline] fn cmp(&self, other: &LevelFilter) -> cmp::Ordering { (*self as usize).cmp(&(*other as usize)) } } impl FromStr for LevelFilter { type Err = ParseLevelError; fn from_str(level: &str) -> Result { ok_or( LOG_LEVEL_NAMES .iter() .position(|&name| eq_ignore_ascii_case(name, level)) .map(|p| LevelFilter::from_usize(p).unwrap()), ParseLevelError(()), ) } } impl fmt::Display for LevelFilter { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.pad(LOG_LEVEL_NAMES[*self as usize]) } } impl LevelFilter { fn from_usize(u: usize) -> Option { match u { 0 => Some(LevelFilter::Off), 1 => Some(LevelFilter::Error), 2 => Some(LevelFilter::Warn), 3 => Some(LevelFilter::Info), 4 => Some(LevelFilter::Debug), 5 => Some(LevelFilter::Trace), _ => None, } } /// Returns the most verbose logging level filter. #[inline] pub fn max() -> LevelFilter { LevelFilter::Trace } /// Converts `self` to the equivalent `Level`. /// /// Returns `None` if `self` is `LevelFilter::Off`. #[inline] pub fn to_level(&self) -> Option { Level::from_usize(*self as usize) } } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] enum MaybeStaticStr<'a> { Static(&'static str), Borrowed(&'a str), } impl<'a> MaybeStaticStr<'a> { #[inline] fn get(&self) -> &'a str { match *self { MaybeStaticStr::Static(s) => s, MaybeStaticStr::Borrowed(s) => s, } } } /// The "payload" of a log message. /// /// # Use /// /// `Record` structures are passed as parameters to the [`log`][method.log] /// method of the [`Log`] trait. Logger implementors manipulate these /// structures in order to display log messages. `Record`s are automatically /// created by the [`log!`] macro and so are not seen by log users. /// /// Note that the [`level()`] and [`target()`] accessors are equivalent to /// `self.metadata().level()` and `self.metadata().target()` respectively. /// These methods are provided as a convenience for users of this structure. /// /// # Example /// /// The following example shows a simple logger that displays the level, /// module path, and message of any `Record` that is passed to it. /// /// ```edition2018 /// struct SimpleLogger; /// /// impl log::Log for SimpleLogger { /// fn enabled(&self, metadata: &log::Metadata) -> bool { /// true /// } /// /// fn log(&self, record: &log::Record) { /// if !self.enabled(record.metadata()) { /// return; /// } /// /// println!("{}:{} -- {}", /// record.level(), /// record.target(), /// record.args()); /// } /// fn flush(&self) {} /// } /// ``` /// /// [method.log]: trait.Log.html#tymethod.log /// [`Log`]: trait.Log.html /// [`log!`]: macro.log.html /// [`level()`]: struct.Record.html#method.level /// [`target()`]: struct.Record.html#method.target #[derive(Clone, Debug)] pub struct Record<'a> { metadata: Metadata<'a>, args: fmt::Arguments<'a>, module_path: Option>, file: Option>, line: Option, #[cfg(feature = "kv_unstable")] key_values: KeyValues<'a>, } // This wrapper type is only needed so we can // `#[derive(Debug)]` on `Record`. It also // provides a useful `Debug` implementation for // the underlying `Source`. #[cfg(feature = "kv_unstable")] #[derive(Clone)] struct KeyValues<'a>(&'a dyn kv::Source); #[cfg(feature = "kv_unstable")] impl<'a> fmt::Debug for KeyValues<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut visitor = f.debug_map(); self.0.visit(&mut visitor).map_err(|_| fmt::Error)?; visitor.finish() } } impl<'a> Record<'a> { /// Returns a new builder. #[inline] pub fn builder() -> RecordBuilder<'a> { RecordBuilder::new() } /// The message body. #[inline] pub fn args(&self) -> &fmt::Arguments<'a> { &self.args } /// Metadata about the log directive. #[inline] pub fn metadata(&self) -> &Metadata<'a> { &self.metadata } /// The verbosity level of the message. #[inline] pub fn level(&self) -> Level { self.metadata.level() } /// The name of the target of the directive. #[inline] pub fn target(&self) -> &'a str { self.metadata.target() } /// The module path of the message. #[inline] pub fn module_path(&self) -> Option<&'a str> { self.module_path.map(|s| s.get()) } /// The module path of the message, if it is a `'static` string. #[inline] pub fn module_path_static(&self) -> Option<&'static str> { match self.module_path { Some(MaybeStaticStr::Static(s)) => Some(s), _ => None, } } /// The source file containing the message. #[inline] pub fn file(&self) -> Option<&'a str> { self.file.map(|s| s.get()) } /// The module path of the message, if it is a `'static` string. #[inline] pub fn file_static(&self) -> Option<&'static str> { match self.file { Some(MaybeStaticStr::Static(s)) => Some(s), _ => None, } } /// The line containing the message. #[inline] pub fn line(&self) -> Option { self.line } /// The structued key-value pairs associated with the message. #[cfg(feature = "kv_unstable")] #[inline] pub fn key_values(&self) -> &dyn kv::Source { self.key_values.0 } /// Create a new [`RecordBuilder`](struct.RecordBuilder.html) based on this record. #[cfg(feature = "kv_unstable")] #[inline] pub fn to_builder(&self) -> RecordBuilder { RecordBuilder { record: Record { metadata: Metadata { level: self.metadata.level, target: self.metadata.target, }, args: self.args, module_path: self.module_path, file: self.file, line: self.line, key_values: self.key_values.clone(), }, } } } /// Builder for [`Record`](struct.Record.html). /// /// Typically should only be used by log library creators or for testing and "shim loggers". /// The `RecordBuilder` can set the different parameters of `Record` object, and returns /// the created object when `build` is called. /// /// # Examples /// /// /// ```edition2018 /// use log::{Level, Record}; /// /// let record = Record::builder() /// .args(format_args!("Error!")) /// .level(Level::Error) /// .target("myApp") /// .file(Some("server.rs")) /// .line(Some(144)) /// .module_path(Some("server")) /// .build(); /// ``` /// /// Alternatively, use [`MetadataBuilder`](struct.MetadataBuilder.html): /// /// ```edition2018 /// use log::{Record, Level, MetadataBuilder}; /// /// let error_metadata = MetadataBuilder::new() /// .target("myApp") /// .level(Level::Error) /// .build(); /// /// let record = Record::builder() /// .metadata(error_metadata) /// .args(format_args!("Error!")) /// .line(Some(433)) /// .file(Some("app.rs")) /// .module_path(Some("server")) /// .build(); /// ``` #[derive(Debug)] pub struct RecordBuilder<'a> { record: Record<'a>, } impl<'a> RecordBuilder<'a> { /// Construct new `RecordBuilder`. /// /// The default options are: /// /// - `args`: [`format_args!("")`] /// - `metadata`: [`Metadata::builder().build()`] /// - `module_path`: `None` /// - `file`: `None` /// - `line`: `None` /// /// [`format_args!("")`]: https://doc.rust-lang.org/std/macro.format_args.html /// [`Metadata::builder().build()`]: struct.MetadataBuilder.html#method.build #[inline] pub fn new() -> RecordBuilder<'a> { RecordBuilder { record: Record { args: format_args!(""), metadata: Metadata::builder().build(), module_path: None, file: None, line: None, #[cfg(feature = "kv_unstable")] key_values: KeyValues(&Option::None::<(kv::Key, kv::Value)>), }, } } /// Set [`args`](struct.Record.html#method.args). #[inline] pub fn args(&mut self, args: fmt::Arguments<'a>) -> &mut RecordBuilder<'a> { self.record.args = args; self } /// Set [`metadata`](struct.Record.html#method.metadata). Construct a `Metadata` object with [`MetadataBuilder`](struct.MetadataBuilder.html). #[inline] pub fn metadata(&mut self, metadata: Metadata<'a>) -> &mut RecordBuilder<'a> { self.record.metadata = metadata; self } /// Set [`Metadata::level`](struct.Metadata.html#method.level). #[inline] pub fn level(&mut self, level: Level) -> &mut RecordBuilder<'a> { self.record.metadata.level = level; self } /// Set [`Metadata::target`](struct.Metadata.html#method.target) #[inline] pub fn target(&mut self, target: &'a str) -> &mut RecordBuilder<'a> { self.record.metadata.target = target; self } /// Set [`module_path`](struct.Record.html#method.module_path) #[inline] pub fn module_path(&mut self, path: Option<&'a str>) -> &mut RecordBuilder<'a> { self.record.module_path = path.map(MaybeStaticStr::Borrowed); self } /// Set [`module_path`](struct.Record.html#method.module_path) to a `'static` string #[inline] pub fn module_path_static(&mut self, path: Option<&'static str>) -> &mut RecordBuilder<'a> { self.record.module_path = path.map(MaybeStaticStr::Static); self } /// Set [`file`](struct.Record.html#method.file) #[inline] pub fn file(&mut self, file: Option<&'a str>) -> &mut RecordBuilder<'a> { self.record.file = file.map(MaybeStaticStr::Borrowed); self } /// Set [`file`](struct.Record.html#method.file) to a `'static` string. #[inline] pub fn file_static(&mut self, file: Option<&'static str>) -> &mut RecordBuilder<'a> { self.record.file = file.map(MaybeStaticStr::Static); self } /// Set [`line`](struct.Record.html#method.line) #[inline] pub fn line(&mut self, line: Option) -> &mut RecordBuilder<'a> { self.record.line = line; self } /// Set [`key_values`](struct.Record.html#method.key_values) #[cfg(feature = "kv_unstable")] #[inline] pub fn key_values(&mut self, kvs: &'a dyn kv::Source) -> &mut RecordBuilder<'a> { self.record.key_values = KeyValues(kvs); self } /// Invoke the builder and return a `Record` #[inline] pub fn build(&self) -> Record<'a> { self.record.clone() } } /// Metadata about a log message. /// /// # Use /// /// `Metadata` structs are created when users of the library use /// logging macros. /// /// They are consumed by implementations of the `Log` trait in the /// `enabled` method. /// /// `Record`s use `Metadata` to determine the log message's severity /// and target. /// /// Users should use the `log_enabled!` macro in their code to avoid /// constructing expensive log messages. /// /// # Examples /// /// ```edition2018 /// use log::{Record, Level, Metadata}; /// /// struct MyLogger; /// /// impl log::Log for MyLogger { /// fn enabled(&self, metadata: &Metadata) -> bool { /// metadata.level() <= Level::Info /// } /// /// fn log(&self, record: &Record) { /// if self.enabled(record.metadata()) { /// println!("{} - {}", record.level(), record.args()); /// } /// } /// fn flush(&self) {} /// } /// /// # fn main(){} /// ``` #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub struct Metadata<'a> { level: Level, target: &'a str, } impl<'a> Metadata<'a> { /// Returns a new builder. #[inline] pub fn builder() -> MetadataBuilder<'a> { MetadataBuilder::new() } /// The verbosity level of the message. #[inline] pub fn level(&self) -> Level { self.level } /// The name of the target of the directive. #[inline] pub fn target(&self) -> &'a str { self.target } } /// Builder for [`Metadata`](struct.Metadata.html). /// /// Typically should only be used by log library creators or for testing and "shim loggers". /// The `MetadataBuilder` can set the different parameters of a `Metadata` object, and returns /// the created object when `build` is called. /// /// # Example /// /// ```edition2018 /// let target = "myApp"; /// use log::{Level, MetadataBuilder}; /// let metadata = MetadataBuilder::new() /// .level(Level::Debug) /// .target(target) /// .build(); /// ``` #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub struct MetadataBuilder<'a> { metadata: Metadata<'a>, } impl<'a> MetadataBuilder<'a> { /// Construct a new `MetadataBuilder`. /// /// The default options are: /// /// - `level`: `Level::Info` /// - `target`: `""` #[inline] pub fn new() -> MetadataBuilder<'a> { MetadataBuilder { metadata: Metadata { level: Level::Info, target: "", }, } } /// Setter for [`level`](struct.Metadata.html#method.level). #[inline] pub fn level(&mut self, arg: Level) -> &mut MetadataBuilder<'a> { self.metadata.level = arg; self } /// Setter for [`target`](struct.Metadata.html#method.target). #[inline] pub fn target(&mut self, target: &'a str) -> &mut MetadataBuilder<'a> { self.metadata.target = target; self } /// Returns a `Metadata` object. #[inline] pub fn build(&self) -> Metadata<'a> { self.metadata.clone() } } /// A trait encapsulating the operations required of a logger. pub trait Log: Sync + Send { /// Determines if a log message with the specified metadata would be /// logged. /// /// This is used by the `log_enabled!` macro to allow callers to avoid /// expensive computation of log message arguments if the message would be /// discarded anyway. fn enabled(&self, metadata: &Metadata) -> bool; /// Logs the `Record`. /// /// Note that `enabled` is *not* necessarily called before this method. /// Implementations of `log` should perform all necessary filtering /// internally. fn log(&self, record: &Record); /// Flushes any buffered records. fn flush(&self); } // Just used as a dummy initial value for LOGGER struct NopLogger; impl Log for NopLogger { fn enabled(&self, _: &Metadata) -> bool { false } fn log(&self, _: &Record) {} fn flush(&self) {} } /// Sets the global maximum log level. /// /// Generally, this should only be called by the active logging implementation. #[inline] pub fn set_max_level(level: LevelFilter) { MAX_LOG_LEVEL_FILTER.store(level as usize, Ordering::SeqCst) } /// Returns the current maximum log level. /// /// The [`log!`], [`error!`], [`warn!`], [`info!`], [`debug!`], and [`trace!`] macros check /// this value and discard any message logged at a higher level. The maximum /// log level is set by the [`set_max_level`] function. /// /// [`log!`]: macro.log.html /// [`error!`]: macro.error.html /// [`warn!`]: macro.warn.html /// [`info!`]: macro.info.html /// [`debug!`]: macro.debug.html /// [`trace!`]: macro.trace.html /// [`set_max_level`]: fn.set_max_level.html #[inline(always)] pub fn max_level() -> LevelFilter { // Since `LevelFilter` is `repr(usize)`, // this transmute is sound if and only if `MAX_LOG_LEVEL_FILTER` // is set to a usize that is a valid discriminant for `LevelFilter`. // Since `MAX_LOG_LEVEL_FILTER` is private, the only time it's set // is by `set_max_level` above, i.e. by casting a `LevelFilter` to `usize`. // So any usize stored in `MAX_LOG_LEVEL_FILTER` is a valid discriminant. unsafe { mem::transmute(MAX_LOG_LEVEL_FILTER.load(Ordering::Relaxed)) } } /// Sets the global logger to a `Box`. /// /// This is a simple convenience wrapper over `set_logger`, which takes a /// `Box` rather than a `&'static Log`. See the documentation for /// [`set_logger`] for more details. /// /// Requires the `std` feature. /// /// # Errors /// /// An error is returned if a logger has already been set. /// /// [`set_logger`]: fn.set_logger.html #[cfg(all(feature = "std", atomic_cas))] pub fn set_boxed_logger(logger: Box) -> Result<(), SetLoggerError> { set_logger_inner(|| Box::leak(logger)) } /// Sets the global logger to a `&'static Log`. /// /// This function may only be called once in the lifetime of a program. Any log /// events that occur before the call to `set_logger` completes will be ignored. /// /// This function does not typically need to be called manually. Logger /// implementations should provide an initialization method that installs the /// logger internally. /// /// # Availability /// /// This method is available even when the `std` feature is disabled. However, /// it is currently unavailable on `thumbv6` targets, which lack support for /// some atomic operations which are used by this function. Even on those /// targets, [`set_logger_racy`] will be available. /// /// # Errors /// /// An error is returned if a logger has already been set. /// /// # Examples /// /// ```edition2018 /// use log::{error, info, warn, Record, Level, Metadata, LevelFilter}; /// /// static MY_LOGGER: MyLogger = MyLogger; /// /// struct MyLogger; /// /// impl log::Log for MyLogger { /// fn enabled(&self, metadata: &Metadata) -> bool { /// metadata.level() <= Level::Info /// } /// /// fn log(&self, record: &Record) { /// if self.enabled(record.metadata()) { /// println!("{} - {}", record.level(), record.args()); /// } /// } /// fn flush(&self) {} /// } /// /// # fn main(){ /// log::set_logger(&MY_LOGGER).unwrap(); /// log::set_max_level(LevelFilter::Info); /// /// info!("hello log"); /// warn!("warning"); /// error!("oops"); /// # } /// ``` /// /// [`set_logger_racy`]: fn.set_logger_racy.html #[cfg(atomic_cas)] pub fn set_logger(logger: &'static dyn Log) -> Result<(), SetLoggerError> { set_logger_inner(|| logger) } #[cfg(atomic_cas)] fn set_logger_inner(make_logger: F) -> Result<(), SetLoggerError> where F: FnOnce() -> &'static dyn Log, { match STATE.compare_and_swap(UNINITIALIZED, INITIALIZING, Ordering::SeqCst) { UNINITIALIZED => { unsafe { LOGGER = make_logger(); } STATE.store(INITIALIZED, Ordering::SeqCst); Ok(()) } INITIALIZING => { while STATE.load(Ordering::SeqCst) == INITIALIZING { std::sync::atomic::spin_loop_hint(); } Err(SetLoggerError(())) } _ => Err(SetLoggerError(())), } } /// A thread-unsafe version of [`set_logger`]. /// /// This function is available on all platforms, even those that do not have /// support for atomics that is needed by [`set_logger`]. /// /// In almost all cases, [`set_logger`] should be preferred. /// /// # Safety /// /// This function is only safe to call when no other logger initialization /// function is called while this function still executes. /// /// This can be upheld by (for example) making sure that **there are no other /// threads**, and (on embedded) that **interrupts are disabled**. /// /// It is safe to use other logging functions while this function runs /// (including all logging macros). /// /// [`set_logger`]: fn.set_logger.html pub unsafe fn set_logger_racy(logger: &'static dyn Log) -> Result<(), SetLoggerError> { match STATE.load(Ordering::SeqCst) { UNINITIALIZED => { LOGGER = logger; STATE.store(INITIALIZED, Ordering::SeqCst); Ok(()) } INITIALIZING => { // This is just plain UB, since we were racing another initialization function unreachable!("set_logger_racy must not be used with other initialization functions") } _ => Err(SetLoggerError(())), } } /// The type returned by [`set_logger`] if [`set_logger`] has already been called. /// /// [`set_logger`]: fn.set_logger.html #[allow(missing_copy_implementations)] #[derive(Debug)] pub struct SetLoggerError(()); impl fmt::Display for SetLoggerError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(SET_LOGGER_ERROR) } } // The Error trait is not available in libcore #[cfg(feature = "std")] impl error::Error for SetLoggerError {} /// The type returned by [`from_str`] when the string doesn't match any of the log levels. /// /// [`from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str #[allow(missing_copy_implementations)] #[derive(Debug, PartialEq)] pub struct ParseLevelError(()); impl fmt::Display for ParseLevelError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(LEVEL_PARSE_ERROR) } } // The Error trait is not available in libcore #[cfg(feature = "std")] impl error::Error for ParseLevelError {} /// Returns a reference to the logger. /// /// If a logger has not been set, a no-op implementation is returned. pub fn logger() -> &'static dyn Log { if STATE.load(Ordering::SeqCst) != INITIALIZED { static NOP: NopLogger = NopLogger; &NOP } else { unsafe { LOGGER } } } // WARNING: this is not part of the crate's public API and is subject to change at any time #[doc(hidden)] pub fn __private_api_log( args: fmt::Arguments, level: Level, &(target, module_path, file, line): &(&str, &'static str, &'static str, u32), ) { logger().log( &Record::builder() .args(args) .level(level) .target(target) .module_path_static(Some(module_path)) .file_static(Some(file)) .line(Some(line)) .build(), ); } // WARNING: this is not part of the crate's public API and is subject to change at any time #[doc(hidden)] pub fn __private_api_log_lit( message: &str, level: Level, &(target, module_path, file, line): &(&str, &'static str, &'static str, u32), ) { logger().log( &Record::builder() .args(format_args!("{}", message)) .level(level) .target(target) .module_path_static(Some(module_path)) .file_static(Some(file)) .line(Some(line)) .build(), ); } // WARNING: this is not part of the crate's public API and is subject to change at any time #[doc(hidden)] pub fn __private_api_enabled(level: Level, target: &str) -> bool { logger().enabled(&Metadata::builder().level(level).target(target).build()) } /// The statically resolved maximum log level. /// /// See the crate level documentation for information on how to configure this. /// /// This value is checked by the log macros, but not by the `Log`ger returned by /// the [`logger`] function. Code that manually calls functions on that value /// should compare the level against this value. /// /// [`logger`]: fn.logger.html pub const STATIC_MAX_LEVEL: LevelFilter = MAX_LEVEL_INNER; cfg_if! { if #[cfg(all(not(debug_assertions), feature = "release_max_level_off"))] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Off; } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_error"))] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Error; } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_warn"))] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Warn; } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_info"))] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Info; } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_debug"))] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Debug; } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_trace"))] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Trace; } else if #[cfg(feature = "max_level_off")] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Off; } else if #[cfg(feature = "max_level_error")] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Error; } else if #[cfg(feature = "max_level_warn")] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Warn; } else if #[cfg(feature = "max_level_info")] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Info; } else if #[cfg(feature = "max_level_debug")] { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Debug; } else { const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Trace; } } #[cfg(test)] mod tests { extern crate std; use super::{Level, LevelFilter, ParseLevelError}; use tests::std::string::ToString; #[test] fn test_levelfilter_from_str() { let tests = [ ("off", Ok(LevelFilter::Off)), ("error", Ok(LevelFilter::Error)), ("warn", Ok(LevelFilter::Warn)), ("info", Ok(LevelFilter::Info)), ("debug", Ok(LevelFilter::Debug)), ("trace", Ok(LevelFilter::Trace)), ("OFF", Ok(LevelFilter::Off)), ("ERROR", Ok(LevelFilter::Error)), ("WARN", Ok(LevelFilter::Warn)), ("INFO", Ok(LevelFilter::Info)), ("DEBUG", Ok(LevelFilter::Debug)), ("TRACE", Ok(LevelFilter::Trace)), ("asdf", Err(ParseLevelError(()))), ]; for &(s, ref expected) in &tests { assert_eq!(expected, &s.parse()); } } #[test] fn test_level_from_str() { let tests = [ ("OFF", Err(ParseLevelError(()))), ("error", Ok(Level::Error)), ("warn", Ok(Level::Warn)), ("info", Ok(Level::Info)), ("debug", Ok(Level::Debug)), ("trace", Ok(Level::Trace)), ("ERROR", Ok(Level::Error)), ("WARN", Ok(Level::Warn)), ("INFO", Ok(Level::Info)), ("DEBUG", Ok(Level::Debug)), ("TRACE", Ok(Level::Trace)), ("asdf", Err(ParseLevelError(()))), ]; for &(s, ref expected) in &tests { assert_eq!(expected, &s.parse()); } } #[test] fn test_level_show() { assert_eq!("INFO", Level::Info.to_string()); assert_eq!("ERROR", Level::Error.to_string()); } #[test] fn test_levelfilter_show() { assert_eq!("OFF", LevelFilter::Off.to_string()); assert_eq!("ERROR", LevelFilter::Error.to_string()); } #[test] fn test_cross_cmp() { assert!(Level::Debug > LevelFilter::Error); assert!(LevelFilter::Warn < Level::Trace); assert!(LevelFilter::Off < Level::Error); } #[test] fn test_cross_eq() { assert!(Level::Error == LevelFilter::Error); assert!(LevelFilter::Off != Level::Error); assert!(Level::Trace == LevelFilter::Trace); } #[test] fn test_to_level() { assert_eq!(Some(Level::Error), LevelFilter::Error.to_level()); assert_eq!(None, LevelFilter::Off.to_level()); assert_eq!(Some(Level::Debug), LevelFilter::Debug.to_level()); } #[test] fn test_to_level_filter() { assert_eq!(LevelFilter::Error, Level::Error.to_level_filter()); assert_eq!(LevelFilter::Trace, Level::Trace.to_level_filter()); } #[test] #[cfg(feature = "std")] fn test_error_trait() { use super::SetLoggerError; let e = SetLoggerError(()); assert_eq!( &e.to_string(), "attempted to set a logger after the logging system \ was already initialized" ); } #[test] fn test_metadata_builder() { use super::MetadataBuilder; let target = "myApp"; let metadata_test = MetadataBuilder::new() .level(Level::Debug) .target(target) .build(); assert_eq!(metadata_test.level(), Level::Debug); assert_eq!(metadata_test.target(), "myApp"); } #[test] fn test_metadata_convenience_builder() { use super::Metadata; let target = "myApp"; let metadata_test = Metadata::builder() .level(Level::Debug) .target(target) .build(); assert_eq!(metadata_test.level(), Level::Debug); assert_eq!(metadata_test.target(), "myApp"); } #[test] fn test_record_builder() { use super::{MetadataBuilder, RecordBuilder}; let target = "myApp"; let metadata = MetadataBuilder::new().target(target).build(); let fmt_args = format_args!("hello"); let record_test = RecordBuilder::new() .args(fmt_args) .metadata(metadata) .module_path(Some("foo")) .file(Some("bar")) .line(Some(30)) .build(); assert_eq!(record_test.metadata().target(), "myApp"); assert_eq!(record_test.module_path(), Some("foo")); assert_eq!(record_test.file(), Some("bar")); assert_eq!(record_test.line(), Some(30)); } #[test] fn test_record_convenience_builder() { use super::{Metadata, Record}; let target = "myApp"; let metadata = Metadata::builder().target(target).build(); let fmt_args = format_args!("hello"); let record_test = Record::builder() .args(fmt_args) .metadata(metadata) .module_path(Some("foo")) .file(Some("bar")) .line(Some(30)) .build(); assert_eq!(record_test.target(), "myApp"); assert_eq!(record_test.module_path(), Some("foo")); assert_eq!(record_test.file(), Some("bar")); assert_eq!(record_test.line(), Some(30)); } #[test] fn test_record_complete_builder() { use super::{Level, Record}; let target = "myApp"; let record_test = Record::builder() .module_path(Some("foo")) .file(Some("bar")) .line(Some(30)) .target(target) .level(Level::Error) .build(); assert_eq!(record_test.target(), "myApp"); assert_eq!(record_test.level(), Level::Error); assert_eq!(record_test.module_path(), Some("foo")); assert_eq!(record_test.file(), Some("bar")); assert_eq!(record_test.line(), Some(30)); } #[test] #[cfg(feature = "kv_unstable")] fn test_record_key_values_builder() { use super::Record; use kv::{self, Visitor}; struct TestVisitor { seen_pairs: usize, } impl<'kvs> Visitor<'kvs> for TestVisitor { fn visit_pair( &mut self, _: kv::Key<'kvs>, _: kv::Value<'kvs>, ) -> Result<(), kv::Error> { self.seen_pairs += 1; Ok(()) } } let kvs: &[(&str, i32)] = &[("a", 1), ("b", 2)]; let record_test = Record::builder().key_values(&kvs).build(); let mut visitor = TestVisitor { seen_pairs: 0 }; record_test.key_values().visit(&mut visitor).unwrap(); assert_eq!(2, visitor.seen_pairs); } #[test] #[cfg(feature = "kv_unstable")] fn test_record_key_values_get_coerce() { use super::Record; let kvs: &[(&str, &str)] = &[("a", "1"), ("b", "2")]; let record = Record::builder().key_values(&kvs).build(); assert_eq!( "2", record .key_values() .get("b".into()) .expect("missing key") .to_borrowed_str() .expect("invalid value") ); } } log-0.4.11/src/macros.rs000064400000000000000000000165771361466760600131640ustar 00000000000000// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// The standard logging macro. /// /// This macro will generically log with the specified `Level` and `format!` /// based argument list. /// /// # Examples /// /// ```edition2018 /// use log::{log, Level}; /// /// # fn main() { /// let data = (42, "Forty-two"); /// let private_data = "private"; /// /// log!(Level::Error, "Received errors: {}, {}", data.0, data.1); /// log!(target: "app_events", Level::Warn, "App warning: {}, {}, {}", /// data.0, data.1, private_data); /// # } /// ``` #[macro_export(local_inner_macros)] macro_rules! log { (target: $target:expr, $lvl:expr, $message:expr) => ({ let lvl = $lvl; if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() { // ensure that $message is a valid format string literal let _ = __log_format_args!($message); $crate::__private_api_log_lit( $message, lvl, &($target, __log_module_path!(), __log_file!(), __log_line!()), ); } }); (target: $target:expr, $lvl:expr, $($arg:tt)+) => ({ let lvl = $lvl; if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() { $crate::__private_api_log( __log_format_args!($($arg)+), lvl, &($target, __log_module_path!(), __log_file!(), __log_line!()), ); } }); ($lvl:expr, $($arg:tt)+) => (log!(target: __log_module_path!(), $lvl, $($arg)+)) } /// Logs a message at the error level. /// /// # Examples /// /// ```edition2018 /// use log::error; /// /// # fn main() { /// let (err_info, port) = ("No connection", 22); /// /// error!("Error: {} on port {}", err_info, port); /// error!(target: "app_events", "App Error: {}, Port: {}", err_info, 22); /// # } /// ``` #[macro_export(local_inner_macros)] macro_rules! error { (target: $target:expr, $($arg:tt)+) => ( log!(target: $target, $crate::Level::Error, $($arg)+); ); ($($arg:tt)+) => ( log!($crate::Level::Error, $($arg)+); ) } /// Logs a message at the warn level. /// /// # Examples /// /// ```edition2018 /// use log::warn; /// /// # fn main() { /// let warn_description = "Invalid Input"; /// /// warn!("Warning! {}!", warn_description); /// warn!(target: "input_events", "App received warning: {}", warn_description); /// # } /// ``` #[macro_export(local_inner_macros)] macro_rules! warn { (target: $target:expr, $($arg:tt)+) => ( log!(target: $target, $crate::Level::Warn, $($arg)+); ); ($($arg:tt)+) => ( log!($crate::Level::Warn, $($arg)+); ) } /// Logs a message at the info level. /// /// # Examples /// /// ```edition2018 /// use log::info; /// /// # fn main() { /// # struct Connection { port: u32, speed: f32 } /// let conn_info = Connection { port: 40, speed: 3.20 }; /// /// info!("Connected to port {} at {} Mb/s", conn_info.port, conn_info.speed); /// info!(target: "connection_events", "Successfull connection, port: {}, speed: {}", /// conn_info.port, conn_info.speed); /// # } /// ``` #[macro_export(local_inner_macros)] macro_rules! info { (target: $target:expr, $($arg:tt)+) => ( log!(target: $target, $crate::Level::Info, $($arg)+); ); ($($arg:tt)+) => ( log!($crate::Level::Info, $($arg)+); ) } /// Logs a message at the debug level. /// /// # Examples /// /// ```edition2018 /// use log::debug; /// /// # fn main() { /// # struct Position { x: f32, y: f32 } /// let pos = Position { x: 3.234, y: -1.223 }; /// /// debug!("New position: x: {}, y: {}", pos.x, pos.y); /// debug!(target: "app_events", "New position: x: {}, y: {}", pos.x, pos.y); /// # } /// ``` #[macro_export(local_inner_macros)] macro_rules! debug { (target: $target:expr, $($arg:tt)+) => ( log!(target: $target, $crate::Level::Debug, $($arg)+); ); ($($arg:tt)+) => ( log!($crate::Level::Debug, $($arg)+); ) } /// Logs a message at the trace level. /// /// # Examples /// /// ```edition2018 /// use log::trace; /// /// # fn main() { /// # struct Position { x: f32, y: f32 } /// let pos = Position { x: 3.234, y: -1.223 }; /// /// trace!("Position is: x: {}, y: {}", pos.x, pos.y); /// trace!(target: "app_events", "x is {} and y is {}", /// if pos.x >= 0.0 { "positive" } else { "negative" }, /// if pos.y >= 0.0 { "positive" } else { "negative" }); /// # } /// ``` #[macro_export(local_inner_macros)] macro_rules! trace { (target: $target:expr, $($arg:tt)+) => ( log!(target: $target, $crate::Level::Trace, $($arg)+); ); ($($arg:tt)+) => ( log!($crate::Level::Trace, $($arg)+); ) } /// Determines if a message logged at the specified level in that module will /// be logged. /// /// This can be used to avoid expensive computation of log message arguments if /// the message would be ignored anyway. /// /// # Examples /// /// ```edition2018 /// use log::Level::Debug; /// use log::{debug, log_enabled}; /// /// # fn foo() { /// if log_enabled!(Debug) { /// let data = expensive_call(); /// debug!("expensive debug data: {} {}", data.x, data.y); /// } /// if log_enabled!(target: "Global", Debug) { /// let data = expensive_call(); /// debug!(target: "Global", "expensive debug data: {} {}", data.x, data.y); /// } /// # } /// # struct Data { x: u32, y: u32 } /// # fn expensive_call() -> Data { Data { x: 0, y: 0 } } /// # fn main() {} /// ``` #[macro_export(local_inner_macros)] macro_rules! log_enabled { (target: $target:expr, $lvl:expr) => {{ let lvl = $lvl; lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() && $crate::__private_api_enabled(lvl, $target) }}; ($lvl:expr) => { log_enabled!(target: __log_module_path!(), $lvl) }; } // The log macro above cannot invoke format_args directly because it uses // local_inner_macros. A format_args invocation there would resolve to // $crate::format_args which does not exist. Instead invoke format_args here // outside of local_inner_macros so that it resolves (probably) to // core::format_args or std::format_args. Same for the several macros that // follow. // // This is a workaround until we drop support for pre-1.30 compilers. At that // point we can remove use of local_inner_macros, use $crate:: when invoking // local macros, and invoke format_args directly. #[doc(hidden)] #[macro_export] macro_rules! __log_format_args { ($($args:tt)*) => { format_args!($($args)*) }; } #[doc(hidden)] #[macro_export] macro_rules! __log_module_path { () => { module_path!() }; } #[doc(hidden)] #[macro_export] macro_rules! __log_file { () => { file!() }; } #[doc(hidden)] #[macro_export] macro_rules! __log_line { () => { line!() }; } log-0.4.11/src/serde.rs000064400000000000000000000252041346047754400127640ustar 00000000000000#![cfg(feature = "serde")] extern crate serde; use self::serde::de::{ Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error, Unexpected, VariantAccess, Visitor, }; use self::serde::ser::{Serialize, Serializer}; use {Level, LevelFilter, LOG_LEVEL_NAMES}; use std::fmt; use std::str::{self, FromStr}; // The Deserialize impls are handwritten to be case insensitive using FromStr. impl Serialize for Level { fn serialize(&self, serializer: S) -> Result where S: Serializer, { match *self { Level::Error => serializer.serialize_unit_variant("Level", 0, "ERROR"), Level::Warn => serializer.serialize_unit_variant("Level", 1, "WARN"), Level::Info => serializer.serialize_unit_variant("Level", 2, "INFO"), Level::Debug => serializer.serialize_unit_variant("Level", 3, "DEBUG"), Level::Trace => serializer.serialize_unit_variant("Level", 4, "TRACE"), } } } impl<'de> Deserialize<'de> for Level { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct LevelIdentifier; impl<'de> Visitor<'de> for LevelIdentifier { type Value = Level; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("log level") } fn visit_str(self, s: &str) -> Result where E: Error, { // Case insensitive. FromStr::from_str(s).map_err(|_| Error::unknown_variant(s, &LOG_LEVEL_NAMES[1..])) } fn visit_bytes(self, value: &[u8]) -> Result where E: Error, { let variant = str::from_utf8(value) .map_err(|_| Error::invalid_value(Unexpected::Bytes(value), &self))?; self.visit_str(variant) } } impl<'de> DeserializeSeed<'de> for LevelIdentifier { type Value = Level; fn deserialize(self, deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_identifier(LevelIdentifier) } } struct LevelEnum; impl<'de> Visitor<'de> for LevelEnum { type Value = Level; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("log level") } fn visit_enum(self, value: A) -> Result where A: EnumAccess<'de>, { let (level, variant) = value.variant_seed(LevelIdentifier)?; // Every variant is a unit variant. variant.unit_variant()?; Ok(level) } } deserializer.deserialize_enum("Level", &LOG_LEVEL_NAMES[1..], LevelEnum) } } impl Serialize for LevelFilter { fn serialize(&self, serializer: S) -> Result where S: Serializer, { match *self { LevelFilter::Off => serializer.serialize_unit_variant("LevelFilter", 0, "OFF"), LevelFilter::Error => serializer.serialize_unit_variant("LevelFilter", 1, "ERROR"), LevelFilter::Warn => serializer.serialize_unit_variant("LevelFilter", 2, "WARN"), LevelFilter::Info => serializer.serialize_unit_variant("LevelFilter", 3, "INFO"), LevelFilter::Debug => serializer.serialize_unit_variant("LevelFilter", 4, "DEBUG"), LevelFilter::Trace => serializer.serialize_unit_variant("LevelFilter", 5, "TRACE"), } } } impl<'de> Deserialize<'de> for LevelFilter { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct LevelFilterIdentifier; impl<'de> Visitor<'de> for LevelFilterIdentifier { type Value = LevelFilter; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("log level filter") } fn visit_str(self, s: &str) -> Result where E: Error, { // Case insensitive. FromStr::from_str(s).map_err(|_| Error::unknown_variant(s, &LOG_LEVEL_NAMES)) } fn visit_bytes(self, value: &[u8]) -> Result where E: Error, { let variant = str::from_utf8(value) .map_err(|_| Error::invalid_value(Unexpected::Bytes(value), &self))?; self.visit_str(variant) } } impl<'de> DeserializeSeed<'de> for LevelFilterIdentifier { type Value = LevelFilter; fn deserialize(self, deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_identifier(LevelFilterIdentifier) } } struct LevelFilterEnum; impl<'de> Visitor<'de> for LevelFilterEnum { type Value = LevelFilter; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("log level filter") } fn visit_enum(self, value: A) -> Result where A: EnumAccess<'de>, { let (level_filter, variant) = value.variant_seed(LevelFilterIdentifier)?; // Every variant is a unit variant. variant.unit_variant()?; Ok(level_filter) } } deserializer.deserialize_enum("LevelFilter", &LOG_LEVEL_NAMES, LevelFilterEnum) } } #[cfg(test)] mod tests { extern crate serde_test; use self::serde_test::{assert_de_tokens, assert_de_tokens_error, assert_tokens, Token}; use {Level, LevelFilter}; fn level_token(variant: &'static str) -> Token { Token::UnitVariant { name: "Level", variant: variant, } } fn level_bytes_tokens(variant: &'static [u8]) -> [Token; 3] { [ Token::Enum { name: "Level" }, Token::Bytes(variant), Token::Unit, ] } fn level_filter_token(variant: &'static str) -> Token { Token::UnitVariant { name: "LevelFilter", variant: variant, } } fn level_filter_bytes_tokens(variant: &'static [u8]) -> [Token; 3] { [ Token::Enum { name: "LevelFilter", }, Token::Bytes(variant), Token::Unit, ] } #[test] fn test_level_ser_de() { let cases = [ (Level::Error, [level_token("ERROR")]), (Level::Warn, [level_token("WARN")]), (Level::Info, [level_token("INFO")]), (Level::Debug, [level_token("DEBUG")]), (Level::Trace, [level_token("TRACE")]), ]; for &(s, expected) in &cases { assert_tokens(&s, &expected); } } #[test] fn test_level_case_insensitive() { let cases = [ (Level::Error, [level_token("error")]), (Level::Warn, [level_token("warn")]), (Level::Info, [level_token("info")]), (Level::Debug, [level_token("debug")]), (Level::Trace, [level_token("trace")]), ]; for &(s, expected) in &cases { assert_de_tokens(&s, &expected); } } #[test] fn test_level_de_bytes() { let cases = [ (Level::Error, level_bytes_tokens(b"ERROR")), (Level::Warn, level_bytes_tokens(b"WARN")), (Level::Info, level_bytes_tokens(b"INFO")), (Level::Debug, level_bytes_tokens(b"DEBUG")), (Level::Trace, level_bytes_tokens(b"TRACE")), ]; for &(value, tokens) in &cases { assert_de_tokens(&value, &tokens); } } #[test] fn test_level_de_error() { let msg = "unknown variant `errorx`, expected one of \ `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`"; assert_de_tokens_error::(&[level_token("errorx")], msg); } #[test] fn test_level_filter_ser_de() { let cases = [ (LevelFilter::Off, [level_filter_token("OFF")]), (LevelFilter::Error, [level_filter_token("ERROR")]), (LevelFilter::Warn, [level_filter_token("WARN")]), (LevelFilter::Info, [level_filter_token("INFO")]), (LevelFilter::Debug, [level_filter_token("DEBUG")]), (LevelFilter::Trace, [level_filter_token("TRACE")]), ]; for &(s, expected) in &cases { assert_tokens(&s, &expected); } } #[test] fn test_level_filter_case_insensitive() { let cases = [ (LevelFilter::Off, [level_filter_token("off")]), (LevelFilter::Error, [level_filter_token("error")]), (LevelFilter::Warn, [level_filter_token("warn")]), (LevelFilter::Info, [level_filter_token("info")]), (LevelFilter::Debug, [level_filter_token("debug")]), (LevelFilter::Trace, [level_filter_token("trace")]), ]; for &(s, expected) in &cases { assert_de_tokens(&s, &expected); } } #[test] fn test_level_filter_de_bytes() { let cases = [ (LevelFilter::Off, level_filter_bytes_tokens(b"OFF")), (LevelFilter::Error, level_filter_bytes_tokens(b"ERROR")), (LevelFilter::Warn, level_filter_bytes_tokens(b"WARN")), (LevelFilter::Info, level_filter_bytes_tokens(b"INFO")), (LevelFilter::Debug, level_filter_bytes_tokens(b"DEBUG")), (LevelFilter::Trace, level_filter_bytes_tokens(b"TRACE")), ]; for &(value, tokens) in &cases { assert_de_tokens(&value, &tokens); } } #[test] fn test_level_filter_de_error() { let msg = "unknown variant `errorx`, expected one of \ `OFF`, `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`"; assert_de_tokens_error::(&[level_filter_token("errorx")], msg); } } log-0.4.11/tests/filters.rs000064400000000000000000000032521361466760600137050ustar 00000000000000#[macro_use] extern crate log; use log::{Level, LevelFilter, Log, Metadata, Record}; use std::sync::{Arc, Mutex}; #[cfg(feature = "std")] use log::set_boxed_logger; #[cfg(not(feature = "std"))] fn set_boxed_logger(logger: Box) -> Result<(), log::SetLoggerError> { log::set_logger(Box::leak(logger)) } struct State { last_log: Mutex>, } struct Logger(Arc); impl Log for Logger { fn enabled(&self, _: &Metadata) -> bool { true } fn log(&self, record: &Record) { *self.0.last_log.lock().unwrap() = Some(record.level()); } fn flush(&self) {} } fn main() { let me = Arc::new(State { last_log: Mutex::new(None), }); let a = me.clone(); set_boxed_logger(Box::new(Logger(me))).unwrap(); test(&a, LevelFilter::Off); test(&a, LevelFilter::Error); test(&a, LevelFilter::Warn); test(&a, LevelFilter::Info); test(&a, LevelFilter::Debug); test(&a, LevelFilter::Trace); } fn test(a: &State, filter: LevelFilter) { log::set_max_level(filter); error!(""); last(&a, t(Level::Error, filter)); warn!(""); last(&a, t(Level::Warn, filter)); info!(""); last(&a, t(Level::Info, filter)); debug!(""); last(&a, t(Level::Debug, filter)); trace!(""); last(&a, t(Level::Trace, filter)); fn t(lvl: Level, filter: LevelFilter) -> Option { if lvl <= filter { Some(lvl) } else { None } } } fn last(state: &State, expected: Option) { let lvl = state.last_log.lock().unwrap().take(); assert_eq!(lvl, expected); } log-0.4.11/tests/macros.rs000064400000000000000000000011361361466760600135200ustar 00000000000000#[macro_use] extern crate log; #[test] fn base() { info!("hello"); info!("hello",); } #[test] fn base_expr_context() { let _ = info!("hello"); } #[test] fn with_args() { info!("hello {}", "cats"); info!("hello {}", "cats",); info!("hello {}", "cats",); } #[test] fn with_args_expr_context() { match "cats" { cats => info!("hello {}", cats), }; } #[test] fn with_named_args() { let cats = "cats"; info!("hello {cats}", cats = cats); info!("hello {cats}", cats = cats,); info!("hello {cats}", cats = cats,); } log-0.4.11/triagebot.toml000064400000000000000000000000121366165217300133640ustar 00000000000000[assign]