repo
stringclasses 1
value | pull_number
int64 70
619
| instance_id
stringlengths 17
18
| issue_numbers
listlengths 1
1
| base_commit
stringlengths 40
40
| patch
stringlengths 341
89.2k
| test_patch
stringlengths 548
5.67k
| problem_statement
stringlengths 67
4.82k
| hints_text
stringlengths 0
4.86k
| created_at
stringlengths 20
20
| version
stringclasses 2
values | environment_setup_commit
stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
rust-lang/log
| 619
|
rust-lang__log-619
|
[
"601"
] |
06c306fa8f4d41a722f8759f03effd4185eee3ee
|
diff --git a/Cargo.toml b/Cargo.toml
index c0ea52a77..72fcdb0e4 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -20,8 +20,8 @@ edition = "2021"
features = ["std", "serde", "kv_std", "kv_sval", "kv_serde"]
[[test]]
-name = "filters"
-path = "tests/filters.rs"
+name = "integration"
+path = "tests/integration.rs"
harness = false
[[test]]
|
diff --git a/tests/filters.rs b/tests/integration.rs
similarity index 56%
rename from tests/filters.rs
rename to tests/integration.rs
index 3e0810d07..7bf456e02 100644
--- a/tests/filters.rs
+++ b/tests/integration.rs
@@ -12,7 +12,8 @@ fn set_boxed_logger(logger: Box<dyn Log>) -> Result<(), log::SetLoggerError> {
}
struct State {
- last_log: Mutex<Option<Level>>,
+ last_log_level: Mutex<Option<Level>>,
+ last_log_location: Mutex<Option<u32>>,
}
struct Logger(Arc<State>);
@@ -23,11 +24,11 @@ impl Log for Logger {
}
fn log(&self, record: &Record) {
- *self.0.last_log.lock().unwrap() = Some(record.level());
+ *self.0.last_log_level.lock().unwrap() = Some(record.level());
+ *self.0.last_log_location.lock().unwrap() = record.line();
}
fn flush(&self) {}
}
-
#[cfg_attr(lib_build, test)]
fn main() {
// These tests don't really make sense when static
@@ -48,21 +49,25 @@ fn main() {
)))]
{
let me = Arc::new(State {
- last_log: Mutex::new(None),
+ last_log_level: Mutex::new(None),
+ last_log_location: 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);
+ test_filter(&a, LevelFilter::Off);
+ test_filter(&a, LevelFilter::Error);
+ test_filter(&a, LevelFilter::Warn);
+ test_filter(&a, LevelFilter::Info);
+ test_filter(&a, LevelFilter::Debug);
+ test_filter(&a, LevelFilter::Trace);
+
+ test_line_numbers(&a);
}
}
-fn test(a: &State, filter: LevelFilter) {
+fn test_filter(a: &State, filter: LevelFilter) {
+ // tests to ensure logs with a level beneath 'max_level' are filtered out
log::set_max_level(filter);
error!("");
last(a, t(Level::Error, filter));
@@ -82,9 +87,22 @@ fn test(a: &State, filter: LevelFilter) {
None
}
}
+ fn last(state: &State, expected: Option<Level>) {
+ let lvl = state.last_log_level.lock().unwrap().take();
+ assert_eq!(lvl, expected);
+ }
}
-fn last(state: &State, expected: Option<Level>) {
- let lvl = state.last_log.lock().unwrap().take();
- assert_eq!(lvl, expected);
+fn test_line_numbers(state: &State) {
+ log::set_max_level(LevelFilter::Trace);
+
+ info!(""); // ensure check_line function follows log macro
+ check_log_location(&state);
+
+ #[track_caller]
+ fn check_log_location(state: &State) {
+ let location = std::panic::Location::caller().line(); // get function calling location
+ let line_number = state.last_log_location.lock().unwrap().take().unwrap(); // get location of most recent log
+ assert_eq!(line_number, location - 1);
+ }
}
diff --git a/tests/src/lib.rs b/tests/src/lib.rs
index 73f0753ca..a791a0c87 100644
--- a/tests/src/lib.rs
+++ b/tests/src/lib.rs
@@ -6,8 +6,8 @@
#![allow(dead_code)]
#[cfg(test)]
-#[path = "../filters.rs"]
-mod filters;
+#[path = "../integration.rs"]
+mod integration;
#[cfg(test)]
#[path = "../macros.rs"]
|
Add tests that check the line numbers
We currently don't have any.
|
Im pretty new to contributing, but I would love to contribute to this repo. Would this be a good issue to start with?
> Im pretty new to contributing, but I would love to contribute to this repo. Would this be a good issue to start with?
Hey @DIvkov575 sorry for the delayed response, I've been traveling.
I think it will be a good first issue. I think the easiest way to get started is to look at `tests/filters.rs`for inspiration. If you have a any questions or you get stuck somewhere feel free to ask!
|
2024-03-16T14:49:52Z
|
0.4
|
06c306fa8f4d41a722f8759f03effd4185eee3ee
|
rust-lang/log
| 613
|
rust-lang__log-613
|
[
"584"
] |
7cb6a01dff9157f3f3dca36aa0152f144023ff60
|
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 3fc335e73..3c263a434 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -44,10 +44,10 @@ jobs:
- run: cargo test --verbose --all-features
- 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_sval
- - run: cargo test --verbose --features kv_unstable_serde
- - run: cargo test --verbose --features "kv_unstable kv_unstable_std kv_unstable_sval kv_unstable_serde"
+ - run: cargo test --verbose --features kv
+ - run: cargo test --verbose --features kv_sval
+ - run: cargo test --verbose --features kv_serde
+ - run: cargo test --verbose --features "kv kv_std kv_sval kv_serde"
- 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
@@ -103,12 +103,12 @@ jobs:
run: |
rustup update nightly --no-self-update
rustup default nightly
- - run: cargo build --verbose -Z avoid-dev-deps --features kv_unstable
- - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable std"
- - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable kv_unstable_sval"
- - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable kv_unstable_serde"
- - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable kv_unstable_std"
- - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable kv_unstable_sval kv_unstable_serde"
+ - run: cargo build --verbose -Z avoid-dev-deps --features kv
+ - run: cargo build --verbose -Z avoid-dev-deps --features "kv std"
+ - run: cargo build --verbose -Z avoid-dev-deps --features "kv kv_sval"
+ - run: cargo build --verbose -Z avoid-dev-deps --features "kv kv_serde"
+ - run: cargo build --verbose -Z avoid-dev-deps --features "kv kv_std"
+ - run: cargo build --verbose -Z avoid-dev-deps --features "kv kv_sval kv_serde"
minimalv:
name: Minimal versions
@@ -119,12 +119,12 @@ jobs:
run: |
rustup update nightly --no-self-update
rustup default nightly
- - run: cargo build --verbose -Z minimal-versions --features kv_unstable
- - run: cargo build --verbose -Z minimal-versions --features "kv_unstable std"
- - run: cargo build --verbose -Z minimal-versions --features "kv_unstable kv_unstable_sval"
- - run: cargo build --verbose -Z minimal-versions --features "kv_unstable kv_unstable_serde"
- - run: cargo build --verbose -Z minimal-versions --features "kv_unstable kv_unstable_std"
- - run: cargo build --verbose -Z minimal-versions --features "kv_unstable kv_unstable_sval kv_unstable_serde"
+ - run: cargo build --verbose -Z minimal-versions --features kv
+ - run: cargo build --verbose -Z minimal-versions --features "kv std"
+ - run: cargo build --verbose -Z minimal-versions --features "kv kv_sval"
+ - run: cargo build --verbose -Z minimal-versions --features "kv kv_serde"
+ - run: cargo build --verbose -Z minimal-versions --features "kv kv_std"
+ - run: cargo build --verbose -Z minimal-versions --features "kv kv_sval kv_serde"
msrv:
name: MSRV
@@ -135,7 +135,9 @@ jobs:
run: |
rustup update 1.60.0 --no-self-update
rustup default 1.60.0
- - run: cargo test --verbose --manifest-path tests/Cargo.toml
+ - run: |
+ cargo test --verbose --manifest-path tests/Cargo.toml
+ cargo test --verbose --manifest-path tests/Cargo.toml --features kv
embedded:
name: Embedded
diff --git a/Cargo.toml b/Cargo.toml
index 89012be02..cf64b43e7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,7 +17,7 @@ rust-version = "1.60.0"
edition = "2021"
[package.metadata.docs.rs]
-features = ["std", "serde", "kv_unstable_std", "kv_unstable_sval", "kv_unstable_serde"]
+features = ["std", "serde", "kv_std", "kv_sval", "kv_serde"]
[[test]]
name = "filters"
@@ -46,25 +46,31 @@ release_max_level_trace = []
std = []
-# requires the latest stable
-# this will have a tighter MSRV before stabilization
-kv_unstable = ["value-bag"]
-kv_unstable_sval = ["kv_unstable", "value-bag/sval", "sval", "sval_ref"]
-kv_unstable_std = ["std", "kv_unstable", "value-bag/error"]
-kv_unstable_serde = ["kv_unstable_std", "value-bag/serde", "serde"]
+kv = []
+kv_sval = ["kv", "value-bag/sval", "sval", "sval_ref"]
+kv_std = ["std", "kv", "value-bag/error"]
+kv_serde = ["kv_std", "value-bag/serde", "serde"]
+
+# Deprecated: use `kv_*` instead
+# These `*_unstable` features will be removed in a future release
+kv_unstable = ["kv", "value-bag"]
+kv_unstable_sval = ["kv_sval", "kv_unstable"]
+kv_unstable_std = ["kv_std", "kv_unstable"]
+kv_unstable_serde = ["kv_serde", "kv_unstable_std"]
[dependencies]
serde = { version = "1.0", optional = true, default-features = false }
sval = { version = "2.1", optional = true, default-features = false }
sval_ref = { version = "2.1", optional = true, default-features = false }
-value-bag = { version = "1.4", optional = true, default-features = false }
+value-bag = { version = "1.7", optional = true, default-features = false, features = ["inline-i128"] }
[dev-dependencies]
serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
serde_test = "1.0"
sval = { version = "2.1" }
sval_derive = { version = "2.1" }
-value-bag = { version = "1.4", features = ["test"] }
+value-bag = { version = "1.7", features = ["test"] }
# NOTE: log doesn't actually depent on this crate. However our dependencies,
# serde and sval, dependent on version 1.0 of the crate, which has problem fixed
diff --git a/README.md b/README.md
index d41414473..d6a08f558 100644
--- a/README.md
+++ b/README.md
@@ -100,23 +100,28 @@ The executable itself may use the `log` crate to log as well.
## Structured logging
-If you enable the `kv_unstable` feature, you can associate structured data with your log records:
+If you enable the `kv` feature, you can associate structured data with your log records:
```rust
-use log::{info, trace, warn, as_serde, as_error};
+use log::{info, trace, warn};
pub fn shave_the_yak(yak: &mut Yak) {
- trace!(target = "yak_events", yak = as_serde!(yak); "Commencing yak shaving");
+ // `yak:serde` will capture `yak` using its `serde::Serialize` impl
+ //
+ // You could also use `:?` for `Debug`, or `:%` for `Display`. For a
+ // full list, see the `log` crate documentation
+ trace!(target = "yak_events", yak:serde; "Commencing yak shaving");
loop {
match find_a_razor() {
Ok(razor) => {
- info!(razor = razor; "Razor located");
+ info!(razor; "Razor located");
yak.shave(razor);
break;
}
- Err(err) => {
- warn!(err = as_error!(err); "Unable to locate a razor, retrying");
+ Err(e) => {
+ // `e:err` will capture `e` using its `std::error::Error` impl
+ warn!(e:err; "Unable to locate a razor, retrying");
}
}
}
diff --git a/benches/value.rs b/benches/value.rs
index e43be50f7..3d0f18bfe 100644
--- a/benches/value.rs
+++ b/benches/value.rs
@@ -1,4 +1,4 @@
-#![cfg(feature = "kv_unstable")]
+#![cfg(feature = "kv")]
#![feature(test)]
use log::kv::Value;
diff --git a/src/__private_api.rs b/src/__private_api.rs
index 92bd15656..fd0a5a762 100644
--- a/src/__private_api.rs
+++ b/src/__private_api.rs
@@ -5,31 +5,28 @@ use crate::{Level, Metadata, Record};
use std::fmt::Arguments;
pub use std::{file, format_args, line, module_path, stringify};
-#[cfg(feature = "kv_unstable")]
-pub type Value<'a> = dyn crate::kv::value::ToValue + 'a;
-
-#[cfg(not(feature = "kv_unstable"))]
-pub type Value<'a> = str;
+#[cfg(not(feature = "kv"))]
+pub type Value<'a> = &'a str;
mod sealed {
/// Types for the `kv` argument.
pub trait KVs<'a> {
- fn into_kvs(self) -> Option<&'a [(&'a str, &'a super::Value<'a>)]>;
+ fn into_kvs(self) -> Option<&'a [(&'a str, super::Value<'a>)]>;
}
}
// Types for the `kv` argument.
-impl<'a> KVs<'a> for &'a [(&'a str, &'a Value<'a>)] {
+impl<'a> KVs<'a> for &'a [(&'a str, Value<'a>)] {
#[inline]
- fn into_kvs(self) -> Option<&'a [(&'a str, &'a Value<'a>)]> {
+ fn into_kvs(self) -> Option<&'a [(&'a str, Value<'a>)]> {
Some(self)
}
}
impl<'a> KVs<'a> for () {
#[inline]
- fn into_kvs(self) -> Option<&'a [(&'a str, &'a Value<'a>)]> {
+ fn into_kvs(self) -> Option<&'a [(&'a str, Value<'a>)]> {
None
}
}
@@ -41,13 +38,11 @@ fn log_impl(
level: Level,
&(target, module_path, file): &(&str, &'static str, &'static str),
line: u32,
- kvs: Option<&[(&str, &Value)]>,
+ kvs: Option<&[(&str, Value)]>,
) {
- #[cfg(not(feature = "kv_unstable"))]
+ #[cfg(not(feature = "kv"))]
if kvs.is_some() {
- panic!(
- "key-value support is experimental and must be enabled using the `kv_unstable` feature"
- )
+ panic!("key-value support is experimental and must be enabled using the `kv` feature")
}
let mut builder = Record::builder();
@@ -60,7 +55,7 @@ fn log_impl(
.file_static(Some(file))
.line(Some(line));
- #[cfg(feature = "kv_unstable")]
+ #[cfg(feature = "kv")]
builder.key_values(&kvs);
crate::logger().log(&builder.build());
@@ -87,3 +82,44 @@ pub fn log<'a, K>(
pub fn enabled(level: Level, target: &str) -> bool {
crate::logger().enabled(&Metadata::builder().level(level).target(target).build())
}
+
+#[cfg(feature = "kv")]
+mod kv_support {
+ use crate::kv;
+
+ pub type Value<'a> = kv::Value<'a>;
+
+ // NOTE: Many functions here accept a double reference &&V
+ // This is so V itself can be ?Sized, while still letting us
+ // erase it to some dyn Trait (because &T is sized)
+
+ pub fn capture_to_value<'a, V: kv::ToValue + ?Sized>(v: &'a &'a V) -> Value<'a> {
+ v.to_value()
+ }
+
+ pub fn capture_debug<'a, V: core::fmt::Debug + ?Sized>(v: &'a &'a V) -> Value<'a> {
+ Value::from_debug(v)
+ }
+
+ pub fn capture_display<'a, V: core::fmt::Display + ?Sized>(v: &'a &'a V) -> Value<'a> {
+ Value::from_display(v)
+ }
+
+ #[cfg(feature = "kv_std")]
+ pub fn capture_error<'a>(v: &'a (dyn std::error::Error + 'static)) -> Value<'a> {
+ Value::from_dyn_error(v)
+ }
+
+ #[cfg(feature = "kv_sval")]
+ pub fn capture_sval<'a, V: sval::Value + ?Sized>(v: &'a &'a V) -> Value<'a> {
+ Value::from_sval(v)
+ }
+
+ #[cfg(feature = "kv_serde")]
+ pub fn capture_serde<'a, V: serde::Serialize + ?Sized>(v: &'a &'a V) -> Value<'a> {
+ Value::from_serde(v)
+ }
+}
+
+#[cfg(feature = "kv")]
+pub use self::kv_support::*;
diff --git a/src/kv/error.rs b/src/kv/error.rs
index 9643a47f2..7efa5af36 100644
--- a/src/kv/error.rs
+++ b/src/kv/error.rs
@@ -11,7 +11,8 @@ enum Inner {
#[cfg(feature = "std")]
Boxed(std_support::BoxedError),
Msg(&'static str),
- Value(value_bag::Error),
+ #[cfg(feature = "value-bag")]
+ Value(crate::kv::value::inner::Error),
Fmt,
}
@@ -23,21 +24,23 @@ impl Error {
}
}
- // Not public so we don't leak the `value_bag` API
- pub(super) fn from_value(err: value_bag::Error) -> Self {
+ // Not public so we don't leak the `crate::kv::value::inner` API
+ #[cfg(feature = "value-bag")]
+ pub(super) fn from_value(err: crate::kv::value::inner::Error) -> Self {
Error {
inner: Inner::Value(err),
}
}
- // Not public so we don't leak the `value_bag` API
- pub(super) fn into_value(self) -> value_bag::Error {
+ // Not public so we don't leak the `crate::kv::value::inner` API
+ #[cfg(feature = "value-bag")]
+ pub(super) fn into_value(self) -> crate::kv::value::inner::Error {
match self.inner {
Inner::Value(err) => err,
- #[cfg(feature = "kv_unstable_std")]
- _ => value_bag::Error::boxed(self),
- #[cfg(not(feature = "kv_unstable_std"))]
- _ => value_bag::Error::msg("error inspecting a value"),
+ #[cfg(feature = "kv_std")]
+ _ => crate::kv::value::inner::Error::boxed(self),
+ #[cfg(not(feature = "kv_std"))]
+ _ => crate::kv::value::inner::Error::msg("error inspecting a value"),
}
}
}
@@ -48,6 +51,7 @@ impl fmt::Display for Error {
match &self.inner {
#[cfg(feature = "std")]
Boxed(err) => err.fmt(f),
+ #[cfg(feature = "value-bag")]
Value(err) => err.fmt(f),
Msg(msg) => msg.fmt(f),
Fmt => fmt::Error.fmt(f),
diff --git a/src/kv/key.rs b/src/kv/key.rs
index 858ec493a..9a64b956f 100644
--- a/src/kv/key.rs
+++ b/src/kv/key.rs
@@ -30,7 +30,7 @@ impl ToKey for str {
}
}
-/// A key in a structured key-value pair.
+/// A key in a key-value.
// These impls must only be based on the as_str() representation of the key
// If a new field (such as an optional index) is added to the key they must not affect comparison
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -93,7 +93,7 @@ mod std_support {
}
}
-#[cfg(feature = "kv_unstable_sval")]
+#[cfg(feature = "kv_sval")]
mod sval_support {
use super::*;
@@ -116,7 +116,7 @@ mod sval_support {
}
}
-#[cfg(feature = "kv_unstable_serde")]
+#[cfg(feature = "kv_serde")]
mod serde_support {
use super::*;
diff --git a/src/kv/mod.rs b/src/kv/mod.rs
index 5dc69337c..1ccb82514 100644
--- a/src/kv/mod.rs
+++ b/src/kv/mod.rs
@@ -1,26 +1,265 @@
-//! **UNSTABLE:** Structured key-value pairs.
+//! Structured logging.
//!
-//! 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
+//! Add the `kv` feature to your `Cargo.toml` to enable
//! this module:
//!
//! ```toml
//! [dependencies.log]
-//! features = ["kv_unstable"]
+//! features = ["kv"]
+//! ```
+//!
+//! # Structured logging in `log`
+//!
+//! Structured logging enhances traditional text-based log records with user-defined
+//! attributes. Structured logs can be analyzed using a variety of data processing
+//! techniques, without needing to find and parse attributes from unstructured text first.
+//!
+//! In `log`, user-defined attributes are part of a [`Source`] on the log record.
+//! Each attribute is a key-value; a pair of [`Key`] and [`Value`]. Keys are strings
+//! and values are a datum of any type that can be formatted or serialized. Simple types
+//! like strings, booleans, and numbers are supported, as well as arbitrarily complex
+//! structures involving nested objects and sequences.
+//!
+//! ## Adding key-values to log records
+//!
+//! Key-values appear before the message format in the `log!` macros:
+//!
+//! ```
+//! # use log::info;
+//! info!(a = 1; "Something of interest");
+//! ```
+//!
+//! Key-values support the same shorthand identifer syntax as `format_args`:
+//!
+//! ```
+//! # use log::info;
+//! let a = 1;
+//!
+//! info!(a; "Something of interest");
+//! ```
+//!
+//! Values are capturing using the [`ToValue`] trait by default. To capture a value
+//! using a different trait implementation, use a modifier after its key. Here's how
+//! the same example can capture `a` using its `Debug` implementation instead:
+//!
+//! ```
+//! # use log::info;
+//! info!(a:? = 1; "Something of interest");
+//! ```
+//!
+//! The following capturing modifiers are supported:
+//!
+//! - `:?` will capture the value using `Debug`.
+//! - `:debug` will capture the value using `Debug`.
+//! - `:%` will capture the value using `Display`.
+//! - `:display` will capture the value using `Display`.
+//! - `:err` will capture the value using `std::error::Error` (requires the `kv_std` feature).
+//! - `:sval` will capture the value using `sval::Value` (requires the `kv_sval` feature).
+//! - `:serde` will capture the value using `serde::Serialize` (requires the `kv_serde` feature).
+//!
+//! ## Working with key-values on log records
+//!
+//! Use the [`Record::key_values`](../struct.Record.html#method.key_values) method to access key-values.
+//!
+//! Individual values can be pulled from the source by their key:
+//!
+//! ```
+//! # fn main() -> Result<(), log::kv::Error> {
+//! use log::kv::{Source, Key, Value};
+//! # let record = log::Record::builder().key_values(&[("a", 1)]).build();
+//!
+//! // info!(a = 1; "Something of interest");
+//!
+//! let a: Value = record.key_values().get(Key::from("a")).unwrap();
+//! assert_eq!(1, a.to_i64().unwrap());
+//! # Ok(())
+//! # }
+//! ```
+//!
+//! All key-values can also be enumerated using a [`VisitSource`]:
+//!
+//! ```
+//! # fn main() -> Result<(), log::kv::Error> {
+//! use std::collections::BTreeMap;
+//!
+//! use log::kv::{self, Source, Key, Value, VisitSource};
+//!
+//! struct Collect<'kvs>(BTreeMap<Key<'kvs>, Value<'kvs>>);
+//!
+//! impl<'kvs> VisitSource<'kvs> for Collect<'kvs> {
+//! fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), kv::Error> {
+//! self.0.insert(key, value);
+//!
+//! Ok(())
+//! }
+//! }
+//!
+//! let mut visitor = Collect(BTreeMap::new());
+//!
+//! # let record = log::Record::builder().key_values(&[("a", 1), ("b", 2), ("c", 3)]).build();
+//! // info!(a = 1, b = 2, c = 3; "Something of interest");
+//!
+//! record.key_values().visit(&mut visitor)?;
+//!
+//! let collected = visitor.0;
+//!
+//! assert_eq!(
+//! vec!["a", "b", "c"],
+//! collected
+//! .keys()
+//! .map(|k| k.as_str())
+//! .collect::<Vec<_>>(),
+//! );
+//! # Ok(())
+//! # }
+//! ```
+//!
+//! [`Value`]s have methods for conversions to common types:
+//!
+//! ```
+//! # fn main() -> Result<(), log::kv::Error> {
+//! use log::kv::{Source, Key};
+//! # let record = log::Record::builder().key_values(&[("a", 1)]).build();
+//!
+//! // info!(a = 1; "Something of interest");
+//!
+//! let a = record.key_values().get(Key::from("a")).unwrap();
+//!
+//! assert_eq!(1, a.to_i64().unwrap());
+//! # Ok(())
+//! # }
+//! ```
+//!
+//! Values also have their own [`VisitValue`] type. Value visitors are a lightweight
+//! API for working with primitives types:
+//!
+//! ```
+//! # fn main() -> Result<(), log::kv::Error> {
+//! use log::kv::{self, Source, Key, VisitValue};
+//! # let record = log::Record::builder().key_values(&[("a", 1)]).build();
+//!
+//! struct IsNumeric(bool);
+//!
+//! impl<'kvs> VisitValue<'kvs> for IsNumeric {
+//! fn visit_any(&mut self, _value: kv::Value) -> Result<(), kv::Error> {
+//! self.0 = false;
+//! Ok(())
+//! }
+//!
+//! fn visit_u64(&mut self, _value: u64) -> Result<(), kv::Error> {
+//! self.0 = true;
+//! Ok(())
+//! }
+//!
+//! fn visit_i64(&mut self, _value: i64) -> Result<(), kv::Error> {
+//! self.0 = true;
+//! Ok(())
+//! }
+//!
+//! fn visit_u128(&mut self, _value: u128) -> Result<(), kv::Error> {
+//! self.0 = true;
+//! Ok(())
+//! }
+//!
+//! fn visit_i128(&mut self, _value: i128) -> Result<(), kv::Error> {
+//! self.0 = true;
+//! Ok(())
+//! }
+//!
+//! fn visit_f64(&mut self, _value: f64) -> Result<(), kv::Error> {
+//! self.0 = true;
+//! Ok(())
+//! }
+//! }
+//!
+//! // info!(a = 1; "Something of interest");
+//!
+//! let a = record.key_values().get(Key::from("a")).unwrap();
+//!
+//! let mut visitor = IsNumeric(false);
+//!
+//! a.visit(&mut visitor)?;
+//!
+//! let is_numeric = visitor.0;
+//!
+//! assert!(is_numeric);
+//! # Ok(())
+//! # }
+//! ```
+//!
+//! To serialize a value to a format like JSON, you can also use either `serde` or `sval`:
+//!
+//! ```
+//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
+//! # #[cfg(feature = "serde")]
+//! # {
+//! # use log::kv::Key;
+//! #[derive(serde::Serialize)]
+//! struct Data {
+//! a: i32, b: bool,
+//! c: &'static str,
+//! }
+//!
+//! let data = Data { a: 1, b: true, c: "Some data" };
+//!
+//! # let source = [("a", log::kv::Value::from_serde(&data))];
+//! # let record = log::Record::builder().key_values(&source).build();
+//! // info!(a = data; "Something of interest");
+//!
+//! let a = record.key_values().get(Key::from("a")).unwrap();
+//!
+//! assert_eq!("{\"a\":1,\"b\":true,\"c\":\"Some data\"}", serde_json::to_string(&a)?);
+//! # }
+//! # Ok(())
+//! # }
+//! ```
+//!
+//! The choice of serialization framework depends on the needs of the consumer.
+//! If you're in a no-std environment, you can use `sval`. In other cases, you can use `serde`.
+//! Log producers and log consumers don't need to agree on the serialization framework.
+//! A value can be captured using its `serde::Serialize` implementation and still be serialized
+//! through `sval` without losing any structure or data.
+//!
+//! Values can also always be formatted using the standard `Debug` and `Display`
+//! traits:
+//!
+//! ```
+//! # use log::kv::Key;
+//! # #[derive(Debug)]
+//! struct Data {
+//! a: i32,
+//! b: bool,
+//! c: &'static str,
+//! }
+//!
+//! let data = Data { a: 1, b: true, c: "Some data" };
+//!
+//! # let source = [("a", log::kv::Value::from_debug(&data))];
+//! # let record = log::Record::builder().key_values(&source).build();
+//! // info!(a = data; "Something of interest");
+//!
+//! let a = record.key_values().get(Key::from("a")).unwrap();
+//!
+//! assert_eq!("Data { a: 1, b: true, c: \"Some data\" }", format!("{a:?}"));
//! ```
mod error;
mod key;
-pub mod source;
-pub mod value;
+#[cfg(not(feature = "kv_unstable"))]
+mod source;
+#[cfg(not(feature = "kv_unstable"))]
+mod value;
pub use self::error::Error;
pub use self::key::{Key, ToKey};
-pub use self::source::{Source, Visitor};
+pub use self::source::{Source, VisitSource};
+pub use self::value::{ToValue, Value, VisitValue};
+
+#[cfg(feature = "kv_unstable")]
+pub mod source;
+#[cfg(feature = "kv_unstable")]
+pub mod value;
-#[doc(inline)]
-pub use self::value::{ToValue, Value};
+#[cfg(feature = "kv_unstable")]
+pub use self::source::Visitor;
diff --git a/src/kv/source.rs b/src/kv/source.rs
index 9c56f8b76..0ca267ce3 100644
--- a/src/kv/source.rs
+++ b/src/kv/source.rs
@@ -1,25 +1,65 @@
-//! Sources for key-value pairs.
+//! Sources for key-values.
+//!
+//! This module defines the [`Source`] type and supporting APIs for
+//! working with collections of key-values.
use crate::kv::{Error, Key, ToKey, ToValue, Value};
use std::fmt;
-/// A source of key-value pairs.
+/// A source of key-values.
///
/// 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
+/// Use the [`VisitSource`](trait.VisitSource.html) trait to inspect the structured data
/// in a source.
+///
+/// A source is like an iterator over its key-values, except with a push-based API
+/// instead of a pull-based one.
+///
+/// # Examples
+///
+/// Enumerating the key-values in a source:
+///
+/// ```
+/// # fn main() -> Result<(), log::kv::Error> {
+/// use log::kv::{self, Source, Key, Value, VisitSource};
+///
+/// // A `VisitSource` that prints all key-values
+/// // VisitSources are fed the key-value pairs of each key-values
+/// struct Printer;
+///
+/// impl<'kvs> VisitSource<'kvs> for Printer {
+/// fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), kv::Error> {
+/// println!("{key}: {value}");
+///
+/// Ok(())
+/// }
+/// }
+///
+/// // A source with 3 key-values
+/// // Common collection types implement the `Source` trait
+/// let source = &[
+/// ("a", 1),
+/// ("b", 2),
+/// ("c", 3),
+/// ];
+///
+/// // Pass an instance of the `VisitSource` to a `Source` to visit it
+/// source.visit(&mut Printer)?;
+/// # Ok(())
+/// # }
+/// ```
pub trait Source {
- /// Visit key-value pairs.
+ /// Visit key-values.
///
- /// A source doesn't have to guarantee any ordering or uniqueness of key-value pairs.
+ /// A source doesn't have to guarantee any ordering or uniqueness of key-values.
/// If the given visitor returns an error then the source may early-return with it,
- /// even if there are more key-value pairs.
+ /// even if there are more key-values.
///
/// # Implementation notes
///
- /// A source should yield the same key-value pairs to a subsequent visitor unless
+ /// A source should yield the same key-values to a subsequent visitor unless
/// that visitor itself fails.
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error>;
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error>;
/// Get the value for a given key.
///
@@ -34,15 +74,14 @@ pub trait Source {
get_default(self, key)
}
- /// Count the number of key-value pairs that can be visited.
+ /// Count the number of key-values that can be visited.
///
/// # Implementation notes
///
- /// A source that knows the number of key-value pairs upfront may provide a more
+ /// A source that knows the number of key-values 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.
+ /// A subsequent call to `visit` should yield the same number of key-values.
fn count(&self) -> usize {
count_default(self)
}
@@ -55,7 +94,7 @@ fn get_default<'v>(source: &'v (impl Source + ?Sized), key: Key) -> Option<Value
found: Option<Value<'v>>,
}
- impl<'k, 'kvs> Visitor<'kvs> for Get<'k, 'kvs> {
+ impl<'k, 'kvs> VisitSource<'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);
@@ -75,7 +114,7 @@ fn get_default<'v>(source: &'v (impl Source + ?Sized), key: Key) -> Option<Value
fn count_default(source: impl Source) -> usize {
struct Count(usize);
- impl<'kvs> Visitor<'kvs> for Count {
+ impl<'kvs> VisitSource<'kvs> for Count {
fn visit_pair(&mut self, _: Key<'kvs>, _: Value<'kvs>) -> Result<(), Error> {
self.0 += 1;
@@ -92,7 +131,7 @@ impl<'a, T> Source for &'a T
where
T: Source + ?Sized,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
Source::visit(&**self, visitor)
}
@@ -110,7 +149,7 @@ where
K: ToKey,
V: ToValue,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
visitor.visit_pair(self.0.to_key(), self.1.to_value())
}
@@ -131,7 +170,7 @@ impl<S> Source for [S]
where
S: Source,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
for source in self {
source.visit(visitor)?;
}
@@ -154,11 +193,28 @@ where
}
}
+impl<const N: usize, S> Source for [S; N]
+where
+ S: Source,
+{
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
+ Source::visit(self as &[_], visitor)
+ }
+
+ fn get(&self, key: Key) -> Option<Value<'_>> {
+ Source::get(self as &[_], key)
+ }
+
+ fn count(&self) -> usize {
+ Source::count(self as &[_])
+ }
+}
+
impl<S> Source for Option<S>
where
S: Source,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
if let Some(source) = self {
source.visit(visitor)?;
}
@@ -176,42 +232,42 @@ where
}
/// A visitor for the key-value pairs in a [`Source`](trait.Source.html).
-pub trait Visitor<'kvs> {
+pub trait VisitSource<'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
+impl<'a, 'kvs, T> VisitSource<'kvs> for &'a mut T
where
- T: Visitor<'kvs> + ?Sized,
+ T: VisitSource<'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> {
+impl<'a, 'b: 'a, 'kvs> VisitSource<'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> {
+impl<'a, 'b: 'a, 'kvs> VisitSource<'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> {
+impl<'a, 'b: 'a, 'kvs> VisitSource<'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> {
+impl<'a, 'b: 'a, 'kvs> VisitSource<'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);
@@ -232,7 +288,7 @@ mod std_support {
where
S: Source + ?Sized,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
Source::visit(&**self, visitor)
}
@@ -249,7 +305,7 @@ mod std_support {
where
S: Source + ?Sized,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
Source::visit(&**self, visitor)
}
@@ -266,7 +322,7 @@ mod std_support {
where
S: Source + ?Sized,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
Source::visit(&**self, visitor)
}
@@ -283,7 +339,7 @@ mod std_support {
where
S: Source,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
Source::visit(&**self, visitor)
}
@@ -296,9 +352,9 @@ mod std_support {
}
}
- impl<'kvs, V> Visitor<'kvs> for Box<V>
+ impl<'kvs, V> VisitSource<'kvs> for Box<V>
where
- V: Visitor<'kvs> + ?Sized,
+ V: VisitSource<'kvs> + ?Sized,
{
fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> {
(**self).visit_pair(key, value)
@@ -311,7 +367,7 @@ mod std_support {
V: ToValue,
S: BuildHasher,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
for (key, value) in self {
visitor.visit_pair(key.to_key(), value.to_value())?;
}
@@ -332,7 +388,7 @@ mod std_support {
K: ToKey + Borrow<str> + Ord,
V: ToValue,
{
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
for (key, value) in self {
visitor.visit_pair(key.to_key(), value.to_value())?;
}
@@ -352,7 +408,7 @@ mod std_support {
mod tests {
use std::collections::{BTreeMap, HashMap};
- use crate::kv::value::tests::Token;
+ use crate::kv::value;
use super::*;
@@ -366,7 +422,7 @@ mod std_support {
fn get() {
let source = vec![("a", 1), ("b", 2), ("a", 1)];
assert_eq!(
- Token::I64(1),
+ value::inner::Token::I64(1),
Source::get(&source, Key::from_str("a")).unwrap().to_token()
);
@@ -382,7 +438,7 @@ mod std_support {
assert_eq!(2, Source::count(&map));
assert_eq!(
- Token::I64(1),
+ value::inner::Token::I64(1),
Source::get(&map, Key::from_str("a")).unwrap().to_token()
);
}
@@ -395,16 +451,20 @@ mod std_support {
assert_eq!(2, Source::count(&map));
assert_eq!(
- Token::I64(1),
+ value::inner::Token::I64(1),
Source::get(&map, Key::from_str("a")).unwrap().to_token()
);
}
}
}
+// NOTE: Deprecated; but aliases can't carry this attribute
+#[cfg(feature = "kv_unstable")]
+pub use VisitSource as Visitor;
+
#[cfg(test)]
mod tests {
- use crate::kv::value::tests::Token;
+ use crate::kv::value;
use super::*;
@@ -415,7 +475,7 @@ mod tests {
#[test]
fn visitor_is_object_safe() {
- fn _check(_: &dyn Visitor) {}
+ fn _check(_: &dyn VisitSource) {}
}
#[test]
@@ -426,7 +486,7 @@ mod tests {
}
impl Source for OnePair {
- fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> {
visitor.visit_pair(self.key.to_key(), self.value.to_value())
}
}
@@ -441,11 +501,11 @@ mod tests {
fn get() {
let source = &[("a", 1), ("b", 2), ("a", 1)] as &[_];
assert_eq!(
- Token::I64(1),
+ value::inner::Token::I64(1),
Source::get(source, Key::from_str("a")).unwrap().to_token()
);
assert_eq!(
- Token::I64(2),
+ value::inner::Token::I64(2),
Source::get(source, Key::from_str("b")).unwrap().to_token()
);
assert!(Source::get(&source, Key::from_str("c")).is_none());
diff --git a/src/kv/value.rs b/src/kv/value.rs
index 1c39bef0a..1511dd02e 100644
--- a/src/kv/value.rs
+++ b/src/kv/value.rs
@@ -1,11 +1,12 @@
//! Structured values.
+//!
+//! This module defines the [`Value`] type and supporting APIs for
+//! capturing and serializing them.
use std::fmt;
pub use crate::kv::Error;
-use value_bag::ValueBag;
-
/// A type that can be converted into a [`Value`](struct.Value.html).
pub trait ToValue {
/// Perform the conversion.
@@ -29,77 +30,21 @@ impl<'v> ToValue for Value<'v> {
}
}
-/// Get a value from a type implementing `std::fmt::Debug`.
-#[macro_export]
-macro_rules! as_debug {
- ($capture:expr) => {
- $crate::kv::Value::from_debug(&$capture)
- };
-}
-
-/// Get a value from a type implementing `std::fmt::Display`.
-#[macro_export]
-macro_rules! as_display {
- ($capture:expr) => {
- $crate::kv::Value::from_display(&$capture)
- };
-}
-
-/// Get a value from an error.
-#[cfg(feature = "kv_unstable_std")]
-#[macro_export]
-macro_rules! as_error {
- ($capture:expr) => {
- $crate::kv::Value::from_dyn_error(&$capture)
- };
-}
-
-#[cfg(feature = "kv_unstable_serde")]
-/// Get a value from a type implementing `serde::Serialize`.
-#[macro_export]
-macro_rules! as_serde {
- ($capture:expr) => {
- $crate::kv::Value::from_serde(&$capture)
- };
-}
-
-/// Get a value from a type implementing `sval::Value`.
-#[cfg(feature = "kv_unstable_sval")]
-#[macro_export]
-macro_rules! as_sval {
- ($capture:expr) => {
- $crate::kv::Value::from_sval(&$capture)
- };
-}
-
-/// A value in a structured key-value pair.
+/// A value in a key-value.
+///
+/// Values are an anonymous bag containing some structured datum.
///
/// # Capturing values
///
/// There are a few ways to capture a value:
///
-/// - Using the `Value::capture_*` methods.
/// - Using the `Value::from_*` methods.
/// - Using the `ToValue` trait.
/// - Using the standard `From` trait.
///
-/// ## Using the `Value::capture_*` methods
-///
-/// `Value` offers a few constructor methods that capture values of different kinds.
-/// These methods require a `T: 'static` to support downcasting.
-///
-/// ```
-/// use log::kv::Value;
-///
-/// let value = Value::capture_debug(&42i32);
-///
-/// assert_eq!(Some(42), value.to_i64());
-/// ```
-///
/// ## Using the `Value::from_*` methods
///
/// `Value` offers a few constructor methods that capture values of different kinds.
-/// These methods don't require `T: 'static`, but can't support downcasting.
///
/// ```
/// use log::kv::Value;
@@ -133,19 +78,45 @@ macro_rules! as_sval {
/// assert_eq!(Some(42), value.to_i64());
/// ```
///
+/// # Data model
+///
+/// Values can hold one of a number of types:
+///
+/// - **Null:** The absence of any other meaningful value. Note that
+/// `Some(Value::null())` is not the same as `None`. The former is
+/// `null` while the latter is `undefined`. This is important to be
+/// able to tell the difference between a key-value that was logged,
+/// but its value was empty (`Some(Value::null())`) and a key-value
+/// that was never logged at all (`None`).
+/// - **Strings:** `str`, `char`.
+/// - **Booleans:** `bool`.
+/// - **Integers:** `u8`-`u128`, `i8`-`i128`, `NonZero*`.
+/// - **Floating point numbers:** `f32`-`f64`.
+/// - **Errors:** `dyn (Error + 'static)`.
+/// - **`serde`:** Any type in `serde`'s data model.
+/// - **`sval`:** Any type in `sval`'s data model.
+///
/// # Serialization
///
-/// `Value` provides a number of ways to be serialized.
+/// Values provide a number of ways to be serialized.
///
/// For basic types the [`Value::visit`] method can be used to extract the
/// underlying typed value. However this is limited in the amount of types
-/// supported (see the [`Visit`] trait methods).
+/// supported (see the [`VisitValue`] trait methods).
///
/// For more complex types one of the following traits can be used:
-/// * [`sval::Value`], requires the `kv_unstable_sval` feature.
-/// * [`serde::Serialize`], requires the `kv_unstable_serde` feature.
+/// * `sval::Value`, requires the `kv_sval` feature.
+/// * `serde::Serialize`, requires the `kv_serde` feature.
+///
+/// You don't need a visitor to serialize values through `serde` or `sval`.
+///
+/// A value can always be serialized using any supported framework, regardless
+/// of how it was captured. If, for example, a value was captured using its
+/// `Display` implementation, it will serialize through `serde` as a string. If it was
+/// captured as a struct using `serde`, it will also serialize as a struct
+/// through `sval`, or can be formatted using a `Debug`-compatible representation.
pub struct Value<'v> {
- inner: ValueBag<'v>,
+ inner: inner::Inner<'v>,
}
impl<'v> Value<'v> {
@@ -157,66 +128,13 @@ impl<'v> Value<'v> {
value.to_value()
}
- /// Get a value from a type implementing `std::fmt::Debug`.
- pub fn capture_debug<T>(value: &'v T) -> Self
- where
- T: fmt::Debug + 'static,
- {
- Value {
- inner: ValueBag::capture_debug(value),
- }
- }
-
- /// Get a value from a type implementing `std::fmt::Display`.
- pub fn capture_display<T>(value: &'v T) -> Self
- where
- T: fmt::Display + 'static,
- {
- Value {
- inner: ValueBag::capture_display(value),
- }
- }
-
- /// Get a value from an error.
- #[cfg(feature = "kv_unstable_std")]
- pub fn capture_error<T>(err: &'v T) -> Self
- where
- T: std::error::Error + 'static,
- {
- Value {
- inner: ValueBag::capture_error(err),
- }
- }
-
- #[cfg(feature = "kv_unstable_serde")]
- /// Get a value from a type implementing `serde::Serialize`.
- pub fn capture_serde<T>(value: &'v T) -> Self
- where
- T: serde::Serialize + 'static,
- {
- Value {
- inner: ValueBag::capture_serde1(value),
- }
- }
-
- /// Get a value from a type implementing `sval::Value`.
- #[cfg(feature = "kv_unstable_sval")]
- pub fn capture_sval<T>(value: &'v T) -> Self
- where
- T: sval::Value + 'static,
- {
- Value {
- inner: ValueBag::capture_sval2(value),
- }
- }
-
/// Get a value from a type implementing `std::fmt::Debug`.
pub fn from_debug<T>(value: &'v T) -> Self
where
T: fmt::Debug,
{
Value {
- inner: ValueBag::from_debug(value),
+ inner: inner::Inner::from_debug(value),
}
}
@@ -226,144 +144,77 @@ impl<'v> Value<'v> {
T: fmt::Display,
{
Value {
- inner: ValueBag::from_display(value),
+ inner: inner::Inner::from_display(value),
}
}
/// Get a value from a type implementing `serde::Serialize`.
- #[cfg(feature = "kv_unstable_serde")]
+ #[cfg(feature = "kv_serde")]
pub fn from_serde<T>(value: &'v T) -> Self
where
T: serde::Serialize,
{
Value {
- inner: ValueBag::from_serde1(value),
+ inner: inner::Inner::from_serde1(value),
}
}
/// Get a value from a type implementing `sval::Value`.
- #[cfg(feature = "kv_unstable_sval")]
+ #[cfg(feature = "kv_sval")]
pub fn from_sval<T>(value: &'v T) -> Self
where
T: sval::Value,
{
Value {
- inner: ValueBag::from_sval2(value),
+ inner: inner::Inner::from_sval2(value),
}
}
/// Get a value from a dynamic `std::fmt::Debug`.
pub fn from_dyn_debug(value: &'v dyn fmt::Debug) -> Self {
Value {
- inner: ValueBag::from_dyn_debug(value),
+ inner: inner::Inner::from_dyn_debug(value),
}
}
/// Get a value from a dynamic `std::fmt::Display`.
pub fn from_dyn_display(value: &'v dyn fmt::Display) -> Self {
Value {
- inner: ValueBag::from_dyn_display(value),
+ inner: inner::Inner::from_dyn_display(value),
}
}
/// Get a value from a dynamic error.
- #[cfg(feature = "kv_unstable_std")]
+ #[cfg(feature = "kv_std")]
pub fn from_dyn_error(err: &'v (dyn std::error::Error + 'static)) -> Self {
Value {
- inner: ValueBag::from_dyn_error(err),
+ inner: inner::Inner::from_dyn_error(err),
+ }
+ }
+
+ /// Get a `null` value.
+ pub fn null() -> Self {
+ Value {
+ inner: inner::Inner::empty(),
}
}
/// Get a value from an internal primitive.
- fn from_value_bag<T>(value: T) -> Self
+ fn from_inner<T>(value: T) -> Self
where
- T: Into<ValueBag<'v>>,
+ T: Into<inner::Inner<'v>>,
{
Value {
inner: value.into(),
}
}
- /// Check whether this value can be downcast to `T`.
- pub fn is<T: 'static>(&self) -> bool {
- self.inner.is::<T>()
- }
-
- /// Try downcast this value to `T`.
- pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
- self.inner.downcast_ref::<T>()
- }
-
/// Inspect this value using a simple visitor.
- pub fn visit(&self, visitor: impl Visit<'v>) -> Result<(), Error> {
- struct Visitor<V>(V);
-
- impl<'v, V> value_bag::visit::Visit<'v> for Visitor<V>
- where
- V: Visit<'v>,
- {
- fn visit_any(&mut self, value: ValueBag) -> Result<(), value_bag::Error> {
- self.0
- .visit_any(Value { inner: value })
- .map_err(Error::into_value)
- }
-
- fn visit_u64(&mut self, value: u64) -> Result<(), value_bag::Error> {
- self.0.visit_u64(value).map_err(Error::into_value)
- }
-
- fn visit_i64(&mut self, value: i64) -> Result<(), value_bag::Error> {
- self.0.visit_i64(value).map_err(Error::into_value)
- }
-
- fn visit_u128(&mut self, value: u128) -> Result<(), value_bag::Error> {
- self.0.visit_u128(value).map_err(Error::into_value)
- }
-
- fn visit_i128(&mut self, value: i128) -> Result<(), value_bag::Error> {
- self.0.visit_i128(value).map_err(Error::into_value)
- }
-
- fn visit_f64(&mut self, value: f64) -> Result<(), value_bag::Error> {
- self.0.visit_f64(value).map_err(Error::into_value)
- }
-
- fn visit_bool(&mut self, value: bool) -> Result<(), value_bag::Error> {
- self.0.visit_bool(value).map_err(Error::into_value)
- }
-
- fn visit_str(&mut self, value: &str) -> Result<(), value_bag::Error> {
- self.0.visit_str(value).map_err(Error::into_value)
- }
-
- fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), value_bag::Error> {
- self.0.visit_borrowed_str(value).map_err(Error::into_value)
- }
-
- fn visit_char(&mut self, value: char) -> Result<(), value_bag::Error> {
- self.0.visit_char(value).map_err(Error::into_value)
- }
-
- #[cfg(feature = "kv_unstable_std")]
- fn visit_error(
- &mut self,
- err: &(dyn std::error::Error + 'static),
- ) -> Result<(), value_bag::Error> {
- self.0.visit_error(err).map_err(Error::into_value)
- }
-
- #[cfg(feature = "kv_unstable_std")]
- fn visit_borrowed_error(
- &mut self,
- err: &'v (dyn std::error::Error + 'static),
- ) -> Result<(), value_bag::Error> {
- self.0.visit_borrowed_error(err).map_err(Error::into_value)
- }
- }
-
- self.inner
- .visit(&mut Visitor(visitor))
- .map_err(Error::from_value)
+ ///
+ /// When the `kv_serde` or `kv_sval` features are enabled, you can also
+ /// serialize a value using its `Serialize` or `Value` implementation.
+ pub fn visit(&self, visitor: impl VisitValue<'v>) -> Result<(), Error> {
+ inner::visit(&self.inner, visitor)
}
}
@@ -379,7 +230,7 @@ impl<'v> fmt::Display for Value<'v> {
}
}
-#[cfg(feature = "kv_unstable_serde")]
+#[cfg(feature = "kv_serde")]
impl<'v> serde::Serialize for Value<'v> {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
@@ -389,14 +240,14 @@ impl<'v> serde::Serialize for Value<'v> {
}
}
-#[cfg(feature = "kv_unstable_sval")]
+#[cfg(feature = "kv_sval")]
impl<'v> sval::Value for Value<'v> {
fn stream<'sval, S: sval::Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> sval::Result {
sval::Value::stream(&self.inner, stream)
}
}
-#[cfg(feature = "kv_unstable_sval")]
+#[cfg(feature = "kv_sval")]
impl<'v> sval_ref::ValueRef<'v> for Value<'v> {
fn stream_ref<S: sval::Stream<'v> + ?Sized>(&self, stream: &mut S) -> sval::Result {
sval_ref::ValueRef::stream_ref(&self.inner, stream)
@@ -409,65 +260,15 @@ impl ToValue for str {
}
}
-impl ToValue for u128 {
- fn to_value(&self) -> Value {
- Value::from(self)
- }
-}
-
-impl ToValue for i128 {
- fn to_value(&self) -> Value {
- Value::from(self)
- }
-}
-
-impl ToValue for std::num::NonZeroU128 {
- fn to_value(&self) -> Value {
- Value::from(self)
- }
-}
-
-impl ToValue for std::num::NonZeroI128 {
- fn to_value(&self) -> Value {
- Value::from(self)
- }
-}
-
impl<'v> From<&'v str> for Value<'v> {
fn from(value: &'v str) -> Self {
- Value::from_value_bag(value)
- }
-}
-
-impl<'v> From<&'v u128> for Value<'v> {
- fn from(value: &'v u128) -> Self {
- Value::from_value_bag(value)
- }
-}
-
-impl<'v> From<&'v i128> for Value<'v> {
- fn from(value: &'v i128) -> Self {
- Value::from_value_bag(value)
- }
-}
-
-impl<'v> From<&'v std::num::NonZeroU128> for Value<'v> {
- fn from(v: &'v std::num::NonZeroU128) -> Value<'v> {
- // SAFETY: `NonZeroU128` and `u128` have the same ABI
- Value::from_value_bag(unsafe { &*(v as *const std::num::NonZeroU128 as *const u128) })
- }
-}
-
-impl<'v> From<&'v std::num::NonZeroI128> for Value<'v> {
- fn from(v: &'v std::num::NonZeroI128) -> Value<'v> {
- // SAFETY: `NonZeroI128` and `i128` have the same ABI
- Value::from_value_bag(unsafe { &*(v as *const std::num::NonZeroI128 as *const i128) })
+ Value::from_inner(value)
}
}
impl ToValue for () {
fn to_value(&self) -> Value {
- Value::from_value_bag(())
+ Value::from_inner(())
}
}
@@ -478,7 +279,7 @@ where
fn to_value(&self) -> Value {
match *self {
Some(ref value) => value.to_value(),
- None => Value::from_value_bag(()),
+ None => Value::from_inner(()),
}
}
}
@@ -494,7 +295,13 @@ macro_rules! impl_to_value_primitive {
impl<'v> From<$into_ty> for Value<'v> {
fn from(value: $into_ty) -> Self {
- Value::from_value_bag(value)
+ Value::from_inner(value)
+ }
+ }
+
+ impl<'v> From<&'v $into_ty> for Value<'v> {
+ fn from(value: &'v $into_ty) -> Self {
+ Value::from_inner(*value)
}
}
)*
@@ -515,6 +322,12 @@ macro_rules! impl_to_value_nonzero_primitive {
Value::from(value.get())
}
}
+
+ impl<'v> From<&'v std::num::$into_ty> for Value<'v> {
+ fn from(value: &'v std::num::$into_ty) -> Self {
+ Value::from(value.get())
+ }
+ }
)*
};
}
@@ -532,12 +345,14 @@ macro_rules! impl_value_to_primitive {
}
}
-impl_to_value_primitive![usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64, char, bool,];
+impl_to_value_primitive![
+ usize, u8, u16, u32, u64, u128, isize, i8, i16, i32, i64, i128, f32, f64, char, bool,
+];
#[rustfmt::skip]
impl_to_value_nonzero_primitive![
- NonZeroUsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64,
- NonZeroIsize, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64,
+ NonZeroUsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128,
+ NonZeroIsize, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128,
];
impl_value_to_primitive![
@@ -559,7 +374,7 @@ impl_value_to_primitive![
impl<'v> Value<'v> {
/// Try convert this value into an error.
- #[cfg(feature = "kv_unstable_std")]
+ #[cfg(feature = "kv_std")]
pub fn to_borrowed_error(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner.to_borrowed_error()
}
@@ -570,7 +385,7 @@ impl<'v> Value<'v> {
}
}
-#[cfg(feature = "kv_unstable_std")]
+#[cfg(feature = "kv_std")]
mod std_support {
use std::borrow::Cow;
use std::rc::Rc;
@@ -631,20 +446,32 @@ mod std_support {
}
}
-/// A visitor for a `Value`.
+/// A visitor for a [`Value`].
///
-/// Also see [`Value`'s documentation on seralization].
+/// Also see [`Value`'s documentation on seralization]. Value visitors are a simple alternative
+/// to a more fully-featured serialization framework like `serde` or `sval`. A value visitor
+/// can differentiate primitive types through methods like [`VisitValue::visit_bool`] and
+/// [`VisitValue::visit_str`], but more complex types like maps and sequences
+/// will fallthrough to [`VisitValue::visit_any`].
+///
+/// If you're trying to serialize a value to a format like JSON, you can use either `serde`
+/// or `sval` directly with the value. You don't need a visitor.
///
/// [`Value`'s documentation on seralization]: Value#serialization
-pub trait Visit<'v> {
+pub trait VisitValue<'v> {
/// Visit a `Value`.
///
- /// This is the only required method on `Visit` and acts as a fallback for any
+ /// This is the only required method on `VisitValue` and acts as a fallback for any
/// more specific methods that aren't overridden.
/// The `Value` may be formatted using its `fmt::Debug` or `fmt::Display` implementation,
/// or serialized using its `sval::Value` or `serde::Serialize` implementation.
fn visit_any(&mut self, value: Value) -> Result<(), Error>;
+ /// Visit an empty value.
+ fn visit_null(&mut self) -> Result<(), Error> {
+ self.visit_any(Value::null())
+ }
+
/// Visit an unsigned integer.
fn visit_u64(&mut self, value: u64) -> Result<(), Error> {
self.visit_any(value.into())
@@ -657,12 +484,12 @@ pub trait Visit<'v> {
/// Visit a big unsigned integer.
fn visit_u128(&mut self, value: u128) -> Result<(), Error> {
- self.visit_any((&value).into())
+ self.visit_any((value).into())
}
/// Visit a big signed integer.
fn visit_i128(&mut self, value: i128) -> Result<(), Error> {
- self.visit_any((&value).into())
+ self.visit_any((value).into())
}
/// Visit a floating point.
@@ -692,13 +519,13 @@ pub trait Visit<'v> {
}
/// Visit an error.
- #[cfg(feature = "kv_unstable_std")]
+ #[cfg(feature = "kv_std")]
fn visit_error(&mut self, err: &(dyn std::error::Error + 'static)) -> Result<(), Error> {
self.visit_any(Value::from_dyn_error(err))
}
/// Visit an error.
- #[cfg(feature = "kv_unstable_std")]
+ #[cfg(feature = "kv_std")]
fn visit_borrowed_error(
&mut self,
err: &'v (dyn std::error::Error + 'static),
@@ -707,14 +534,18 @@ pub trait Visit<'v> {
}
}
-impl<'a, 'v, T: ?Sized> Visit<'v> for &'a mut T
+impl<'a, 'v, T: ?Sized> VisitValue<'v> for &'a mut T
where
- T: Visit<'v>,
+ T: VisitValue<'v>,
{
fn visit_any(&mut self, value: Value) -> Result<(), Error> {
(**self).visit_any(value)
}
+ fn visit_null(&mut self) -> Result<(), Error> {
+ (**self).visit_null()
+ }
+
fn visit_u64(&mut self, value: u64) -> Result<(), Error> {
(**self).visit_u64(value)
}
@@ -751,12 +582,12 @@ where
(**self).visit_char(value)
}
- #[cfg(feature = "kv_unstable_std")]
+ #[cfg(feature = "kv_std")]
fn visit_error(&mut self, err: &(dyn std::error::Error + 'static)) -> Result<(), Error> {
(**self).visit_error(err)
}
- #[cfg(feature = "kv_unstable_std")]
+ #[cfg(feature = "kv_std")]
fn visit_borrowed_error(
&mut self,
err: &'v (dyn std::error::Error + 'static),
@@ -765,13 +596,586 @@ where
}
}
+#[cfg(feature = "value-bag")]
+pub(in crate::kv) mod inner {
+ /**
+ An implementation of `Value` based on a library called `value_bag`.
+
+ `value_bag` was written specifically for use in `log`'s value, but was split out when it outgrew
+ the codebase here. It's a general-purpose type-erasure library that handles mapping between
+ more fully-featured serialization frameworks.
+ */
+ use super::*;
+
+ pub use value_bag::ValueBag as Inner;
+
+ pub use value_bag::Error;
+
+ #[cfg(test)]
+ pub use value_bag::test::TestToken as Token;
+
+ pub fn visit<'v>(
+ inner: &Inner<'v>,
+ visitor: impl VisitValue<'v>,
+ ) -> Result<(), crate::kv::Error> {
+ struct InnerVisitValue<V>(V);
+
+ impl<'v, V> value_bag::visit::Visit<'v> for InnerVisitValue<V>
+ where
+ V: VisitValue<'v>,
+ {
+ fn visit_any(&mut self, value: value_bag::ValueBag) -> Result<(), Error> {
+ self.0
+ .visit_any(Value { inner: value })
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_empty(&mut self) -> Result<(), Error> {
+ self.0.visit_null().map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_u64(&mut self, value: u64) -> Result<(), Error> {
+ self.0
+ .visit_u64(value)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_i64(&mut self, value: i64) -> Result<(), Error> {
+ self.0
+ .visit_i64(value)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_u128(&mut self, value: u128) -> Result<(), Error> {
+ self.0
+ .visit_u128(value)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_i128(&mut self, value: i128) -> Result<(), Error> {
+ self.0
+ .visit_i128(value)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_f64(&mut self, value: f64) -> Result<(), Error> {
+ self.0
+ .visit_f64(value)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_bool(&mut self, value: bool) -> Result<(), Error> {
+ self.0
+ .visit_bool(value)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_str(&mut self, value: &str) -> Result<(), Error> {
+ self.0
+ .visit_str(value)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), Error> {
+ self.0
+ .visit_borrowed_str(value)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ fn visit_char(&mut self, value: char) -> Result<(), Error> {
+ self.0
+ .visit_char(value)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ #[cfg(feature = "kv_std")]
+ fn visit_error(
+ &mut self,
+ err: &(dyn std::error::Error + 'static),
+ ) -> Result<(), Error> {
+ self.0
+ .visit_error(err)
+ .map_err(crate::kv::Error::into_value)
+ }
+
+ #[cfg(feature = "kv_std")]
+ fn visit_borrowed_error(
+ &mut self,
+ err: &'v (dyn std::error::Error + 'static),
+ ) -> Result<(), Error> {
+ self.0
+ .visit_borrowed_error(err)
+ .map_err(crate::kv::Error::into_value)
+ }
+ }
+
+ inner
+ .visit(&mut InnerVisitValue(visitor))
+ .map_err(crate::kv::Error::from_value)
+ }
+}
+
+#[cfg(not(feature = "value-bag"))]
+pub(in crate::kv) mod inner {
+ /**
+ This is a dependency-free implementation of `Value` when there's no serialization frameworks involved.
+ In these simple cases a more fully featured solution like `value_bag` isn't needed, so we avoid pulling it in.
+
+ There are a few things here that need to remain consistent with the `value_bag`-based implementation:
+
+ 1. Conversions should always produce the same results. If a conversion here returns `Some`, then
+ the same `value_bag`-based conversion must also. Of particular note here are floats to ints; they're
+ based on the standard library's `TryInto` conversions, which need to be convert to `i32` or `u32`,
+ and then to `f64`.
+ 2. VisitValues should always be called in the same way. If a particular type of value calls `visit_i64`,
+ then the same `value_bag`-based visitor must also.
+ */
+ use super::*;
+
+ #[derive(Clone)]
+ pub enum Inner<'v> {
+ None,
+ Bool(bool),
+ Str(&'v str),
+ Char(char),
+ I64(i64),
+ U64(u64),
+ F64(f64),
+ I128(i128),
+ U128(u128),
+ Debug(&'v dyn fmt::Debug),
+ Display(&'v dyn fmt::Display),
+ }
+
+ impl<'v> From<()> for Inner<'v> {
+ fn from(_: ()) -> Self {
+ Inner::None
+ }
+ }
+
+ impl<'v> From<bool> for Inner<'v> {
+ fn from(v: bool) -> Self {
+ Inner::Bool(v)
+ }
+ }
+
+ impl<'v> From<char> for Inner<'v> {
+ fn from(v: char) -> Self {
+ Inner::Char(v)
+ }
+ }
+
+ impl<'v> From<f32> for Inner<'v> {
+ fn from(v: f32) -> Self {
+ Inner::F64(v as f64)
+ }
+ }
+
+ impl<'v> From<f64> for Inner<'v> {
+ fn from(v: f64) -> Self {
+ Inner::F64(v)
+ }
+ }
+
+ impl<'v> From<i8> for Inner<'v> {
+ fn from(v: i8) -> Self {
+ Inner::I64(v as i64)
+ }
+ }
+
+ impl<'v> From<i16> for Inner<'v> {
+ fn from(v: i16) -> Self {
+ Inner::I64(v as i64)
+ }
+ }
+
+ impl<'v> From<i32> for Inner<'v> {
+ fn from(v: i32) -> Self {
+ Inner::I64(v as i64)
+ }
+ }
+
+ impl<'v> From<i64> for Inner<'v> {
+ fn from(v: i64) -> Self {
+ Inner::I64(v as i64)
+ }
+ }
+
+ impl<'v> From<isize> for Inner<'v> {
+ fn from(v: isize) -> Self {
+ Inner::I64(v as i64)
+ }
+ }
+
+ impl<'v> From<u8> for Inner<'v> {
+ fn from(v: u8) -> Self {
+ Inner::U64(v as u64)
+ }
+ }
+
+ impl<'v> From<u16> for Inner<'v> {
+ fn from(v: u16) -> Self {
+ Inner::U64(v as u64)
+ }
+ }
+
+ impl<'v> From<u32> for Inner<'v> {
+ fn from(v: u32) -> Self {
+ Inner::U64(v as u64)
+ }
+ }
+
+ impl<'v> From<u64> for Inner<'v> {
+ fn from(v: u64) -> Self {
+ Inner::U64(v as u64)
+ }
+ }
+
+ impl<'v> From<usize> for Inner<'v> {
+ fn from(v: usize) -> Self {
+ Inner::U64(v as u64)
+ }
+ }
+
+ impl<'v> From<i128> for Inner<'v> {
+ fn from(v: i128) -> Self {
+ Inner::I128(v)
+ }
+ }
+
+ impl<'v> From<u128> for Inner<'v> {
+ fn from(v: u128) -> Self {
+ Inner::U128(v)
+ }
+ }
+
+ impl<'v> From<&'v str> for Inner<'v> {
+ fn from(v: &'v str) -> Self {
+ Inner::Str(v)
+ }
+ }
+
+ impl<'v> fmt::Debug for Inner<'v> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self {
+ Inner::None => fmt::Debug::fmt(&None::<()>, f),
+ Inner::Bool(v) => fmt::Debug::fmt(v, f),
+ Inner::Str(v) => fmt::Debug::fmt(v, f),
+ Inner::Char(v) => fmt::Debug::fmt(v, f),
+ Inner::I64(v) => fmt::Debug::fmt(v, f),
+ Inner::U64(v) => fmt::Debug::fmt(v, f),
+ Inner::F64(v) => fmt::Debug::fmt(v, f),
+ Inner::I128(v) => fmt::Debug::fmt(v, f),
+ Inner::U128(v) => fmt::Debug::fmt(v, f),
+ Inner::Debug(v) => fmt::Debug::fmt(v, f),
+ Inner::Display(v) => fmt::Display::fmt(v, f),
+ }
+ }
+ }
+
+ impl<'v> fmt::Display for Inner<'v> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self {
+ Inner::None => fmt::Debug::fmt(&None::<()>, f),
+ Inner::Bool(v) => fmt::Display::fmt(v, f),
+ Inner::Str(v) => fmt::Display::fmt(v, f),
+ Inner::Char(v) => fmt::Display::fmt(v, f),
+ Inner::I64(v) => fmt::Display::fmt(v, f),
+ Inner::U64(v) => fmt::Display::fmt(v, f),
+ Inner::F64(v) => fmt::Display::fmt(v, f),
+ Inner::I128(v) => fmt::Display::fmt(v, f),
+ Inner::U128(v) => fmt::Display::fmt(v, f),
+ Inner::Debug(v) => fmt::Debug::fmt(v, f),
+ Inner::Display(v) => fmt::Display::fmt(v, f),
+ }
+ }
+ }
+
+ impl<'v> Inner<'v> {
+ pub fn from_debug<T: fmt::Debug>(value: &'v T) -> Self {
+ Inner::Debug(value)
+ }
+
+ pub fn from_display<T: fmt::Display>(value: &'v T) -> Self {
+ Inner::Display(value)
+ }
+
+ pub fn from_dyn_debug(value: &'v dyn fmt::Debug) -> Self {
+ Inner::Debug(value)
+ }
+
+ pub fn from_dyn_display(value: &'v dyn fmt::Display) -> Self {
+ Inner::Display(value)
+ }
+
+ pub fn empty() -> Self {
+ Inner::None
+ }
+
+ pub fn to_bool(&self) -> Option<bool> {
+ match self {
+ Inner::Bool(v) => Some(*v),
+ _ => None,
+ }
+ }
+
+ pub fn to_char(&self) -> Option<char> {
+ match self {
+ Inner::Char(v) => Some(*v),
+ _ => None,
+ }
+ }
+
+ pub fn to_f64(&self) -> Option<f64> {
+ match self {
+ Inner::F64(v) => Some(*v),
+ Inner::I64(v) => {
+ let v: i32 = (*v).try_into().ok()?;
+ v.try_into().ok()
+ }
+ Inner::U64(v) => {
+ let v: u32 = (*v).try_into().ok()?;
+ v.try_into().ok()
+ }
+ Inner::I128(v) => {
+ let v: i32 = (*v).try_into().ok()?;
+ v.try_into().ok()
+ }
+ Inner::U128(v) => {
+ let v: u32 = (*v).try_into().ok()?;
+ v.try_into().ok()
+ }
+ _ => None,
+ }
+ }
+
+ pub fn to_i64(&self) -> Option<i64> {
+ match self {
+ Inner::I64(v) => Some(*v),
+ Inner::U64(v) => (*v).try_into().ok(),
+ Inner::I128(v) => (*v).try_into().ok(),
+ Inner::U128(v) => (*v).try_into().ok(),
+ _ => None,
+ }
+ }
+
+ pub fn to_u64(&self) -> Option<u64> {
+ match self {
+ Inner::U64(v) => Some(*v),
+ Inner::I64(v) => (*v).try_into().ok(),
+ Inner::I128(v) => (*v).try_into().ok(),
+ Inner::U128(v) => (*v).try_into().ok(),
+ _ => None,
+ }
+ }
+
+ pub fn to_u128(&self) -> Option<u128> {
+ match self {
+ Inner::U128(v) => Some(*v),
+ Inner::I64(v) => (*v).try_into().ok(),
+ Inner::U64(v) => (*v).try_into().ok(),
+ Inner::I128(v) => (*v).try_into().ok(),
+ _ => None,
+ }
+ }
+
+ pub fn to_i128(&self) -> Option<i128> {
+ match self {
+ Inner::I128(v) => Some(*v),
+ Inner::I64(v) => (*v).try_into().ok(),
+ Inner::U64(v) => (*v).try_into().ok(),
+ Inner::U128(v) => (*v).try_into().ok(),
+ _ => None,
+ }
+ }
+
+ pub fn to_borrowed_str(&self) -> Option<&'v str> {
+ match self {
+ Inner::Str(v) => Some(v),
+ _ => None,
+ }
+ }
+
+ #[cfg(test)]
+ pub fn to_test_token(&self) -> Token {
+ match self {
+ Inner::None => Token::None,
+ Inner::Bool(v) => Token::Bool(*v),
+ Inner::Str(v) => Token::Str(*v),
+ Inner::Char(v) => Token::Char(*v),
+ Inner::I64(v) => Token::I64(*v),
+ Inner::U64(v) => Token::U64(*v),
+ Inner::F64(v) => Token::F64(*v),
+ Inner::I128(_) => unimplemented!(),
+ Inner::U128(_) => unimplemented!(),
+ Inner::Debug(_) => unimplemented!(),
+ Inner::Display(_) => unimplemented!(),
+ }
+ }
+ }
+
+ #[cfg(test)]
+ #[derive(Debug, PartialEq)]
+ pub enum Token<'v> {
+ None,
+ Bool(bool),
+ Char(char),
+ Str(&'v str),
+ F64(f64),
+ I64(i64),
+ U64(u64),
+ }
+
+ pub fn visit<'v>(
+ inner: &Inner<'v>,
+ mut visitor: impl VisitValue<'v>,
+ ) -> Result<(), crate::kv::Error> {
+ match inner {
+ Inner::None => visitor.visit_null(),
+ Inner::Bool(v) => visitor.visit_bool(*v),
+ Inner::Str(v) => visitor.visit_borrowed_str(*v),
+ Inner::Char(v) => visitor.visit_char(*v),
+ Inner::I64(v) => visitor.visit_i64(*v),
+ Inner::U64(v) => visitor.visit_u64(*v),
+ Inner::F64(v) => visitor.visit_f64(*v),
+ Inner::I128(v) => visitor.visit_i128(*v),
+ Inner::U128(v) => visitor.visit_u128(*v),
+ Inner::Debug(v) => visitor.visit_any(Value::from_dyn_debug(*v)),
+ Inner::Display(v) => visitor.visit_any(Value::from_dyn_display(*v)),
+ }
+ }
+}
+
+impl<'v> Value<'v> {
+ /// Get a value from a type implementing `std::fmt::Debug`.
+ #[cfg(feature = "kv_unstable")]
+ #[deprecated(note = "use `from_debug` instead")]
+ pub fn capture_debug<T>(value: &'v T) -> Self
+ where
+ T: fmt::Debug + 'static,
+ {
+ Value::from_debug(value)
+ }
+
+ /// Get a value from a type implementing `std::fmt::Display`.
+ #[cfg(feature = "kv_unstable")]
+ #[deprecated(note = "use `from_display` instead")]
+ pub fn capture_display<T>(value: &'v T) -> Self
+ where
+ T: fmt::Display + 'static,
+ {
+ Value::from_display(value)
+ }
+
+ /// Get a value from an error.
+ #[cfg(feature = "kv_unstable_std")]
+ #[deprecated(note = "use `from_dyn_error` instead")]
+ pub fn capture_error<T>(err: &'v T) -> Self
+ where
+ T: std::error::Error + 'static,
+ {
+ Value::from_dyn_error(err)
+ }
+
+ /// Get a value from a type implementing `serde::Serialize`.
+ #[cfg(feature = "kv_unstable_serde")]
+ #[deprecated(note = "use `from_serde` instead")]
+ pub fn capture_serde<T>(value: &'v T) -> Self
+ where
+ T: serde::Serialize + 'static,
+ {
+ Value::from_serde(value)
+ }
+
+ /// Get a value from a type implementing `sval::Value`.
+ #[cfg(feature = "kv_unstable_sval")]
+ #[deprecated(note = "use `from_sval` instead")]
+ pub fn capture_sval<T>(value: &'v T) -> Self
+ where
+ T: sval::Value + 'static,
+ {
+ Value::from_sval(value)
+ }
+
+ /// Check whether this value can be downcast to `T`.
+ #[cfg(feature = "kv_unstable")]
+ #[deprecated(
+ note = "downcasting has been removed; log an issue at https://github.com/rust-lang/log/issues if this is something you rely on"
+ )]
+ pub fn is<T: 'static>(&self) -> bool {
+ false
+ }
+
+ /// Try downcast this value to `T`.
+ #[cfg(feature = "kv_unstable")]
+ #[deprecated(
+ note = "downcasting has been removed; log an issue at https://github.com/rust-lang/log/issues if this is something you rely on"
+ )]
+ pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
+ None
+ }
+}
+
+// NOTE: Deprecated; but aliases can't carry this attribute
+#[cfg(feature = "kv_unstable")]
+pub use VisitValue as Visit;
+
+/// Get a value from a type implementing `std::fmt::Debug`.
+#[cfg(feature = "kv_unstable")]
+#[deprecated(note = "use the `key:? = value` macro syntax instead")]
+#[macro_export]
+macro_rules! as_debug {
+ ($capture:expr) => {
+ $crate::kv::Value::from_debug(&$capture)
+ };
+}
+
+/// Get a value from a type implementing `std::fmt::Display`.
+#[cfg(feature = "kv_unstable")]
+#[deprecated(note = "use the `key:% = value` macro syntax instead")]
+#[macro_export]
+macro_rules! as_display {
+ ($capture:expr) => {
+ $crate::kv::Value::from_display(&$capture)
+ };
+}
+
+/// Get a value from an error.
+#[cfg(feature = "kv_unstable_std")]
+#[deprecated(note = "use the `key:err = value` macro syntax instead")]
+#[macro_export]
+macro_rules! as_error {
+ ($capture:expr) => {
+ $crate::kv::Value::from_dyn_error(&$capture)
+ };
+}
+
+#[cfg(feature = "kv_unstable_serde")]
+#[deprecated(note = "use the `key:serde = value` macro syntax instead")]
+/// Get a value from a type implementing `serde::Serialize`.
+#[macro_export]
+macro_rules! as_serde {
+ ($capture:expr) => {
+ $crate::kv::Value::from_serde(&$capture)
+ };
+}
+
+/// Get a value from a type implementing `sval::Value`.
+#[cfg(feature = "kv_unstable_sval")]
+#[deprecated(note = "use the `key:sval = value` macro syntax instead")]
+#[macro_export]
+macro_rules! as_sval {
+ ($capture:expr) => {
+ $crate::kv::Value::from_sval(&$capture)
+ };
+}
+
#[cfg(test)]
pub(crate) mod tests {
use super::*;
- pub(crate) use value_bag::test::TestToken as Token;
impl<'v> Value<'v> {
- pub(crate) fn to_token(&self) -> Token {
+ pub(crate) fn to_token(&self) -> inner::Token {
self.inner.to_test_token()
}
}
@@ -824,40 +1228,6 @@ pub(crate) mod tests {
vec![Value::from('a'), Value::from('⛰')].into_iter()
}
- #[test]
- fn test_capture_fmt() {
- assert_eq!(Some(42u64), Value::capture_display(&42).to_u64());
- assert_eq!(Some(42u64), Value::capture_debug(&42).to_u64());
-
- assert!(Value::from_display(&42).to_u64().is_none());
- assert!(Value::from_debug(&42).to_u64().is_none());
- }
-
- #[cfg(feature = "kv_unstable_std")]
- #[test]
- fn test_capture_error() {
- let err = std::io::Error::from(std::io::ErrorKind::Other);
-
- assert!(Value::capture_error(&err).to_borrowed_error().is_some());
- assert!(Value::from_dyn_error(&err).to_borrowed_error().is_some());
- }
-
- #[cfg(feature = "kv_unstable_serde")]
- #[test]
- fn test_capture_serde() {
- assert_eq!(Some(42u64), Value::capture_serde(&42).to_u64());
-
- assert_eq!(Some(42u64), Value::from_serde(&42).to_u64());
- }
-
- #[cfg(feature = "kv_unstable_sval")]
- #[test]
- fn test_capture_sval() {
- assert_eq!(Some(42u64), Value::capture_sval(&42).to_u64());
-
- assert_eq!(Some(42u64), Value::from_sval(&42).to_u64());
- }
-
#[test]
fn test_to_value_display() {
assert_eq!(42u64.to_value().to_string(), "42");
@@ -873,18 +1243,18 @@ pub(crate) mod tests {
#[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!(42u64.to_value().to_token(), inner::Token::U64(42));
+ assert_eq!(42i64.to_value().to_token(), inner::Token::I64(42));
+ assert_eq!(42.01f64.to_value().to_token(), inner::Token::F64(42.01));
+ assert_eq!(true.to_value().to_token(), inner::Token::Bool(true));
+ assert_eq!('a'.to_value().to_token(), inner::Token::Char('a'));
assert_eq!(
"a loong string".to_value().to_token(),
- Token::Str("a loong string".into())
+ inner::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!(None::<bool>.to_value().to_token(), Token::None);
+ assert_eq!(Some(true).to_value().to_token(), inner::Token::Bool(true));
+ assert_eq!(().to_value().to_token(), inner::Token::None);
+ assert_eq!(None::<bool>.to_value().to_token(), inner::Token::None);
}
#[test]
@@ -909,12 +1279,22 @@ pub(crate) mod tests {
}
}
+ #[test]
+ fn test_to_float() {
+ // Only integers from i32::MIN..=u32::MAX can be converted into floats
+ assert!(Value::from(i32::MIN).to_f64().is_some());
+ assert!(Value::from(u32::MAX).to_f64().is_some());
+
+ assert!(Value::from((i32::MIN as i64) - 1).to_f64().is_none());
+ assert!(Value::from((u32::MAX as u64) + 1).to_f64().is_none());
+ }
+
#[test]
fn test_to_cow_str() {
for v in str() {
assert!(v.to_borrowed_str().is_some());
- #[cfg(feature = "kv_unstable_std")]
+ #[cfg(feature = "kv_std")]
assert!(v.to_cow_str().is_some());
}
@@ -923,13 +1303,13 @@ pub(crate) mod tests {
assert!(v.to_borrowed_str().is_some());
- #[cfg(feature = "kv_unstable_std")]
+ #[cfg(feature = "kv_std")]
assert!(v.to_cow_str().is_some());
for v in unsigned().chain(signed()).chain(float()).chain(bool()) {
assert!(v.to_borrowed_str().is_none());
- #[cfg(feature = "kv_unstable_std")]
+ #[cfg(feature = "kv_std")]
assert!(v.to_cow_str().is_none());
}
}
@@ -966,22 +1346,11 @@ pub(crate) mod tests {
}
}
- #[test]
- fn test_downcast_ref() {
- #[derive(Debug)]
- struct Foo(u64);
-
- let v = Value::capture_debug(&Foo(42));
-
- assert!(v.is::<Foo>());
- assert_eq!(42u64, v.downcast_ref::<Foo>().expect("invalid downcast").0);
- }
-
#[test]
fn test_visit_integer() {
struct Extract(Option<u64>);
- impl<'v> Visit<'v> for Extract {
+ impl<'v> VisitValue<'v> for Extract {
fn visit_any(&mut self, value: Value) -> Result<(), Error> {
unimplemented!("unexpected value: {value:?}")
}
@@ -1003,7 +1372,7 @@ pub(crate) mod tests {
fn test_visit_borrowed_str() {
struct Extract<'v>(Option<&'v str>);
- impl<'v> Visit<'v> for Extract<'v> {
+ impl<'v> VisitValue<'v> for Extract<'v> {
fn visit_any(&mut self, value: Value) -> Result<(), Error> {
unimplemented!("unexpected value: {value:?}")
}
diff --git a/src/lib.rs b/src/lib.rs
index 6a3a8ca98..505d24961 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -88,7 +88,7 @@
//!
//! ## Structured logging
//!
-//! If you enable the `kv_unstable` feature you can associate structured values
+//! If you enable the `kv` feature you can associate structured values
//! with your log records. If we take the example from before, we can include
//! some additional context besides what's in the formatted message:
//!
@@ -97,31 +97,33 @@
//! # #[derive(Debug, Serialize)] pub struct Yak(String);
//! # impl Yak { fn shave(&mut self, _: u32) {} }
//! # fn find_a_razor() -> Result<u32, std::io::Error> { Ok(1) }
-//! # #[cfg(feature = "kv_unstable_serde")]
+//! # #[cfg(feature = "kv_serde")]
//! # fn main() {
-//! use log::{info, warn, as_serde, as_error};
+//! use log::{info, warn};
//!
//! pub fn shave_the_yak(yak: &mut Yak) {
-//! info!(target: "yak_events", yak = as_serde!(yak); "Commencing yak shaving");
+//! info!(target: "yak_events", yak:serde; "Commencing yak shaving");
//!
//! loop {
//! match find_a_razor() {
//! Ok(razor) => {
-//! info!(razor = razor; "Razor located");
+//! info!(razor; "Razor located");
//! yak.shave(razor);
//! break;
//! }
-//! Err(err) => {
-//! warn!(err = as_error!(err); "Unable to locate a razor, retrying");
+//! Err(e) => {
+//! warn!(e:err; "Unable to locate a razor, retrying");
//! }
//! }
//! }
//! }
//! # }
-//! # #[cfg(not(feature = "kv_unstable_serde"))]
+//! # #[cfg(not(feature = "kv_serde"))]
//! # fn main() {}
//! ```
//!
+//! See the [`kv`] module documentation for more details.
+//!
//! # Available logging implementations
//!
//! In order to produce log output executables have to use
@@ -353,7 +355,7 @@ use std::{cmp, fmt, mem};
mod macros;
mod serde;
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
pub mod kv;
#[cfg(target_has_atomic = "ptr")]
@@ -721,7 +723,7 @@ pub struct Record<'a> {
module_path: Option<MaybeStaticStr<'a>>,
file: Option<MaybeStaticStr<'a>>,
line: Option<u32>,
- #[cfg(feature = "kv_unstable")]
+ #[cfg(feature = "kv")]
key_values: KeyValues<'a>,
}
@@ -729,11 +731,11 @@ pub struct Record<'a> {
// `#[derive(Debug)]` on `Record`. It also
// provides a useful `Debug` implementation for
// the underlying `Source`.
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
#[derive(Clone)]
struct KeyValues<'a>(&'a dyn kv::Source);
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
impl<'a> fmt::Debug for KeyValues<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut visitor = f.debug_map();
@@ -810,14 +812,14 @@ impl<'a> Record<'a> {
}
/// The structured key-value pairs associated with the message.
- #[cfg(feature = "kv_unstable")]
+ #[cfg(feature = "kv")]
#[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")]
+ #[cfg(feature = "kv")]
#[inline]
pub fn to_builder(&self) -> RecordBuilder {
RecordBuilder {
@@ -902,7 +904,7 @@ impl<'a> RecordBuilder<'a> {
module_path: None,
file: None,
line: None,
- #[cfg(feature = "kv_unstable")]
+ #[cfg(feature = "kv")]
key_values: KeyValues(&None::<(kv::Key, kv::Value)>),
},
}
@@ -972,7 +974,7 @@ impl<'a> RecordBuilder<'a> {
}
/// Set [`key_values`](struct.Record.html#method.key_values)
- #[cfg(feature = "kv_unstable")]
+ #[cfg(feature = "kv")]
#[inline]
pub fn key_values(&mut self, kvs: &'a dyn kv::Source) -> &mut RecordBuilder<'a> {
self.record.key_values = KeyValues(kvs);
@@ -1755,16 +1757,16 @@ mod tests {
}
#[test]
- #[cfg(feature = "kv_unstable")]
+ #[cfg(feature = "kv")]
fn test_record_key_values_builder() {
use super::Record;
- use crate::kv::{self, Visitor};
+ use crate::kv::{self, VisitSource};
- struct TestVisitor {
+ struct TestVisitSource {
seen_pairs: usize,
}
- impl<'kvs> Visitor<'kvs> for TestVisitor {
+ impl<'kvs> VisitSource<'kvs> for TestVisitSource {
fn visit_pair(
&mut self,
_: kv::Key<'kvs>,
@@ -1778,7 +1780,7 @@ mod tests {
let kvs: &[(&str, i32)] = &[("a", 1), ("b", 2)];
let record_test = Record::builder().key_values(&kvs).build();
- let mut visitor = TestVisitor { seen_pairs: 0 };
+ let mut visitor = TestVisitSource { seen_pairs: 0 };
record_test.key_values().visit(&mut visitor).unwrap();
@@ -1786,7 +1788,7 @@ mod tests {
}
#[test]
- #[cfg(feature = "kv_unstable")]
+ #[cfg(feature = "kv")]
fn test_record_key_values_get_coerce() {
use super::Record;
diff --git a/src/macros.rs b/src/macros.rs
index 44945f0d9..48a7447ef 100644
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -29,8 +29,8 @@
/// ```
#[macro_export]
macro_rules! log {
- // log!(target: "my_target", Level::Info, key1 = 42, key2 = true; "a {} event", "log");
- (target: $target:expr, $lvl:expr, $($key:tt = $value:expr),+; $($arg:tt)+) => ({
+ // log!(target: "my_target", Level::Info, key1:? = 42, key2 = true; "a {} event", "log");
+ (target: $target:expr, $lvl:expr, $($key:tt $(:$capture:tt)? $(= $value:expr)?),+; $($arg:tt)+) => ({
let lvl = $lvl;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
$crate::__private_api::log::<&_>(
@@ -38,7 +38,7 @@ macro_rules! log {
lvl,
&($target, $crate::__private_api::module_path!(), $crate::__private_api::file!()),
$crate::__private_api::line!(),
- &[$(($crate::__log_key!($key), &$value)),+]
+ &[$(($crate::__log_key!($key), $crate::__log_value!($key $(:$capture)* = $($value)*))),+]
);
}
});
@@ -226,8 +226,12 @@ macro_rules! log_enabled {
};
}
+// These macros use a pattern of #[cfg]s to produce nicer error
+// messages when log features aren't available
+
#[doc(hidden)]
#[macro_export]
+#[cfg(feature = "kv")]
macro_rules! __log_key {
// key1 = 42
($($args:ident)*) => {
@@ -238,3 +242,128 @@ macro_rules! __log_key {
$($args)*
};
}
+
+#[doc(hidden)]
+#[macro_export]
+#[cfg(not(feature = "kv"))]
+macro_rules! __log_key {
+ ($($args:tt)*) => {
+ compile_error!("key value support requires the `kv` feature of `log`")
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+#[cfg(feature = "kv")]
+macro_rules! __log_value {
+ // Entrypoint
+ ($key:tt = $args:expr) => {
+ $crate::__log_value!(($args):value)
+ };
+ ($key:tt :$capture:tt = $args:expr) => {
+ $crate::__log_value!(($args):$capture)
+ };
+ ($key:ident =) => {
+ $crate::__log_value!(($key):value)
+ };
+ ($key:ident :$capture:tt =) => {
+ $crate::__log_value!(($key):$capture)
+ };
+ // ToValue
+ (($args:expr):value) => {
+ $crate::__private_api::capture_to_value(&&$args)
+ };
+ // Debug
+ (($args:expr):?) => {
+ $crate::__private_api::capture_debug(&&$args)
+ };
+ (($args:expr):debug) => {
+ $crate::__private_api::capture_debug(&&$args)
+ };
+ // Display
+ (($args:expr):%) => {
+ $crate::__private_api::capture_display(&&$args)
+ };
+ (($args:expr):display) => {
+ $crate::__private_api::capture_display(&&$args)
+ };
+ //Error
+ (($args:expr):err) => {
+ $crate::__log_value_error!($args)
+ };
+ // sval::Value
+ (($args:expr):sval) => {
+ $crate::__log_value_sval!($args)
+ };
+ // serde::Serialize
+ (($args:expr):serde) => {
+ $crate::__log_value_serde!($args)
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+#[cfg(not(feature = "kv"))]
+macro_rules! __log_value {
+ ($($args:tt)*) => {
+ compile_error!("key value support requires the `kv` feature of `log`")
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+#[cfg(feature = "kv_sval")]
+macro_rules! __log_value_sval {
+ ($args:expr) => {
+ $crate::__private_api::capture_sval(&&$args)
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+#[cfg(not(feature = "kv_sval"))]
+macro_rules! __log_value_sval {
+ ($args:expr) => {
+ compile_error!("capturing values as `sval::Value` requites the `kv_sval` feature of `log`")
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+#[cfg(feature = "kv_serde")]
+macro_rules! __log_value_serde {
+ ($args:expr) => {
+ $crate::__private_api::capture_serde(&&$args)
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+#[cfg(not(feature = "kv_serde"))]
+macro_rules! __log_value_serde {
+ ($args:expr) => {
+ compile_error!(
+ "capturing values as `serde::Serialize` requites the `kv_serde` feature of `log`"
+ )
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+#[cfg(feature = "kv_std")]
+macro_rules! __log_value_error {
+ ($args:expr) => {
+ $crate::__private_api::capture_error(&$args)
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+#[cfg(not(feature = "kv_std"))]
+macro_rules! __log_value_error {
+ ($args:expr) => {
+ compile_error!(
+ "capturing values as `std::error::Error` requites the `kv_std` feature of `log`"
+ )
+ };
+}
|
diff --git a/tests/Cargo.toml b/tests/Cargo.toml
index 88f37b5d4..8754bb16a 100644
--- a/tests/Cargo.toml
+++ b/tests/Cargo.toml
@@ -7,6 +7,10 @@ build = "src/build.rs"
[features]
std = ["log/std"]
+kv = ["log/kv"]
+kv_std = ["log/kv_std"]
+kv_sval = ["log/kv_sval"]
+kv_serde = ["log/kv_serde"]
[dependencies.log]
path = ".."
diff --git a/tests/macros.rs b/tests/macros.rs
index 3afcf88da..20da6ac44 100644
--- a/tests/macros.rs
+++ b/tests/macros.rs
@@ -107,7 +107,7 @@ fn expr() {
}
#[test]
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
fn kv_no_args() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello");
@@ -121,7 +121,7 @@ fn kv_no_args() {
}
#[test]
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
fn kv_expr_args() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, cat_math = { let mut x = 0; x += 1; x + 1 }; "hello");
@@ -136,7 +136,7 @@ fn kv_expr_args() {
}
#[test]
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
fn kv_anonymous_args() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {}", "world");
@@ -151,7 +151,7 @@ fn kv_anonymous_args() {
}
#[test]
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
fn kv_named_args() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}", world = "world");
@@ -166,7 +166,16 @@ fn kv_named_args() {
}
#[test]
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
+fn kv_ident() {
+ let cat_1 = "chashu";
+ let cat_2 = "nori";
+
+ all_log_macros!(cat_1, cat_2:%, cat_count = 2; "hello {world}", world = "world");
+}
+
+#[test]
+#[cfg(feature = "kv")]
fn kv_expr_context() {
match "chashu" {
cat_1 => {
@@ -196,14 +205,14 @@ fn implicit_named_args() {
all_log_macros!(target: "my_target", "hello {world}");
all_log_macros!(target: "my_target", "hello {world}",);
- #[cfg(feature = "kv_unstable")]
+ #[cfg(feature = "kv")]
all_log_macros!(target = "my_target"; "hello {world}");
- #[cfg(feature = "kv_unstable")]
+ #[cfg(feature = "kv")]
all_log_macros!(target = "my_target"; "hello {world}",);
}
#[test]
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
fn kv_implicit_named_args() {
let world = "world";
@@ -219,7 +228,7 @@ fn kv_implicit_named_args() {
}
#[test]
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
fn kv_string_keys() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, "also dogs" = "Fílos", "key/that-can't/be/an/ident" = "hi"; "hello {world}", world = "world");
@@ -229,7 +238,7 @@ fn kv_string_keys() {
}
#[test]
-#[cfg(feature = "kv_unstable")]
+#[cfg(feature = "kv")]
fn kv_common_value_types() {
all_log_macros!(
u8 = 42u8,
@@ -250,6 +259,53 @@ fn kv_common_value_types() {
);
}
+#[test]
+#[cfg(feature = "kv")]
+fn kv_debug() {
+ all_log_macros!(
+ a:? = 42,
+ b:debug = 42;
+ "hello world"
+ );
+}
+
+#[test]
+#[cfg(feature = "kv")]
+fn kv_display() {
+ all_log_macros!(
+ a:% = 42,
+ b:display = 42;
+ "hello world"
+ );
+}
+
+#[test]
+#[cfg(feature = "kv_std")]
+fn kv_error() {
+ all_log_macros!(
+ a:err = std::io::Error::new(std::io::ErrorKind::Other, "an error");
+ "hello world"
+ );
+}
+
+#[test]
+#[cfg(feature = "kv_sval")]
+fn kv_sval() {
+ all_log_macros!(
+ a:sval = 42;
+ "hello world"
+ );
+}
+
+#[test]
+#[cfg(feature = "kv_serde")]
+fn kv_serde() {
+ all_log_macros!(
+ a:serde = 42;
+ "hello world"
+ );
+}
+
/// Some and None (from Option) are used in the macros.
#[derive(Debug)]
enum Type {
|
Review of key-value feature
Discussion for https://github.com/rust-lang/log/issues/328.
|
Thanks for all the time you've spent digging through this so far @Thomasdezeeuw! I think we're getting towards something that feels appropriate for the `log` crate without losing capability.
Just checking back in on this, is the main blocker we've got deciding whether to default to capturing using `ToValue` and supporting some `tracing`-like syntax for changing it?
> Just checking back in on this, is the main blocker we've got deciding whether to default to capturing using `ToValue` and supporting some `tracing`-like syntax for changing it?
Yes, I think those are the two main things from this pr.
I'm doing some work on this now; removing the `Value::capture_*` and downcasting methods, and improving the overall documentation for the `kv` module.
It looks like we already default to using `ToValue` for key-values, so nothing needs to change there. That just leaves some nicer macro support for tweaking how values are captured.
Are you happy with that plan @Thomasdezeeuw?
|
2024-01-26T08:08:39Z
|
0.4
|
06c306fa8f4d41a722f8759f03effd4185eee3ee
|
rust-lang/log
| 495
|
rust-lang__log-495
|
[
"494"
] |
bc181df9fbb1ad40abcae41ae2dd53b3652b50bc
|
diff --git a/src/macros.rs b/src/macros.rs
index ec2f4200c..a4fe6803b 100644
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -37,7 +37,7 @@ macro_rules! log {
__log_format_args!($($arg)+),
lvl,
&($target, __log_module_path!(), __log_file!(), __log_line!()),
- Some(&[$((__log_key!($key), &$value)),+])
+ std::option::Option::Some(&[$((__log_key!($key), &$value)),+])
);
}
});
@@ -50,7 +50,7 @@ macro_rules! log {
__log_format_args!($($arg)+),
lvl,
&($target, __log_module_path!(), __log_file!(), __log_line!()),
- None,
+ std::option::Option::None,
);
}
});
|
diff --git a/tests/macros.rs b/tests/macros.rs
index 7b2483ceb..fcd8556a3 100644
--- a/tests/macros.rs
+++ b/tests/macros.rs
@@ -215,3 +215,16 @@ fn kv_string_keys() {
all_log_macros!(target: "my_target", "also dogs" = "Fílos", "key/that-can't/be/an/ident" = "hi"; "hello {world}", world = "world");
}
+
+/// Some and None (from Option) are used in the macros.
+#[derive(Debug)]
+enum Type {
+ Some,
+ None,
+}
+
+#[test]
+fn regression_issue_494() {
+ use Type::*;
+ all_log_macros!("some message: {:?}, {:?}", None, Some);
+}
|
regression: enum variant named None fails to compile in 0.4.15
I have written some poker software where it makes sense (at least to me!) to have a `None` variant. When I upgraded to log 0.4.15, my code stopped compiling. Here's a short illustration:
```
#[derive(Debug)]
pub enum Limit {
None,
}
pub struct M {
limit: Limit,
}
impl M {
fn bring_in_based_min_raise(&self) {
use Limit::*;
log::warn!("self.limit should not be: {:?}", self.limit);
}
}
fn main() {
println!("Hello, world!");
}
```
```
error[E0308]: mismatched types
--> src/main.rs:13:9
|
13 | log::warn!("self.limit should not be: {:?}", self.limit);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Option`, found enum `Limit`
|
= note: expected enum `Option<&[(&str, &str)]>`
found enum `Limit`
```
I've [temporarily pinned to log 0.4.14](https://github.com/ctm/mb2-doc/issues/933), which works fine.
|
It looks like this `None` (and the `Some` above it) needs to be fully qualified: https://github.com/rust-lang/log/blob/master/src/macros.rs#L53
@sfackler can you make a pr or want me to do it?
I can make one later today, but go for it if you have the time earlier.
|
2022-03-22T13:01:36Z
|
0.4
|
06c306fa8f4d41a722f8759f03effd4185eee3ee
|
rust-lang/log
| 470
|
rust-lang__log-470
|
[
"381"
] |
525336f364fb80b63d910e783884b14be71814c5
|
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index d90d48baa..855a2d965 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -37,6 +37,8 @@ jobs:
rustup update ${{ matrix.rust }} --no-self-update
rustup default ${{ matrix.rust }}
- run: cargo test --verbose
+ - run: cargo test --verbose --no-default-features
+ - run: cargo test --verbose --all-features
- run: cargo test --verbose --features serde
- run: cargo test --verbose --features std
- run: cargo test --verbose --features kv_unstable
|
diff --git a/tests/filters.rs b/tests/filters.rs
index de6bd189f..f37751c24 100644
--- a/tests/filters.rs
+++ b/tests/filters.rs
@@ -1,3 +1,5 @@
+#![allow(dead_code, unused_imports)]
+
#[cfg(not(lib_build))]
#[macro_use]
extern crate log;
@@ -32,18 +34,36 @@ impl Log for Logger {
#[cfg_attr(lib_build, test)]
fn main() {
- let me = Arc::new(State {
- last_log: Mutex::new(None),
- });
- let a = me.clone();
- set_boxed_logger(Box::new(Logger(me))).unwrap();
+ // These tests don't really make sense when static
+ // max level filtering is applied
+ #[cfg(not(any(
+ feature = "max_level_off",
+ feature = "max_level_error",
+ feature = "max_level_warn",
+ feature = "max_level_info",
+ feature = "max_level_debug",
+ feature = "max_level_trace",
+ feature = "max_level_off",
+ feature = "max_level_error",
+ feature = "max_level_warn",
+ feature = "max_level_info",
+ feature = "max_level_debug",
+ feature = "max_level_trace",
+ )))]
+ {
+ 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);
+ 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) {
|
`cargo test --all-features` fails
from git master, if i run `cargo test --all-features`, i see:
```
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running target/debug/deps/log-7d6eb7ffa43b7118
running 45 tests
test kv::key::tests::key_from_string ... ok
test kv::source::std_support::tests::btree_map ... ok
test kv::source::std_support::tests::get ... ok
test kv::source::std_support::tests::count ... ok
test kv::source::tests::count ... ok
test kv::source::std_support::tests::hash_map ... ok
test kv::source::tests::source_is_object_safe ... ok
test kv::source::tests::get ... ok
test kv::source::tests::visitor_is_object_safe ... ok
test kv::value::fill::tests::fill_cast ... ok
test kv::value::fill::tests::fill_value_borrowed ... ok
test kv::value::fill::tests::fill_value_owned ... ok
test kv::value::impls::tests::test_to_value_display ... ok
test kv::value::internal::cast::std_support::tests::primitive_cast ... ok
test kv::value::internal::fmt::tests::fmt_cast ... ok
test kv::value::internal::cast::tests::primitive_cast ... ok
test kv::value::internal::sval::tests::sval_cast ... ok
test kv::value::internal::sval::tests::test_from_sval ... ok
test kv::value::internal::sval::tests::test_sval_structured ... ok
test serde::tests::test_level_case_insensitive ... ok
test serde::tests::test_level_de_error ... ok
test kv::value::impls::tests::test_to_value_structured ... ok
test serde::tests::test_level_filter_case_insensitive ... ok
test serde::tests::test_level_filter_de_bytes ... ok
test serde::tests::test_level_de_bytes ... ok
test serde::tests::test_level_filter_de_error ... ok
test serde::tests::test_level_ser_de ... ok
test tests::test_cross_eq ... ok
test tests::test_error_trait ... ok
test tests::test_level_from_str ... ok
test tests::test_level_show ... ok
test tests::test_levelfilter_from_str ... ok
test tests::test_levelfilter_show ... ok
test tests::test_metadata_builder ... ok
test serde::tests::test_level_filter_ser_de ... ok
test tests::test_metadata_convenience_builder ... ok
test tests::test_record_builder ... ok
test tests::test_record_complete_builder ... ok
test tests::test_record_convenience_builder ... ok
test tests::test_record_key_values_builder ... ok
test tests::test_to_level ... ok
test tests::test_record_key_values_get_coerce ... ok
test tests::test_to_level_filter ... ok
test tests::test_cross_cmp ... ok
test kv::value::fill::tests::fill_multiple_times_panics ... ok
test result: ok. 45 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Running target/debug/deps/filters-8e7b236d082cd8bd
thread 'main' panicked at 'assertion failed: `(left == right)`
left: `None`,
right: `Some(Error)`', tests/filters.rs:71:5
stack backtrace:
0: 0x556fd8283524 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h6001c6574450335d
1: 0x556fd829461d - core::fmt::write::h1371734f6a7c7bc2
2: 0x556fd8282845 - std::io::Write::write_fmt::h5ee928f19b08369c
3: 0x556fd827c84e - std::panicking::default_hook::{{closure}}::h6b521085a6513c53
4: 0x556fd827c560 - std::panicking::default_hook::h3e3fe9b536fd99f6
5: 0x556fd827ceeb - std::panicking::rust_panic_with_hook::h3d899269d6b7f8f7
6: 0x556fd827ca8e - std::panicking::continue_panic_fmt::h22635bd1aa2db87e
7: 0x556fd827c9cf - std::panicking::begin_panic_fmt::h4934e76a4a1dca0f
8: 0x556fd827797b - filters::last::h6ea39f99f73e96a2
at tests/filters.rs:71
9: 0x556fd82771c8 - filters::test::h018f9be09c67b83d
at tests/filters.rs:50
10: 0x556fd8276ee5 - filters::main::h5cb267d978caf4dd
at tests/filters.rs:40
11: 0x556fd82742e0 - std::rt::lang_start::{{closure}}::h99add10a92b1f5d8
at /usr/src/rustc-1.40.0/src/libstd/rt.rs:61
12: 0x556fd827c913 - std::panicking::try::do_call::h405fa073712ab5d5
13: 0x556fd8283eea - __rust_maybe_catch_panic
14: 0x556fd827fd39 - std::rt::lang_start_internal::he63ceb3eba03dd55
15: 0x556fd82742b9 - std::rt::lang_start::h2e31d45daa3b065e
at /usr/src/rustc-1.40.0/src/libstd/rt.rs:61
16: 0x556fd82779ca - main
17: 0x7fb00fb9dbbb - __libc_start_main
18: 0x556fd82741aa - _start
19: 0x0 - <unknown>
error: test failed, to rerun pass '--test filters'
```
This is also a problem at tags 0.4.8 and 0.4.9. (i confess i don't really understand what it means exactly)
It's likely to cause problems for [the debian package for this crate](https://tracker.debian.org/pkg/rust-log) as well, since we typically try to run `cargo test --all-features`.
|
Ah, unfortunately `log`'s features are set up in such a way that running with `--all-features` doesn't really make sense (it uses features to set minimum levels at compile-time). It's unfortunate for tests to fail though since `--all-features` should be a perfectly legitimate flag so we should do something about the filters tests so they don't run unless the feature set makes sense to them.
|
2021-11-15T06:58:10Z
|
0.4
|
06c306fa8f4d41a722f8759f03effd4185eee3ee
|
rust-lang/log
| 423
|
rust-lang__log-423
|
[
"408"
] |
cb0b8c4f93758531ef3eada40da2642e9ed0d616
|
diff --git a/Cargo.toml b/Cargo.toml
index 69fe79d25..299937c3e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,7 +16,7 @@ exclude = ["rfcs/**/*", "/.travis.yml", "/appveyor.yml"]
build = "build.rs"
[package.metadata.docs.rs]
-features = ["std", "serde", "kv_unstable_sval"]
+features = ["std", "serde", "kv_unstable_std", "kv_unstable_sval", "kv_unstable_serde"]
[[test]]
name = "filters"
@@ -45,14 +45,17 @@ std = []
# requires the latest stable
# this will have a tighter MSRV before stabilization
-kv_unstable = []
-kv_unstable_sval = ["kv_unstable", "sval/fmt"]
+kv_unstable = ["value-bag"]
+kv_unstable_sval = ["kv_unstable", "value-bag/sval", "sval"]
+kv_unstable_std = ["std", "kv_unstable", "value-bag/error"]
+kv_unstable_serde = ["kv_unstable_std", "value-bag/serde", "serde"]
[dependencies]
cfg-if = "1.0"
serde = { version = "1.0", optional = true, default-features = false }
-sval = { version = "0.5.2", optional = true, default-features = false }
+sval = { version = "1.0.0-alpha.4", optional = true, default-features = false }
+value-bag = { version = "1.0.0-alpha.5", optional = true, default-features = false }
[dev-dependencies]
serde_test = "1.0"
-sval = { version = "0.5.2", features = ["test"] }
+value-bag = { version = "1.0.0-alpha.5", features = ["test"] }
diff --git a/build.rs b/build.rs
index bb2462d06..2b17e0be9 100644
--- a/build.rs
+++ b/build.rs
@@ -4,10 +4,6 @@
use std::env;
use std::str;
-#[cfg(feature = "kv_unstable")]
-#[path = "src/kv/value/internal/cast/primitive.rs"]
-mod primitive;
-
fn main() {
let target = match rustc_target() {
Some(target) => target,
@@ -22,11 +18,6 @@ fn main() {
println!("cargo:rustc-cfg=has_atomics");
}
- // Generate sorted type id lookup
- #[cfg(feature = "kv_unstable")]
- primitive::generate();
-
- println!("cargo:rustc-cfg=srcbuild");
println!("cargo:rerun-if-changed=build.rs");
}
diff --git a/src/kv/source.rs b/src/kv/source.rs
index 86b016033..cb5efc066 100644
--- a/src/kv/source.rs
+++ b/src/kv/source.rs
@@ -323,7 +323,7 @@ mod std_support {
#[cfg(test)]
mod tests {
use super::*;
- use kv::value::test::Token;
+ use kv::value::tests::Token;
use std::collections::{BTreeMap, HashMap};
#[test]
@@ -375,7 +375,7 @@ mod std_support {
#[cfg(test)]
mod tests {
use super::*;
- use kv::value::test::Token;
+ use kv::value::tests::Token;
#[test]
fn source_is_object_safe() {
diff --git a/src/kv/value.rs b/src/kv/value.rs
new file mode 100644
index 000000000..561ea8641
--- /dev/null
+++ b/src/kv/value.rs
@@ -0,0 +1,659 @@
+//! Structured values.
+
+use std::fmt;
+
+extern crate value_bag;
+
+#[cfg(feature = "kv_unstable_sval")]
+extern crate sval;
+
+#[cfg(feature = "kv_unstable_serde")]
+extern crate serde;
+
+use self::value_bag::ValueBag;
+
+pub use kv::Error;
+
+/// 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.clone(),
+ }
+ }
+}
+
+/// A value in a structured key-value pair.
+///
+/// # Capturing values
+///
+/// There are a few ways to capture a value:
+///
+/// - Using the `Value::capture_*` methods.
+/// - Using the `Value::from_*` methods.
+/// - Using the `ToValue` trait.
+/// - Using the standard `From` trait.
+///
+/// ## Using the `Value::capture_*` methods
+///
+/// `Value` offers a few constructor methods that capture values of different kinds.
+/// These methods require a `T: 'static` to support downcasting.
+///
+/// ```
+/// use log::kv::Value;
+///
+/// let value = Value::capture_debug(&42i32);
+///
+/// assert_eq!(Some(42), value.to_i32());
+/// ```
+///
+/// ## Using the `Value::from_*` methods
+///
+/// `Value` offers a few constructor methods that capture values of different kinds.
+/// These methods don't require `T: 'static`, but can't support downcasting.
+///
+/// ```
+/// use log::kv::Value;
+///
+/// let value = Value::from_debug(&42i32);
+///
+/// assert_eq!(None, value.to_i32());
+/// ```
+///
+/// ## Using the `ToValue` trait
+///
+/// The `ToValue` trait can be used to capture values generically.
+/// It's the bound used by `Source`.
+///
+/// ```
+/// # use log::kv::ToValue;
+/// let value = 42i32.to_value();
+///
+/// assert_eq!(Some(42), value.to_i32());
+/// ```
+///
+/// ```
+/// # use std::fmt::Debug;
+/// use log::kv::ToValue;
+///
+/// let value = (&42i32 as &dyn Debug).to_value();
+///
+/// assert_eq!(None, value.to_i32());
+/// ```
+///
+/// ## Using the standard `From` trait
+///
+/// Standard types that implement `ToValue` also implement `From`.
+///
+/// ```
+/// use log::kv::Value;
+///
+/// let value = Value::from(42i32);
+///
+/// assert_eq!(Some(42), value.to_i32());
+/// ```
+pub struct Value<'v> {
+ inner: ValueBag<'v>,
+}
+
+impl<'v> Value<'v> {
+ /// Get a value from a type implementing `ToValue`.
+ pub fn from_any<T>(value: &'v T) -> Self
+ where
+ T: ToValue,
+ {
+ value.to_value()
+ }
+
+ /// Get a value from a type implementing `std::fmt::Debug`.
+ pub fn capture_debug<T>(value: &'v T) -> Self
+ where
+ T: fmt::Debug + 'static,
+ {
+ Value {
+ inner: ValueBag::capture_debug(value),
+ }
+ }
+
+ /// Get a value from a type implementing `std::fmt::Display`.
+ pub fn capture_display<T>(value: &'v T) -> Self
+ where
+ T: fmt::Display + 'static,
+ {
+ Value {
+ inner: ValueBag::capture_display(value),
+ }
+ }
+
+ /// Get a value from an error.
+ #[cfg(feature = "kv_unstable_std")]
+ pub fn capture_error<T>(err: &'v T) -> Self
+ where
+ T: std::error::Error + 'static,
+ {
+ Value {
+ inner: ValueBag::capture_error(err),
+ }
+ }
+
+ #[cfg(feature = "kv_unstable_serde")]
+ /// Get a value from a type implementing `serde::Serialize`.
+ pub fn capture_serde<T>(value: &'v T) -> Self
+ where
+ T: self::serde::Serialize + 'static,
+ {
+ Value {
+ inner: ValueBag::capture_serde1(value),
+ }
+ }
+
+ /// Get a value from a type implementing `sval::value::Value`.
+ #[cfg(feature = "kv_unstable_sval")]
+ pub fn capture_sval<T>(value: &'v T) -> Self
+ where
+ T: self::sval::value::Value + 'static,
+ {
+ Value {
+ inner: ValueBag::capture_sval1(value),
+ }
+ }
+
+ /// Get a value from a type implementing `std::fmt::Debug`.
+ pub fn from_debug<T>(value: &'v T) -> Self
+ where
+ T: fmt::Debug,
+ {
+ Value {
+ inner: ValueBag::from_debug(value),
+ }
+ }
+
+ /// Get a value from a type implementing `std::fmt::Display`.
+ pub fn from_display<T>(value: &'v T) -> Self
+ where
+ T: fmt::Display,
+ {
+ Value {
+ inner: ValueBag::from_display(value),
+ }
+ }
+
+ /// Get a value from a type implementing `serde::Serialize`.
+ #[cfg(feature = "kv_unstable_serde")]
+ pub fn from_serde<T>(value: &'v T) -> Self
+ where
+ T: self::serde::Serialize,
+ {
+ Value {
+ inner: ValueBag::from_serde1(value),
+ }
+ }
+
+ /// Get a value from a type implementing `sval::value::Value`.
+ #[cfg(feature = "kv_unstable_sval")]
+ pub fn from_sval<T>(value: &'v T) -> Self
+ where
+ T: self::sval::value::Value,
+ {
+ Value {
+ inner: ValueBag::from_sval1(value),
+ }
+ }
+
+ /// Get a value from a dynamic `std::fmt::Debug`.
+ pub fn from_dyn_debug(value: &'v dyn fmt::Debug) -> Self {
+ Value {
+ inner: ValueBag::from_dyn_debug(value),
+ }
+ }
+
+ /// Get a value from a dynamic `std::fmt::Display`.
+ pub fn from_dyn_display(value: &'v dyn fmt::Display) -> Self {
+ Value {
+ inner: ValueBag::from_dyn_display(value),
+ }
+ }
+
+ /// Get a value from a dynamic error.
+ #[cfg(feature = "kv_unstable_std")]
+ pub fn from_dyn_error(err: &'v (dyn std::error::Error + 'static)) -> Self {
+ Value {
+ inner: ValueBag::from_dyn_error(err),
+ }
+ }
+
+ /// Get a value from a type implementing `sval::value::Value`.
+ #[cfg(feature = "kv_unstable_sval")]
+ pub fn from_dyn_sval(value: &'v dyn self::sval::value::Value) -> Self {
+ Value {
+ inner: ValueBag::from_dyn_sval1(value),
+ }
+ }
+
+ /// Get a value from an internal primitive.
+ fn from_value_bag<T>(value: T) -> Self
+ where
+ T: Into<ValueBag<'v>>,
+ {
+ Value {
+ inner: value.into(),
+ }
+ }
+}
+
+impl<'v> fmt::Debug for Value<'v> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fmt::Debug::fmt(&self.inner, f)
+ }
+}
+
+impl<'v> fmt::Display for Value<'v> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fmt::Display::fmt(&self.inner, f)
+ }
+}
+
+impl ToValue for dyn fmt::Debug {
+ fn to_value(&self) -> Value {
+ Value::from_dyn_debug(self)
+ }
+}
+
+impl ToValue for dyn fmt::Display {
+ fn to_value(&self) -> Value {
+ Value::from_dyn_display(self)
+ }
+}
+
+#[cfg(feature = "kv_unstable_std")]
+impl ToValue for dyn std::error::Error + 'static {
+ fn to_value(&self) -> Value {
+ Value::from_dyn_error(self)
+ }
+}
+
+#[cfg(feature = "kv_unstable_serde")]
+impl<'v> self::serde::Serialize for Value<'v> {
+ fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
+ where
+ S: self::serde::Serializer,
+ {
+ self.inner.serialize(s)
+ }
+}
+
+#[cfg(feature = "kv_unstable_sval")]
+impl<'v> self::sval::value::Value for Value<'v> {
+ fn stream(&self, stream: &mut self::sval::value::Stream) -> self::sval::value::Result {
+ self::sval::value::Value::stream(&self.inner, stream)
+ }
+}
+
+#[cfg(feature = "kv_unstable_sval")]
+impl ToValue for dyn self::sval::value::Value {
+ fn to_value(&self) -> Value {
+ Value::from_dyn_sval(self)
+ }
+}
+
+impl ToValue for 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_value_bag(value)
+ }
+}
+
+impl ToValue for () {
+ fn to_value(&self) -> Value {
+ Value::from_value_bag(())
+ }
+}
+
+impl<T> ToValue for Option<T>
+where
+ T: ToValue,
+{
+ fn to_value(&self) -> Value {
+ match *self {
+ Some(ref value) => value.to_value(),
+ None => Value::from_value_bag(()),
+ }
+ }
+}
+
+macro_rules! impl_to_value_primitive {
+ ($($into_ty:ty,)*) => {
+ $(
+ 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_value_bag(value)
+ }
+ }
+ )*
+ };
+}
+
+macro_rules! impl_value_to_primitive {
+ ($(#[doc = $doc:tt] $into_name:ident -> $into_ty:ty,)*) => {
+ impl<'v> Value<'v> {
+ $(
+ #[doc = $doc]
+ pub fn $into_name(&self) -> Option<$into_ty> {
+ self.inner.$into_name()
+ }
+ )*
+ }
+ }
+}
+
+impl_to_value_primitive![usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64, char, bool,];
+
+impl_value_to_primitive![
+ #[doc = "Try convert this value into a `usize`."]
+ to_usize -> usize,
+ #[doc = "Try convert this value into a `u8`."]
+ to_u8 -> u8,
+ #[doc = "Try convert this value into a `u16`."]
+ to_u16 -> u16,
+ #[doc = "Try convert this value into a `u32`."]
+ to_u32 -> u32,
+ #[doc = "Try convert this value into a `u64`."]
+ to_u64 -> u64,
+ #[doc = "Try convert this value into a `isize`."]
+ to_isize -> isize,
+ #[doc = "Try convert this value into a `i8`."]
+ to_i8 -> i8,
+ #[doc = "Try convert this value into a `i16`."]
+ to_i16 -> i16,
+ #[doc = "Try convert this value into a `i32`."]
+ to_i32 -> i32,
+ #[doc = "Try convert this value into a `i64`."]
+ to_i64 -> i64,
+ #[doc = "Try convert this value into a `f32`."]
+ to_f32 -> f32,
+ #[doc = "Try convert this value into a `f64`."]
+ to_f64 -> f64,
+ #[doc = "Try convert this value into a `char`."]
+ to_char -> char,
+ #[doc = "Try convert this value into a `bool`."]
+ to_bool -> bool,
+];
+
+impl<'v> Value<'v> {
+ /// Try convert this value into an error.
+ #[cfg(feature = "kv_unstable_std")]
+ pub fn to_error(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ self.inner.to_error()
+ }
+
+ /// Try convert this value into a borrowed string.
+ pub fn to_borrowed_str(&self) -> Option<&str> {
+ self.inner.to_borrowed_str()
+ }
+}
+
+#[cfg(feature = "std")]
+mod std_support {
+ use super::*;
+
+ use std::borrow::Cow;
+
+ impl<T> ToValue for Box<T>
+ where
+ T: ToValue + ?Sized,
+ {
+ fn to_value(&self) -> Value {
+ (**self).to_value()
+ }
+ }
+
+ impl ToValue for String {
+ fn to_value(&self) -> Value {
+ Value::from(&**self)
+ }
+ }
+
+ impl<'v> ToValue for Cow<'v, str> {
+ fn to_value(&self) -> Value {
+ Value::from(&**self)
+ }
+ }
+
+ impl<'v> Value<'v> {
+ /// Try convert this value into a string.
+ pub fn to_str(&self) -> Option<Cow<str>> {
+ self.inner.to_str()
+ }
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+
+ pub(crate) use super::value_bag::test::Token;
+
+ impl<'v> Value<'v> {
+ pub(crate) fn to_token(&self) -> Token {
+ self.inner.to_token()
+ }
+ }
+
+ fn unsigned() -> impl Iterator<Item = Value<'static>> {
+ vec![
+ Value::from(8u8),
+ Value::from(16u16),
+ Value::from(32u32),
+ Value::from(64u64),
+ Value::from(1usize),
+ ]
+ .into_iter()
+ }
+
+ fn signed() -> impl Iterator<Item = Value<'static>> {
+ vec![
+ Value::from(-8i8),
+ Value::from(-16i16),
+ Value::from(-32i32),
+ Value::from(-64i64),
+ Value::from(-1isize),
+ ]
+ .into_iter()
+ }
+
+ fn float() -> impl Iterator<Item = Value<'static>> {
+ vec![Value::from(32.32f32), Value::from(64.64f64)].into_iter()
+ }
+
+ fn bool() -> impl Iterator<Item = Value<'static>> {
+ vec![Value::from(true), Value::from(false)].into_iter()
+ }
+
+ fn str() -> impl Iterator<Item = Value<'static>> {
+ vec![Value::from("a string"), Value::from("a loong string")].into_iter()
+ }
+
+ fn char() -> impl Iterator<Item = Value<'static>> {
+ vec![Value::from('a'), Value::from('⛰')].into_iter()
+ }
+
+ #[test]
+ fn test_capture_fmt() {
+ assert_eq!(Some(42u64), Value::capture_display(&42).to_u64());
+ assert_eq!(Some(42u64), Value::capture_debug(&42).to_u64());
+
+ assert!(Value::from_display(&42).to_u64().is_none());
+ assert!(Value::from_debug(&42).to_u64().is_none());
+ }
+
+ #[cfg(feature = "kv_unstable_std")]
+ #[test]
+ fn test_capture_error() {
+ let err = std::io::Error::from(std::io::ErrorKind::Other);
+
+ assert!(Value::capture_error(&err).to_error().is_some());
+ assert!(Value::from_dyn_error(&err).to_error().is_some());
+ }
+
+ #[cfg(feature = "kv_unstable_serde")]
+ #[test]
+ fn test_capture_serde() {
+ assert_eq!(Some(42u64), Value::capture_serde(&42).to_u64());
+
+ assert_eq!(Some(42u64), Value::from_serde(&42).to_u64());
+ }
+
+ #[cfg(feature = "kv_unstable_sval")]
+ #[test]
+ fn test_capture_sval() {
+ assert_eq!(Some(42u64), Value::capture_sval(&42).to_u64());
+
+ assert_eq!(Some(42u64), Value::from_sval(&42).to_u64());
+ }
+
+ #[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!("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::<bool>.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!(
+ "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::<bool>.to_value().to_token(), Token::None);
+ }
+
+ #[test]
+ fn test_to_number() {
+ for v in unsigned().chain(signed()).chain(float()) {
+ assert!(v.to_u8().is_some());
+ assert!(v.to_u16().is_some());
+ assert!(v.to_u32().is_some());
+ assert!(v.to_u64().is_some());
+ assert!(v.to_usize().is_some());
+
+ assert!(v.to_i8().is_some());
+ assert!(v.to_i16().is_some());
+ assert!(v.to_i32().is_some());
+ assert!(v.to_i64().is_some());
+ assert!(v.to_isize().is_some());
+
+ assert!(v.to_f32().is_some());
+ assert!(v.to_f64().is_some());
+ }
+
+ for v in bool().chain(str()).chain(char()) {
+ assert!(v.to_u8().is_none());
+ assert!(v.to_u16().is_none());
+ assert!(v.to_u32().is_none());
+ assert!(v.to_u64().is_none());
+
+ assert!(v.to_i8().is_none());
+ assert!(v.to_i16().is_none());
+ assert!(v.to_i32().is_none());
+ assert!(v.to_i64().is_none());
+
+ assert!(v.to_f32().is_none());
+ assert!(v.to_f64().is_none());
+ }
+ }
+
+ #[test]
+ fn test_to_str() {
+ for v in str() {
+ assert!(v.to_borrowed_str().is_some());
+
+ #[cfg(feature = "std")]
+ assert!(v.to_str().is_some());
+ }
+
+ let short_lived = String::from("short lived");
+ let v = Value::from(&*short_lived);
+
+ assert!(v.to_borrowed_str().is_some());
+
+ #[cfg(feature = "std")]
+ assert!(v.to_str().is_some());
+
+ for v in unsigned().chain(signed()).chain(float()).chain(bool()) {
+ assert!(v.to_borrowed_str().is_none());
+
+ #[cfg(feature = "std")]
+ assert!(v.to_str().is_none());
+ }
+ }
+
+ #[test]
+ fn test_to_bool() {
+ for v in bool() {
+ assert!(v.to_bool().is_some());
+ }
+
+ for v in unsigned()
+ .chain(signed())
+ .chain(float())
+ .chain(str())
+ .chain(char())
+ {
+ assert!(v.to_bool().is_none());
+ }
+ }
+
+ #[test]
+ fn test_to_char() {
+ for v in char() {
+ assert!(v.to_char().is_some());
+ }
+
+ for v in unsigned()
+ .chain(signed())
+ .chain(float())
+ .chain(str())
+ .chain(bool())
+ {
+ assert!(v.to_char().is_none());
+ }
+ }
+}
diff --git a/src/kv/value/fill.rs b/src/kv/value/fill.rs
deleted file mode 100644
index f34ba31d5..000000000
--- a/src/kv/value/fill.rs
+++ /dev/null
@@ -1,164 +0,0 @@
-//! Lazy value initialization.
-
-use std::fmt;
-
-use super::internal::{Inner, Visitor};
-use super::{Error, Value};
-
-impl<'v> Value<'v> {
- /// Get a value from a fillable slot.
- pub fn from_fill<T>(value: &'v T) -> Self
- where
- T: Fill,
- {
- Value {
- inner: Inner::Fill(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<F>(&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<T>(&mut self, value: T) -> Result<(), Error>
- where
- T: Into<Value<'f>>,
- {
- 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)),
- )
- }
-}
diff --git a/src/kv/value/impls.rs b/src/kv/value/impls.rs
deleted file mode 100644
index 506128bf2..000000000
--- a/src/kv/value/impls.rs
+++ /dev/null
@@ -1,141 +0,0 @@
-//! 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};
-
-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<fmt::Arguments<'v>> 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<T> ToValue for Option<T>
-where
- T: ToValue,
-{
- fn to_value(&self) -> Value {
- match *self {
- Some(ref value) => value.to_value(),
- None => Value::from_primitive(Primitive::None),
- }
- }
-}
-
-macro_rules! impl_to_value_primitive {
- ($($into_ty:ty,)*) => {
- $(
- 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)
- }
- }
- )*
- };
-}
-
-impl_to_value_primitive![usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64, char, bool,];
-
-#[cfg(feature = "std")]
-mod std_support {
- use super::*;
-
- use std::borrow::Cow;
-
- impl<T> ToValue for Box<T>
- 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::<bool>.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::<bool>.to_value().to_token(), Token::None);
- }
-}
diff --git a/src/kv/value/internal/cast/mod.rs b/src/kv/value/internal/cast/mod.rs
deleted file mode 100644
index ec6a22379..000000000
--- a/src/kv/value/internal/cast/mod.rs
+++ /dev/null
@@ -1,425 +0,0 @@
-//! 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::fmt;
-
-use super::{Inner, Primitive, Visitor};
-use crate::kv::value::{Error, Value};
-
-mod primitive;
-
-/// Attempt to capture a primitive from some generic value.
-///
-/// If the value is a primitive type, then cast it here, avoiding needing to erase its value
-/// This makes `Value`s produced by `Value::from_*` more useful
-pub(super) fn try_from_primitive<'v, T: 'static>(value: &'v T) -> Option<Value<'v>> {
- primitive::from_any(value).map(|primitive| Value {
- inner: Inner::Primitive(primitive),
- })
-}
-
-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<usize> {
- 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<u8> {
- 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<u16> {
- 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<u32> {
- 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<u64> {
- 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<isize> {
- 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<i8> {
- 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<i16> {
- 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<i32> {
- 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<i64> {
- 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<f32> {
- 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<f64> {
- 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<bool> {
- 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<char> {
- 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(())
- }
-
- #[cfg(feature = "std")]
- fn str(&mut self, s: &str) -> Result<(), Error> {
- self.0 = Cast::String(s.to_owned());
- Ok(())
- }
-
- #[cfg(not(feature = "std"))]
- fn str(&mut self, _: &str) -> Result<(), Error> {
- Ok(())
- }
-
- fn borrowed_str(&mut self, v: &'v str) -> Result<(), Error> {
- self.0 = Cast::Primitive(Primitive::Str(v));
- 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(())
- }
- }
-
- if let Inner::Primitive(value) = self {
- Cast::Primitive(value)
- } 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<u64> {
- 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<i64> {
- 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<f64> {
- 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<char> {
- if let Primitive::Char(value) = self {
- Some(value)
- } else {
- None
- }
- }
-
- fn into_bool(self) -> Option<bool> {
- if let Primitive::Bool(value) = self {
- Some(value)
- } else {
- None
- }
- }
-}
-
-#[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<Cow<str>> {
- self.inner.cast().into_str()
- }
- }
-
- impl<'v> Cast<'v> {
- pub(super) fn into_str(self) -> Option<Cow<'v, str>> {
- 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"));
- }
-}
diff --git a/src/kv/value/internal/cast/primitive.rs b/src/kv/value/internal/cast/primitive.rs
deleted file mode 100644
index c306e66f6..000000000
--- a/src/kv/value/internal/cast/primitive.rs
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
-This module generates code to try efficiently convert some arbitrary `T: 'static` into
-a `Primitive`. It's used by both the `build.rs` script and by the source itself. There
-are currently two implementations here:
-
-- When the compiler version is less than `1.46.0` we check type ids at runtime. This
-means generating a pre-sorted list of type ids at compile time using the `build.rs`
-and matching them at runtime.
-- When the compiler version is at least `1.46.0` we use const evaluation to check type ids
-at compile time. There's no generated code from `build.rs` involved.
-
-In the future when `min_specialization` is stabilized we could use it instead and avoid needing
-the `'static` bound altogether.
-*/
-
-// Use a build-time generated set of type ids to match a type with a conversion fn
-#[cfg(srcbuild)]
-pub(super) fn from_any<'v>(
- value: &'v (dyn std::any::Any + 'static),
-) -> Option<crate::kv::value::internal::Primitive<'v>> {
- // The set of type ids that map to primitives are generated at build-time
- // by the contents of `sorted_type_ids.expr`. These type ids are pre-sorted
- // so that they can be searched efficiently. See the `sorted_type_ids.expr.rs`
- // file for the set of types that appear in this list
- let type_ids = include!(concat!(env!("OUT_DIR"), "/into_primitive.rs"));
-
- if let Ok(i) = type_ids.binary_search_by_key(&value.type_id(), |&(k, _)| k) {
- Some((type_ids[i].1)(value))
- } else {
- None
- }
-}
-
-// When the `src_build` config is not set then we're in the build script
-#[cfg(not(srcbuild))]
-#[allow(dead_code)]
-pub fn generate() {
- use std::path::Path;
- use std::{env, fs};
-
- macro_rules! type_ids {
- ($($ty:ty,)*) => {
- [
- $(
- (
- std::any::TypeId::of::<$ty>(),
- stringify!(
- (
- std::any::TypeId::of::<$ty>(),
- (|value| unsafe {
- debug_assert_eq!(value.type_id(), std::any::TypeId::of::<$ty>());
-
- // SAFETY: We verify the value is $ty before casting
- let value = *(value as *const dyn std::any::Any as *const $ty);
- crate::kv::value::internal::Primitive::from(value)
- }) as for<'a> fn(&'a (dyn std::any::Any + 'static)) -> crate::kv::value::internal::Primitive<'a>
- )
- )
- ),
- )*
- $(
- (
- std::any::TypeId::of::<Option<$ty>>(),
- stringify!(
- (
- std::any::TypeId::of::<Option<$ty>>(),
- (|value| unsafe {
- debug_assert_eq!(value.type_id(), std::any::TypeId::of::<Option<$ty>>());
-
- // SAFETY: We verify the value is Option<$ty> before casting
- let value = *(value as *const dyn std::any::Any as *const Option<$ty>);
- if let Some(value) = value {
- crate::kv::value::internal::Primitive::from(value)
- } else {
- crate::kv::value::internal::Primitive::None
- }
- }) as for<'a> fn(&'a (dyn std::any::Any + 'static)) -> crate::kv::value::internal::Primitive<'a>
- )
- )
- ),
- )*
- ]
- };
- }
-
- // NOTE: The types here *must* match the ones used above when `const_type_id` is available
- let mut type_ids = type_ids![
- usize,
- u8,
- u16,
- u32,
- u64,
- isize,
- i8,
- i16,
- i32,
- i64,
- f32,
- f64,
- char,
- bool,
- &'static str,
- ];
-
- type_ids.sort_by_key(|&(k, _)| k);
-
- let mut ordered_type_ids_expr = String::new();
-
- ordered_type_ids_expr.push('[');
-
- for (_, v) in &type_ids {
- ordered_type_ids_expr.push_str(v);
- ordered_type_ids_expr.push(',');
- }
-
- ordered_type_ids_expr.push(']');
-
- let path = Path::new(&env::var_os("OUT_DIR").unwrap()).join("into_primitive.rs");
- fs::write(path, ordered_type_ids_expr).unwrap();
-}
diff --git a/src/kv/value/internal/fmt.rs b/src/kv/value/internal/fmt.rs
deleted file mode 100644
index bde703c20..000000000
--- a/src/kv/value/internal/fmt.rs
+++ /dev/null
@@ -1,315 +0,0 @@
-//! 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::{cast, Inner, Visitor};
-use crate::kv;
-use crate::kv::value::{Error, Slot, ToValue};
-
-impl<'v> kv::Value<'v> {
- /// Get a value from a debuggable type.
- ///
- /// This method will attempt to capture the given value as a well-known primitive
- /// before resorting to using its `Debug` implementation.
- pub fn capture_debug<T>(value: &'v T) -> Self
- where
- T: fmt::Debug + 'static,
- {
- cast::try_from_primitive(value).unwrap_or(kv::Value {
- inner: Inner::Debug(value),
- })
- }
-
- /// Get a value from a debuggable type.
- pub fn from_debug<T>(value: &'v T) -> Self
- where
- T: fmt::Debug,
- {
- kv::Value {
- inner: Inner::Debug(value),
- }
- }
-
- /// Get a value from a displayable type.
- ///
- /// This method will attempt to capture the given value as a well-known primitive
- /// before resorting to using its `Display` implementation.
- pub fn capture_display<T>(value: &'v T) -> Self
- where
- T: fmt::Display + 'static,
- {
- cast::try_from_primitive(value).unwrap_or(kv::Value {
- inner: Inner::Display(value),
- })
- }
-
- /// Get a value from a displayable type.
- pub fn from_display<T>(value: &'v T) -> Self
- where
- T: fmt::Display,
- {
- kv::Value {
- inner: Inner::Display(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<T>(&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<T>(&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(())
- }
-}
-
-impl<'v> ToValue for dyn fmt::Debug + 'v {
- fn to_value(&self) -> kv::Value {
- kv::Value::from(self)
- }
-}
-
-impl<'v> ToValue for dyn fmt::Display + 'v {
- fn to_value(&self) -> kv::Value {
- kv::Value::from(self)
- }
-}
-
-impl<'v> From<&'v (dyn fmt::Debug)> for kv::Value<'v> {
- fn from(value: &'v (dyn fmt::Debug)) -> kv::Value<'v> {
- kv::Value {
- inner: Inner::Debug(value),
- }
- }
-}
-
-impl<'v> From<&'v (dyn fmt::Display)> for kv::Value<'v> {
- fn from(value: &'v (dyn fmt::Display)) -> kv::Value<'v> {
- kv::Value {
- inner: Inner::Display(value),
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use kv::value::test::Token;
-
- use crate::kv::value::ToValue;
-
- #[test]
- fn fmt_capture() {
- assert_eq!(kv::Value::capture_debug(&1u16).to_token(), Token::U64(1));
- assert_eq!(kv::Value::capture_display(&1u16).to_token(), Token::U64(1));
-
- assert_eq!(
- kv::Value::capture_debug(&Some(1u16)).to_token(),
- Token::U64(1)
- );
- }
-
- #[test]
- fn fmt_cast() {
- assert_eq!(
- 42u32,
- kv::Value::capture_debug(&42u64)
- .to_u32()
- .expect("invalid value")
- );
-
- assert_eq!(
- "a string",
- kv::Value::capture_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()),);
- }
-}
diff --git a/src/kv/value/internal/mod.rs b/src/kv/value/internal/mod.rs
deleted file mode 100644
index 4acbe683c..000000000
--- a/src/kv/value/internal/mod.rs
+++ /dev/null
@@ -1,210 +0,0 @@
-//! 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 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(&'v (dyn Fill)),
- /// A debuggable value.
- Debug(&'v (dyn fmt::Debug)),
- /// A displayable value.
- Display(&'v (dyn fmt::Display)),
-
- #[cfg(feature = "kv_unstable_sval")]
- /// A structured value from `sval`.
- Sval(&'v (dyn sval::Value)),
-}
-
-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::Debug(value) => visitor.debug(value),
- Inner::Display(value) => visitor.display(value),
-
- Inner::Fill(value) => value.fill(&mut Slot::new(visitor)),
-
- #[cfg(feature = "kv_unstable_sval")]
- Inner::Sval(value) => visitor.sval(value),
- }
- }
-}
-
-/// 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<u8> for Primitive<'v> {
- #[inline]
- fn from(v: u8) -> Self {
- Primitive::Unsigned(v as u64)
- }
-}
-
-impl<'v> From<u16> for Primitive<'v> {
- #[inline]
- fn from(v: u16) -> Self {
- Primitive::Unsigned(v as u64)
- }
-}
-
-impl<'v> From<u32> for Primitive<'v> {
- #[inline]
- fn from(v: u32) -> Self {
- Primitive::Unsigned(v as u64)
- }
-}
-
-impl<'v> From<u64> for Primitive<'v> {
- #[inline]
- fn from(v: u64) -> Self {
- Primitive::Unsigned(v)
- }
-}
-
-impl<'v> From<usize> for Primitive<'v> {
- #[inline]
- fn from(v: usize) -> Self {
- Primitive::Unsigned(v as u64)
- }
-}
-
-impl<'v> From<i8> for Primitive<'v> {
- #[inline]
- fn from(v: i8) -> Self {
- Primitive::Signed(v as i64)
- }
-}
-
-impl<'v> From<i16> for Primitive<'v> {
- #[inline]
- fn from(v: i16) -> Self {
- Primitive::Signed(v as i64)
- }
-}
-
-impl<'v> From<i32> for Primitive<'v> {
- #[inline]
- fn from(v: i32) -> Self {
- Primitive::Signed(v as i64)
- }
-}
-
-impl<'v> From<i64> for Primitive<'v> {
- #[inline]
- fn from(v: i64) -> Self {
- Primitive::Signed(v)
- }
-}
-
-impl<'v> From<isize> for Primitive<'v> {
- #[inline]
- fn from(v: isize) -> Self {
- Primitive::Signed(v as i64)
- }
-}
-
-impl<'v> From<f32> for Primitive<'v> {
- #[inline]
- fn from(v: f32) -> Self {
- Primitive::Float(v as f64)
- }
-}
-
-impl<'v> From<f64> for Primitive<'v> {
- #[inline]
- fn from(v: f64) -> Self {
- Primitive::Float(v)
- }
-}
-
-impl<'v> From<bool> for Primitive<'v> {
- #[inline]
- fn from(v: bool) -> Self {
- Primitive::Bool(v)
- }
-}
-
-impl<'v> From<char> for Primitive<'v> {
- #[inline]
- fn from(v: char) -> Self {
- Primitive::Char(v)
- }
-}
-
-impl<'v> From<&'v str> for Primitive<'v> {
- #[inline]
- fn from(v: &'v str) -> Self {
- Primitive::Str(v)
- }
-}
-
-impl<'v> From<fmt::Arguments<'v>> for Primitive<'v> {
- #[inline]
- fn from(v: fmt::Arguments<'v>) -> Self {
- Primitive::Fmt(v)
- }
-}
diff --git a/src/kv/value/internal/sval.rs b/src/kv/value/internal/sval.rs
deleted file mode 100644
index 252efd152..000000000
--- a/src/kv/value/internal/sval.rs
+++ /dev/null
@@ -1,252 +0,0 @@
-//! 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::{self, Cast};
-use super::{Inner, Primitive, Visitor};
-use crate::kv;
-use crate::kv::value::{Error, Slot, ToValue};
-
-impl<'v> kv::Value<'v> {
- /// Get a value from a structured type.
- ///
- /// This method will attempt to capture the given value as a well-known primitive
- /// before resorting to using its `Value` implementation.
- pub fn capture_sval<T>(value: &'v T) -> Self
- where
- T: sval::Value + 'static,
- {
- cast::try_from_primitive(value).unwrap_or(kv::Value {
- inner: Inner::Sval(value),
- })
- }
-
- /// Get a value from a structured type.
- pub fn from_sval<T>(value: &'v T) -> Self
- where
- T: sval::Value,
- {
- kv::Value {
- inner: Inner::Sval(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<T>(&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(())
- }
-}
-
-impl<'v> ToValue for dyn sval::Value + 'v {
- fn to_value(&self) -> kv::Value {
- kv::Value::from(self)
- }
-}
-
-impl<'v> From<&'v (dyn sval::Value)> for kv::Value<'v> {
- fn from(value: &'v (dyn sval::Value)) -> kv::Value<'v> {
- kv::Value {
- inner: Inner::Sval(value),
- }
- }
-}
-
-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 sval_capture() {
- assert_eq!(kv::Value::capture_sval(&42u64).to_token(), Token::U64(42));
- }
-
- #[test]
- fn sval_cast() {
- assert_eq!(
- 42u32,
- kv::Value::capture_sval(&42u64)
- .to_u32()
- .expect("invalid value")
- );
-
- assert_eq!(
- "a string",
- kv::Value::capture_sval(&"a string")
- .to_borrowed_str()
- .expect("invalid value")
- );
-
- #[cfg(feature = "std")]
- assert_eq!(
- "a string",
- kv::Value::capture_sval(&"a string")
- .to_str()
- .expect("invalid value")
- );
- }
-
- #[test]
- fn 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_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)),
- );
- }
-
- #[cfg(feature = "std")]
- mod std_support {
- use super::*;
-
- #[test]
- fn sval_cast() {
- assert_eq!(
- "a string",
- kv::Value::capture_sval(&"a string".to_owned())
- .to_str()
- .expect("invalid value")
- );
- }
- }
-}
diff --git a/src/kv/value/mod.rs b/src/kv/value/mod.rs
deleted file mode 100644
index 8d8282624..000000000
--- a/src/kv/value/mod.rs
+++ /dev/null
@@ -1,180 +0,0 @@
-//! 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.
-///
-/// # Capturing values
-///
-/// There are a few ways to capture a value:
-///
-/// - Using the `Value::capture_*` methods.
-/// - Using the `Value::from_*` methods.
-/// - Using the `ToValue` trait.
-/// - Using the standard `From` trait.
-/// - Using the `Fill` API.
-///
-/// ## Using the `Value::capture_*` methods
-///
-/// `Value` offers a few constructor methods that capture values of different kinds.
-/// These methods require a `T: 'static` to support downcasting.
-///
-/// ```
-/// use log::kv::Value;
-///
-/// let value = Value::capture_debug(&42i32);
-///
-/// assert_eq!(Some(42), value.to_i32());
-/// ```
-///
-/// ## Using the `Value::from_*` methods
-///
-/// `Value` offers a few constructor methods that capture values of different kinds.
-/// These methods don't require `T: 'static`, but can't support downcasting.
-///
-/// ```
-/// use log::kv::Value;
-///
-/// let value = Value::from_debug(&42i32);
-///
-/// assert_eq!(None, value.to_i32());
-/// ```
-///
-/// ## Using the `ToValue` trait
-///
-/// The `ToValue` trait can be used to capture values generically.
-/// It's the bound used by `Source`.
-///
-/// ```
-/// # use log::kv::ToValue;
-/// let value = 42i32.to_value();
-///
-/// assert_eq!(Some(42), value.to_i32());
-/// ```
-///
-/// ```
-/// # use std::fmt::Debug;
-/// use log::kv::ToValue;
-///
-/// let value = (&42i32 as &dyn Debug).to_value();
-///
-/// assert_eq!(None, value.to_i32());
-/// ```
-///
-/// ## Using the standard `From` trait
-///
-/// Standard types that implement `ToValue` also implement `From`.
-///
-/// ```
-/// use log::kv::Value;
-///
-/// let value = Value::from(42i32);
-///
-/// assert_eq!(Some(42), value.to_i32());
-/// ```
-///
-/// ```
-/// # use std::fmt::Debug;
-/// use log::kv::Value;
-///
-/// let value = Value::from(&42i32 as &dyn Debug);
-///
-/// assert_eq!(None, value.to_i32());
-/// ```
-///
-/// ## Using the `Fill` API
-///
-/// The `Fill` trait is a way to bridge APIs that may not be directly
-/// compatible with other constructor methods.
-///
-/// ```
-/// use log::kv::value::{Value, Slot, Fill, Error};
-///
-/// struct FillSigned;
-///
-/// impl Fill for FillSigned {
-/// fn fill(&self, slot: &mut Slot) -> Result<(), Error> {
-/// slot.fill_any(42i32)
-/// }
-/// }
-///
-/// let value = Value::from_fill(&FillSigned);
-///
-/// assert_eq!(Some(42), value.to_i32());
-/// ```
-///
-/// ```
-/// # use std::fmt::Debug;
-/// use log::kv::value::{Value, Slot, Fill, Error};
-///
-/// struct FillDebug;
-///
-/// impl Fill for FillDebug {
-/// fn fill(&self, slot: &mut Slot) -> Result<(), Error> {
-/// slot.fill_debug(&42i32 as &dyn Debug)
-/// }
-/// }
-///
-/// let value = Value::from_fill(&FillDebug);
-///
-/// assert_eq!(None, value.to_i32());
-/// ```
-pub struct Value<'v> {
- inner: Inner<'v>,
-}
-
-impl<'v> Value<'v> {
- /// Get a value from a type implementing `ToValue`.
- pub fn from_any<T>(value: &'v T) -> Self
- where
- T: ToValue,
- {
- value.to_value()
- }
-
- /// Get a value from an internal primitive.
- fn from_primitive<T>(value: T) -> Self
- where
- T: Into<Primitive<'v>>,
- {
- 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)
- }
-}
|
diff --git a/src/kv/value/test.rs b/src/kv/value/test.rs
deleted file mode 100644
index ab5f8075e..000000000
--- a/src/kv/value/test.rs
+++ /dev/null
@@ -1,81 +0,0 @@
-// 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<Token>);
-
- 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()
- }
-}
|
Support converting Errors into Values
There are some design decisions to make around `dyn Error` vs `dyn Error + 'static`, but I've been looking at providing a proper downcasting API too.
|
2020-11-11T03:25:19Z
|
0.4
|
06c306fa8f4d41a722f8759f03effd4185eee3ee
|
|
rust-lang/log
| 370
|
rust-lang__log-370
|
[
"369"
] |
87fc152d40f06623e109ead03cba0431da0e7f73
|
diff --git a/src/macros.rs b/src/macros.rs
index 23378fc5e..f628664b7 100644
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -47,7 +47,7 @@ macro_rules! log {
#[doc(hidden)]
macro_rules! log_impl {
// End of macro input
- (target: $target:expr, $lvl:expr, ($message:expr)) => {
+ (target: $target:expr, $lvl:expr, ($message:expr)) => {{
let lvl = $lvl;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
$crate::__private_api_log_lit(
@@ -56,9 +56,8 @@ macro_rules! log_impl {
&($target, __log_module_path!(), __log_file!(), __log_line!()),
);
}
- };
-
- (target: $target:expr, $lvl:expr, ($($arg:expr),*)) => {
+ }};
+ (target: $target:expr, $lvl:expr, ($($arg:expr),*)) => {{
let lvl = $lvl;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
$crate::__private_api_log(
@@ -68,10 +67,10 @@ macro_rules! log_impl {
None,
);
}
- };
+ }};
// // Trailing k-v pairs containing no trailing comma
- (target: $target:expr, $lvl:expr, ($($arg:expr),*) { $($key:ident : $value:expr),* }) => {
+ (target: $target:expr, $lvl:expr, ($($arg:expr),*) { $($key:ident : $value:expr),* }) => {{
let lvl = log::Level::Info;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
$crate::__private_api_log(
@@ -81,7 +80,7 @@ macro_rules! log_impl {
Some(&[$((__log_stringify!($key), &$value)),*])
);
}
- };
+ }};
// Trailing k-v pairs with trailing comma
(target: $target:expr, $lvl:expr, ($($e:expr),*) { $($key:ident : $value:expr,)* }) => {
|
diff --git a/tests/macros.rs b/tests/macros.rs
index f41c52ed3..34c89811f 100644
--- a/tests/macros.rs
+++ b/tests/macros.rs
@@ -7,6 +7,11 @@ fn base() {
info!("hello",);
}
+#[test]
+fn base_expr_context() {
+ let _ = info!("hello");
+}
+
#[test]
fn with_args() {
info!("hello {}", "cats");
@@ -14,6 +19,13 @@ fn with_args() {
info!("hello {}", "cats",);
}
+#[test]
+fn with_args_expr_context() {
+ match "cats" {
+ cats => info!("hello {}", cats),
+ };
+}
+
#[test]
fn kv() {
info!("hello {}", "cats", {
@@ -21,3 +33,13 @@ fn kv() {
cat_2: "nori",
});
}
+
+#[test]
+fn kv_expr_context() {
+ match "chashu" {
+ cat_1 => info!("hello {}", "cats", {
+ cat_1: cat_1,
+ cat_2: "nori",
+ }),
+ };
+}
|
0.4.9 release seems to break tokio (which depends on log)
You can see an example of this here: https://github.com/alex/otp-cop/pull/374/checks?check_run_id=349720268
I didn't see a mention of breaking changes (besides MSRV) in the CHANGELOG, so I'm filing this here. Let me know if this should be filed on tokio instead though!
|
I am receiving similar errors trying to install cargo-make.
```
Compiling cargo-make v0.24.1
error: macro expansion ignores token `if` and any following
--> <::log::macros::log_impl macros>:13:23
|
13 | let lvl = $ lvl ; if lvl <= $ crate :: STATIC_MAX_LEVEL && lvl <= $ crate
| ^^
|
::: /usr/local/cargo/registry/src/github.com-1ecc6299db9ec823/cargo-make-0.24.1/src/lib/cache.rs:106:47
|
106 | ... Err(error) => info!(
| _____________________________________-
107 | | ... "Error while writing to cache file: {:#?}, error: {:#?}",
108 | | ... &file_name, error
109 | | ... ),
| | -
| | |
| |_______________________caused by the macro expansion here
| help: you might be missing a semicolon here: `;`
|
= note: the usage of `log_impl!` is likely invalid in expression context
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
...
```
It seems to break [`relevant`](https://github.com/omni-viral/relevant) and [`gfx-backend-vulkan`](https://github.com/gfx-rs/gfx/tree/master/src/backend/vulkan) too.
This also breaks [`goblin`](https://github.com/m4b/goblin)
I've yanked the 0.4.9 release.
@KodrAus It looks like all of the code blocks in the log_impl macro need to be contained in a block - how did CI pass after the KV stuff landed?
Install cargo-make is working again, thank you for the very quick fix!
@sfackler Hm that's a good question... I'll check this out now.
Ok, it looks like with our macro tests being brand new we didn't have coverage for the macros in expression context so CI didn't pick this up. I also totally missed this when reviewing the original implementation.
I'm putting together a PR now to fix this up.
|
2019-12-16T00:11:28Z
|
0.4
|
06c306fa8f4d41a722f8759f03effd4185eee3ee
|
rust-lang/log
| 245
|
rust-lang__log-245
|
[
"243"
] |
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
|
diff --git a/src/lib.rs b/src/lib.rs
index feea3d326..50423604a 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -164,10 +164,7 @@
//! static LOGGER: SimpleLogger = SimpleLogger;
//!
//! pub fn init() -> Result<(), SetLoggerError> {
-//! log::set_logger(|max_level| {
-//! max_level.set(LevelFilter::Info);
-//! &LOGGER
-//! })
+//! log::set_logger(&LOGGER)
//! }
//! ```
//!
@@ -191,10 +188,7 @@
//! # fn main() {}
//! # #[cfg(feature = "std")]
//! pub fn init() -> Result<(), SetLoggerError> {
-//! log::set_boxed_logger(|max_level| {
-//! max_level.set(LevelFilter::Info);
-//! Box::new(SimpleLogger)
-//! })
+//! log::set_boxed_logger(Box::new(SimpleLogger))
//! }
//! ```
//!
@@ -954,33 +948,12 @@ impl Log for NopLogger {
fn flush(&self) {}
}
-/// A token providing read and write access to the global maximum log level
-/// filter.
+/// Sets the global maximum log level.
///
-/// The maximum log level is used as an optimization to avoid evaluating log
-/// messages that will be ignored by the logger. Any message with a level
-/// higher than the maximum log level filter will be ignored. A logger should
-/// make sure to keep the maximum log level filter in sync with its current
-/// configuration.
-#[allow(missing_copy_implementations)]
-pub struct MaxLevelFilter(());
-
-impl fmt::Debug for MaxLevelFilter {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- write!(fmt, "MaxLevelFilter")
- }
-}
-
-impl MaxLevelFilter {
- /// Gets the current maximum log level filter.
- pub fn get(&self) -> LevelFilter {
- max_level()
- }
-
- /// Sets the maximum log level.
- pub fn set(&self, level: LevelFilter) {
- MAX_LOG_LEVEL_FILTER.store(level as usize, Ordering::SeqCst)
- }
+/// 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.
@@ -1015,19 +988,12 @@ pub fn max_level() -> LevelFilter {
///
/// [`set_logger`]: fn.set_logger.html
#[cfg(feature = "std")]
-pub fn set_boxed_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
-where
- M: FnOnce(MaxLevelFilter) -> Box<Log>,
-{
- unsafe { set_logger(|max_level| &*Box::into_raw(make_logger(max_level))) }
+pub fn set_boxed_logger(logger: Box<Log>) -> Result<(), SetLoggerError> {
+ set_logger_inner(|| unsafe { &*Box::into_raw(logger) })
}
/// Sets the global logger to a `&'static Log`.
///
-/// The `make_logger` closure is passed a `MaxLevelFilter` object, which the
-/// logger should use to keep the global maximum log level in sync with the
-/// highest log level that the logger will not ignore.
-///
/// 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.
///
@@ -1065,26 +1031,28 @@ where
/// }
///
/// # fn main(){
-/// log::set_logger(|max_log_level| {
-/// max_log_level.set(LevelFilter::Info);
-/// &MY_LOGGER
-/// }).unwrap();
+/// log::set_logger(&MY_LOGGER).unwrap();
+/// log::set_max_level(LevelFilter::Info);
///
/// info!("hello log");
/// warn!("warning");
/// error!("oops");
/// # }
/// ```
-pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
+pub fn set_logger(logger: &'static Log) -> Result<(), SetLoggerError> {
+ set_logger_inner(|| logger)
+}
+
+fn set_logger_inner<F>(make_logger: F) -> Result<(), SetLoggerError>
where
- M: FnOnce(MaxLevelFilter) -> &'static Log,
+ F: FnOnce() -> &'static Log
{
unsafe {
if STATE.compare_and_swap(UNINITIALIZED, INITIALIZING, Ordering::SeqCst) != UNINITIALIZED {
return Err(SetLoggerError(()));
}
- LOGGER = make_logger(MaxLevelFilter(()));
+ LOGGER = make_logger();
STATE.store(INITIALIZED, Ordering::SeqCst);
Ok(())
}
|
diff --git a/tests/filters.rs b/tests/filters.rs
index d28fa004e..84449ccfe 100644
--- a/tests/filters.rs
+++ b/tests/filters.rs
@@ -3,20 +3,17 @@ extern crate log;
use std::sync::{Arc, Mutex};
use log::{Level, LevelFilter, Log, Record, Metadata};
-use log::MaxLevelFilter;
-#[cfg(feature = "use_std")]
+#[cfg(feature = "std")]
use log::set_boxed_logger;
-#[cfg(not(feature = "use_std"))]
-fn set_boxed_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
- where M: FnOnce(MaxLevelFilter) -> Box<Log>
-{
- log::set_logger(|x| unsafe { &*Box::into_raw(make_logger(x)) })
+
+#[cfg(not(feature = "std"))]
+fn set_boxed_logger(logger: Box<Log>) -> Result<(), log::SetLoggerError> {
+ log::set_logger(unsafe { &*Box::into_raw(logger) })
}
struct State {
last_log: Mutex<Option<Level>>,
- filter: MaxLevelFilter,
}
struct Logger(Arc<State>);
@@ -33,16 +30,9 @@ impl Log for Logger {
}
fn main() {
- let mut a = None;
- set_boxed_logger(|max| {
- let me = Arc::new(State {
- last_log: Mutex::new(None),
- filter: max,
- });
- a = Some(me.clone());
- Box::new(Logger(me))
- }).unwrap();
- let a = a.unwrap();
+ 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);
@@ -53,7 +43,7 @@ fn main() {
}
fn test(a: &State, filter: LevelFilter) {
- a.filter.set(filter);
+ log::set_max_level(filter);
error!("");
last(&a, t(Level::Error, filter));
warn!("");
@@ -71,7 +61,6 @@ fn test(a: &State, filter: LevelFilter) {
}
fn last(state: &State, expected: Option<Level>) {
- let mut lvl = state.last_log.lock().unwrap();
- assert_eq!(*lvl, expected);
- *lvl = None;
+ let lvl = state.last_log.lock().unwrap().take();
+ assert_eq!(lvl, expected);
}
diff --git a/tests/max_level_features/main.rs b/tests/max_level_features/main.rs
index e2c43f91c..ba5ce1138 100644
--- a/tests/max_level_features/main.rs
+++ b/tests/max_level_features/main.rs
@@ -3,21 +3,18 @@ extern crate log;
use std::sync::{Arc, Mutex};
use log::{Level, LevelFilter, Log, Record, Metadata};
-use log::MaxLevelFilter;
-#[cfg(feature = "use_std")]
+#[cfg(feature = "std")]
use log::set_boxed_logger;
-#[cfg(not(feature = "use_std"))]
-fn set_boxed_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
- where M: FnOnce(MaxLevelFilter) -> Box<Log> {
+#[cfg(not(feature = "std"))]
+fn set_boxed_logger(logger: Box<Log>) -> Result<(), log::SetLoggerError> {
unsafe {
- log::set_logger(|x| &*Box::into_raw(make_logger(x)))
+ log::set_logger(&*Box::into_raw(logger))
}
}
struct State {
last_log: Mutex<Option<Level>>,
- filter: MaxLevelFilter,
}
struct Logger(Arc<State>);
@@ -35,16 +32,9 @@ impl Log for Logger {
}
fn main() {
- let mut a = None;
- set_boxed_logger(|max| {
- let me = Arc::new(State {
- last_log: Mutex::new(None),
- filter: max,
- });
- a = Some(me.clone());
- Box::new(Logger(me))
- }).unwrap();
- let a = a.unwrap();
+ 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);
@@ -55,7 +45,7 @@ fn main() {
}
fn test(a: &State, filter: LevelFilter) {
- a.filter.set(filter);
+ log::set_max_level(filter);
error!("");
last(&a, t(Level::Error, filter));
warn!("");
|
Possibly removing closures from `set_*_logger` functions?
Are the closures still needed any more? (I'm probably missing some historical context).
I could imagine that we don't have closures here but rather just parameters along with a free function that sets the max level (at any time). Although maybe there's a downside to configuring the max log level (globally) at any point in time?
|
The closure-based indirection is there to make sure the active logger is the only thing that can mess with the max log level, yeah. The main downside is that random code could come in and poke the max log level in confusing ways, but maybe that's not enough of an issue that we need to worry about the extra weirdness?
Hm yeah I wouldn't personally be too worried about a downside like that. The handling of races between concurrent initialization is mostly just for safety rather than anything else, I don't think anyone really wants to rely on log's own arbitration. In that sense I'd fine the argument-taking apis a little more ergonomic (no need for an extra closure) and a little more flexible perhaps (update the max log level while the program is running).
> (update the max log level while the program is running)
As the logging implementation, you can already do this by saving off the token and using it later. Removing the closure would allow things other than the logging implementation to do it as well if they wanted to.
Ah true yeah, the maybe it's just ergonomics!
|
2017-12-06T04:54:16Z
|
0.3
|
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
|
rust-lang/log
| 224
|
rust-lang__log-224
|
[
"145"
] |
8af5f3c688461a166a5097c395a5deb6c99a70ed
|
diff --git a/.travis.yml b/.travis.yml
index 226c591c8..6bc0aa9ed 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -13,11 +13,8 @@ script:
- cargo test --verbose
- cargo test --verbose --features serde
- cargo test --verbose --no-default-features
- - cargo test --verbose --manifest-path env/Cargo.toml
- - cargo test --verbose --manifest-path env/Cargo.toml --no-default-features
- cargo run --verbose --manifest-path tests/max_level_features/Cargo.toml
- cargo run --verbose --manifest-path tests/max_level_features/Cargo.toml --release
- - CARGO_TARGET_DIR=target cargo doc --no-deps --manifest-path env/Cargo.toml
after_success:
- travis-cargo --only nightly doc-upload
env:
diff --git a/README.md b/README.md
index 95b789187..6efed34df 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,6 @@ A Rust library providing a lightweight logging *facade*.
[](https://ci.appveyor.com/project/alexcrichton/log)
* [`log` documentation](https://docs.rs/log)
-* [`env_logger` documentation](https://docs.rs/env_logger)
A logging facade provides a single logging API that abstracts over the actual
logging implementation. Libraries can use the logging API provided by this
@@ -50,6 +49,23 @@ pub fn shave_the_yak(yak: &Yak) {
## 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 chose 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/)
+
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
@@ -88,7 +104,7 @@ $ RUST_LOG=info ./main
starting up
```
-See the [`env_logger` documentation](http://rust-lang-nursery.github.io/log/env_logger/)
+See the [`env_logger` documentation](https://docs.rs/env_logger)
for the `RUST_LOG` values that can be used to get log messages with different
levels or filtered to different modules.
diff --git a/appveyor.yml b/appveyor.yml
index 1b24e1e59..b96810233 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -16,4 +16,3 @@ build: false
test_script:
- cargo test --verbose
- cargo test --verbose --features serde
- - cargo test --manifest-path env/Cargo.toml
diff --git a/env/Cargo.toml b/env/Cargo.toml
deleted file mode 100644
index 7e890cbc7..000000000
--- a/env/Cargo.toml
+++ /dev/null
@@ -1,26 +0,0 @@
-[package]
-name = "env_logger"
-version = "0.4.3" # remember to update html_root_url
-authors = ["The Rust Project Developers"]
-license = "MIT/Apache-2.0"
-repository = "https://github.com/rust-lang/log"
-documentation = "https://docs.rs/env_logger"
-homepage = "https://github.com/rust-lang/log"
-description = """
-A logging implementation for `log` which is configured via an environment
-variable.
-"""
-categories = ["development-tools::debugging"]
-keywords = ["logging"]
-publish = false # this branch contains breaking changes
-
-[dependencies]
-log = { version = "0.3", path = ".." }
-regex = { version = "0.2", optional = true }
-
-[[test]]
-name = "regexp_filter"
-harness = false
-
-[features]
-default = ["regex"]
diff --git a/env/LICENSE-APACHE b/env/LICENSE-APACHE
deleted file mode 100644
index 16fe87b06..000000000
--- a/env/LICENSE-APACHE
+++ /dev/null
@@ -1,201 +0,0 @@
- 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.
diff --git a/env/LICENSE-MIT b/env/LICENSE-MIT
deleted file mode 100644
index 39d4bdb5a..000000000
--- a/env/LICENSE-MIT
+++ /dev/null
@@ -1,25 +0,0 @@
-Copyright (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.
diff --git a/env/src/lib.rs b/env/src/lib.rs
deleted file mode 100644
index 696d76675..000000000
--- a/env/src/lib.rs
+++ /dev/null
@@ -1,681 +0,0 @@
-// 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! A logger configured via an environment variable which writes to standard
-//! error.
-//!
-//! ## Example
-//!
-//! ```
-//! #[macro_use] extern crate log;
-//! extern crate env_logger;
-//!
-//! use log::Level;
-//!
-//! fn main() {
-//! env_logger::init();
-//!
-//! debug!("this is a debug {}", "message");
-//! error!("this is printed by default");
-//!
-//! if log_enabled!(Level::Info) {
-//! let x = 3 * 4; // expensive computation
-//! info!("the answer was: {}", x);
-//! }
-//! }
-//! ```
-//!
-//! Assumes the binary is `main`:
-//!
-//! ```{.bash}
-//! $ RUST_LOG=error ./main
-//! ERROR:main: this is printed by default
-//! ```
-//!
-//! ```{.bash}
-//! $ RUST_LOG=info ./main
-//! ERROR:main: this is printed by default
-//! INFO:main: the answer was: 12
-//! ```
-//!
-//! ```{.bash}
-//! $ RUST_LOG=debug ./main
-//! DEBUG:main: this is a debug message
-//! ERROR:main: this is printed by default
-//! INFO:main: the answer was: 12
-//! ```
-//!
-//! You can also set the log level on a per module basis:
-//!
-//! ```{.bash}
-//! $ RUST_LOG=main=info ./main
-//! ERROR:main: this is printed by default
-//! INFO:main: the answer was: 12
-//! ```
-//!
-//! And enable all logging:
-//!
-//! ```{.bash}
-//! $ RUST_LOG=main ./main
-//! DEBUG:main: this is a debug message
-//! ERROR:main: this is printed by default
-//! INFO:main: the answer was: 12
-//! ```
-//!
-//! See the documentation for the log crate for more information about its API.
-//!
-//! ## Enabling logging
-//!
-//! Log levels are controlled on a per-module basis, and by default all logging
-//! is disabled except for `error!`. Logging is controlled via the `RUST_LOG`
-//! environment variable. The value of this environment variable is a
-//! comma-separated list of logging directives. A logging directive is of the
-//! form:
-//!
-//! ```text
-//! path::to::module=level
-//! ```
-//!
-//! The path to the module is rooted in the name of the crate it was compiled
-//! for, so if your program is contained in a file `hello.rs`, for example, to
-//! turn on logging for this file you would use a value of `RUST_LOG=hello`.
-//! Furthermore, this path is a prefix-search, so all modules nested in the
-//! specified module will also have logging enabled.
-//!
-//! The actual `level` is optional to specify. If omitted, all logging will
-//! be enabled. If specified, it must be one of the strings `debug`, `error`,
-//! `info`, `warn`, or `trace`.
-//!
-//! As the log level for a module is optional, the module to enable logging for
-//! is also optional. If only a `level` is provided, then the global log
-//! level for all modules is set to this value.
-//!
-//! Some examples of valid values of `RUST_LOG` are:
-//!
-//! * `hello` turns on all logging for the 'hello' module
-//! * `info` turns on all info logging
-//! * `hello=debug` turns on debug logging for 'hello'
-//! * `hello,std::option` turns on hello, and std's option logging
-//! * `error,hello=warn` turn on global error logging and also warn for hello
-//!
-//! ## Filtering results
-//!
-//! A RUST_LOG directive may include a regex filter. The syntax is to append `/`
-//! followed by a regex. Each message is checked against the regex, and is only
-//! logged if it matches. Note that the matching is done after formatting the
-//! log string but before adding any logging meta-data. There is a single filter
-//! for all modules.
-//!
-//! Some examples:
-//!
-//! * `hello/foo` turns on all logging for the 'hello' module where the log
-//! message includes 'foo'.
-//! * `info/f.o` turns on all info logging where the log message includes 'foo',
-//! 'f1o', 'fao', etc.
-//! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log
-//! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc.
-//! * `error,hello=warn/[0-9] scopes` turn on global error logging and also
-//! warn for hello. In both cases the log message must include a single digit
-//! number followed by 'scopes'.
-
-#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
- html_favicon_url = "http://www.rust-lang.org/favicon.ico",
- html_root_url = "https://docs.rs/env_logger/0.4.3")]
-#![cfg_attr(test, deny(warnings))]
-
-// 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"))]
-
-extern crate log;
-
-use std::env;
-use std::io::prelude::*;
-use std::io;
-use std::mem;
-
-use log::{Log, Level, LevelFilter, Record, SetLoggerError, Metadata};
-
-#[cfg(feature = "regex")]
-#[path = "regex.rs"]
-mod filter;
-
-#[cfg(not(feature = "regex"))]
-#[path = "string.rs"]
-mod filter;
-
-/// Log target, either stdout or stderr.
-#[derive(Debug)]
-pub enum Target {
- Stdout,
- Stderr,
-}
-
-/// The logger.
-pub struct Logger {
- directives: Vec<Directive>,
- filter: Option<filter::Filter>,
- format: Box<Fn(&Record) -> String + Sync + Send>,
- target: Target,
-}
-
-/// Builder acts as builder for initializing the Logger.
-/// It can be used to customize the log format, change the enviromental variable used
-/// to provide the logging directives and also set the default log level filter.
-///
-/// ## Example
-///
-/// ```
-/// #[macro_use]
-/// extern crate log;
-/// extern crate env_logger;
-///
-/// use std::env;
-/// use log::{Record, LevelFilter};
-/// use env_logger::Builder;
-///
-/// fn main() {
-/// let format = |record: &Record| {
-/// format!("{} - {}", record.level(), record.args())
-/// };
-///
-/// let mut builder = Builder::new();
-/// builder.format(format).filter(None, LevelFilter::Info);
-///
-/// if env::var("RUST_LOG").is_ok() {
-/// builder.parse(&env::var("RUST_LOG").unwrap());
-/// }
-///
-/// builder.init();
-///
-/// error!("error message");
-/// info!("info message");
-/// }
-/// ```
-pub struct Builder {
- directives: Vec<Directive>,
- filter: Option<filter::Filter>,
- format: Box<Fn(&Record) -> String + Sync + Send>,
- target: Target,
-}
-
-impl Builder {
- /// Initializes the log builder with defaults
- pub fn new() -> Builder {
- Builder {
- directives: Vec::new(),
- filter: None,
- format: Box::new(|record: &Record| {
- format!("{}:{}: {}", record.level(),
- record.module_path(), record.args())
- }),
- target: Target::Stderr,
- }
- }
-
- /// Adds filters to the logger
- ///
- /// The given module (if any) will log at most the specified level provided.
- /// If no module is provided then the filter will apply to all log messages.
- pub fn filter(&mut self,
- module: Option<&str>,
- level: LevelFilter) -> &mut Self {
- self.directives.push(Directive {
- name: module.map(|s| s.to_string()),
- level: level,
- });
- self
- }
-
- /// Sets the format function for formatting the log output.
- ///
- /// This function is called on each record logged to produce a string which
- /// is actually printed out.
- pub fn format<F: 'static>(&mut self, format: F) -> &mut Self
- where F: Fn(&Record) -> String + Sync + Send
- {
- self.format = Box::new(format);
- self
- }
-
- /// Sets the target for the log output.
- ///
- /// Env logger can log to either stdout or stderr. The default is stderr.
- pub fn target(&mut self, target: Target) -> &mut Self {
- self.target = target;
- self
- }
-
- /// Parses the directives string in the same form as the RUST_LOG
- /// environment variable.
- ///
- /// See the module documentation for more details.
- pub fn parse(&mut self, filters: &str) -> &mut Self {
- let (directives, filter) = parse_spec(filters);
-
- self.filter = filter;
-
- for directive in directives {
- self.directives.push(directive);
- }
- self
- }
-
- /// Initializes the global logger with an env logger.
- ///
- /// This should be called early in the execution of a Rust program, and the
- /// global logger may only be initialized once. Future initialization
- /// attempts will return error.
- pub fn try_init(&mut self) -> Result<(), SetLoggerError> {
- log::try_set_logger(|max_level| {
- let logger = self.build();
- max_level.set(logger.filter());
- Box::new(logger)
- })
- }
-
- /// Initializes the global logger with an env logger.
- ///
- /// This should be called early in the execution of a Rust program, and the
- /// global logger may only be initialized once. Future initialization
- /// attempts will panic.
- pub fn init(&mut self) {
- let logger = self.build();
- let filter = logger.filter();
- let logger = Box::new(logger);
- log::set_logger(logger, filter);
- }
-
- /// Build an env logger.
- pub fn build(&mut self) -> Logger {
- if self.directives.is_empty() {
- // Adds the default filter if none exist
- self.directives.push(Directive {
- name: None,
- level: LevelFilter::Error,
- });
- } else {
- // Sort the directives by length of their name, this allows a
- // little more efficient lookup at runtime.
- self.directives.sort_by(|a, b| {
- let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
- let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
- alen.cmp(&blen)
- });
- }
-
- Logger {
- directives: mem::replace(&mut self.directives, Vec::new()),
- filter: mem::replace(&mut self.filter, None),
- format: mem::replace(&mut self.format, Box::new(|_| String::new())),
- target: mem::replace(&mut self.target, Target::Stderr),
- }
- }
-}
-
-impl Logger {
- pub fn new() -> Logger {
- let mut builder = Builder::new();
-
- if let Ok(s) = env::var("RUST_LOG") {
- builder.parse(&s);
- }
-
- builder.build()
- }
-
- pub fn filter(&self) -> LevelFilter {
- self.directives.iter()
- .map(|d| d.level).max()
- .unwrap_or(LevelFilter::Off)
- }
-
- fn enabled(&self, level: Level, target: &str) -> bool {
- // Search for the longest match, the vector is assumed to be pre-sorted.
- for directive in self.directives.iter().rev() {
- match directive.name {
- Some(ref name) if !target.starts_with(&**name) => {},
- Some(..) | None => {
- return level <= directive.level
- }
- }
- }
- false
- }
-}
-
-impl Log for Logger {
- fn enabled(&self, metadata: &Metadata) -> bool {
- self.enabled(metadata.level(), metadata.target())
- }
-
- fn log(&self, record: &Record) {
- if !Log::enabled(self, record.metadata()) {
- return;
- }
-
- if let Some(filter) = self.filter.as_ref() {
- if !filter.is_match(&*record.args().to_string()) {
- return;
- }
- }
-
- match self.target {
- Target::Stdout => println!("{}", (self.format)(record)),
- Target::Stderr => {
- let _ = writeln!(&mut io::stderr(), "{}", (self.format)(record));
- },
- };
- }
-
- fn flush(&self) {}
-}
-
-struct Directive {
- name: Option<String>,
- level: LevelFilter,
-}
-
-/// Initializes the global logger with an env logger.
-///
-/// This should be called early in the execution of a Rust program, and the
-/// global logger may only be initialized once. Future initialization attempts
-/// will return an error.
-pub fn try_init() -> Result<(), SetLoggerError> {
- let mut builder = Builder::new();
-
- if let Ok(s) = env::var("RUST_LOG") {
- builder.parse(&s);
- }
-
- builder.try_init()
-}
-
-/// Initializes the global logger with an env logger.
-///
-/// This should be called early in the execution of a Rust program, and the
-/// global logger may only be initialized once. Future initialization attempts
-/// will panic.
-pub fn init() {
- let mut builder = Builder::new();
-
- if let Ok(s) = env::var("RUST_LOG") {
- builder.parse(&s);
- }
-
- builder.init()
-}
-
-/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=error/foo")
-/// and return a vector with log directives.
-fn parse_spec(spec: &str) -> (Vec<Directive>, Option<filter::Filter>) {
- let mut dirs = Vec::new();
-
- let mut parts = spec.split('/');
- let mods = parts.next();
- let filter = parts.next();
- if parts.next().is_some() {
- println!("warning: invalid logging spec '{}', \
- ignoring it (too many '/'s)", spec);
- return (dirs, None);
- }
- mods.map(|m| { for s in m.split(',') {
- if s.len() == 0 { continue }
- let mut parts = s.split('=');
- let (log_level, name) = match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) {
- (Some(part0), None, None) => {
- // if the single argument is a log-level string or number,
- // treat that as a global fallback
- match part0.parse() {
- Ok(num) => (num, None),
- Err(_) => (LevelFilter::max(), Some(part0)),
- }
- }
- (Some(part0), Some(""), None) => (LevelFilter::max(), Some(part0)),
- (Some(part0), Some(part1), None) => {
- match part1.parse() {
- Ok(num) => (num, Some(part0)),
- _ => {
- println!("warning: invalid logging spec '{}', \
- ignoring it", part1);
- continue
- }
- }
- },
- _ => {
- println!("warning: invalid logging spec '{}', \
- ignoring it", s);
- continue
- }
- };
- dirs.push(Directive {
- name: name.map(|s| s.to_string()),
- level: log_level,
- });
- }});
-
- let filter = filter.map_or(None, |filter| {
- match filter::Filter::new(filter) {
- Ok(re) => Some(re),
- Err(e) => {
- println!("warning: invalid regex filter - {}", e);
- None
- }
- }
- });
-
- return (dirs, filter);
-}
-
-#[cfg(test)]
-mod tests {
- use log::{Level, LevelFilter};
-
- use super::{Builder, Logger, Directive, parse_spec};
-
- fn make_logger(dirs: Vec<Directive>) -> Logger {
- let mut logger = Builder::new().build();
- logger.directives = dirs;
- logger
- }
-
- #[test]
- fn filter_info() {
- let logger = Builder::new().filter(None, LevelFilter::Info).build();
- assert!(logger.enabled(Level::Info, "crate1"));
- assert!(!logger.enabled(Level::Debug, "crate1"));
- }
-
- #[test]
- fn filter_beginning_longest_match() {
- let logger = Builder::new()
- .filter(Some("crate2"), LevelFilter::Info)
- .filter(Some("crate2::mod"), LevelFilter::Debug)
- .filter(Some("crate1::mod1"), LevelFilter::Warn)
- .build();
- assert!(logger.enabled(Level::Debug, "crate2::mod1"));
- assert!(!logger.enabled(Level::Debug, "crate2"));
- }
-
- #[test]
- fn parse_default() {
- let logger = Builder::new().parse("info,crate1::mod1=warn").build();
- assert!(logger.enabled(Level::Warn, "crate1::mod1"));
- assert!(logger.enabled(Level::Info, "crate2::mod2"));
- }
-
- #[test]
- fn match_full_path() {
- let logger = make_logger(vec![
- Directive {
- name: Some("crate2".to_string()),
- level: LevelFilter::Info
- },
- Directive {
- name: Some("crate1::mod1".to_string()),
- level: LevelFilter::Warn
- }
- ]);
- assert!(logger.enabled(Level::Warn, "crate1::mod1"));
- assert!(!logger.enabled(Level::Info, "crate1::mod1"));
- assert!(logger.enabled(Level::Info, "crate2"));
- assert!(!logger.enabled(Level::Debug, "crate2"));
- }
-
- #[test]
- fn no_match() {
- let logger = make_logger(vec![
- Directive { name: Some("crate2".to_string()), level: LevelFilter::Info },
- Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
- ]);
- assert!(!logger.enabled(Level::Warn, "crate3"));
- }
-
- #[test]
- fn match_beginning() {
- let logger = make_logger(vec![
- Directive { name: Some("crate2".to_string()), level: LevelFilter::Info },
- Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
- ]);
- assert!(logger.enabled(Level::Info, "crate2::mod1"));
- }
-
- #[test]
- fn match_beginning_longest_match() {
- let logger = make_logger(vec![
- Directive { name: Some("crate2".to_string()), level: LevelFilter::Info },
- Directive { name: Some("crate2::mod".to_string()), level: LevelFilter::Debug },
- Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
- ]);
- assert!(logger.enabled(Level::Debug, "crate2::mod1"));
- assert!(!logger.enabled(Level::Debug, "crate2"));
- }
-
- #[test]
- fn match_default() {
- let logger = make_logger(vec![
- Directive { name: None, level: LevelFilter::Info },
- Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
- ]);
- assert!(logger.enabled(Level::Warn, "crate1::mod1"));
- assert!(logger.enabled(Level::Info, "crate2::mod2"));
- }
-
- #[test]
- fn zero_level() {
- let logger = make_logger(vec![
- Directive { name: None, level: LevelFilter::Info },
- Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Off }
- ]);
- assert!(!logger.enabled(Level::Error, "crate1::mod1"));
- assert!(logger.enabled(Level::Info, "crate2::mod2"));
- }
-
- #[test]
- fn parse_spec_valid() {
- let (dirs, filter) = parse_spec("crate1::mod1=error,crate1::mod2,crate2=debug");
- assert_eq!(dirs.len(), 3);
- assert_eq!(dirs[0].name, Some("crate1::mod1".to_string()));
- assert_eq!(dirs[0].level, LevelFilter::Error);
-
- assert_eq!(dirs[1].name, Some("crate1::mod2".to_string()));
- assert_eq!(dirs[1].level, LevelFilter::max());
-
- assert_eq!(dirs[2].name, Some("crate2".to_string()));
- assert_eq!(dirs[2].level, LevelFilter::Debug);
- assert!(filter.is_none());
- }
-
- #[test]
- fn parse_spec_invalid_crate() {
- // test parse_spec with multiple = in specification
- let (dirs, filter) = parse_spec("crate1::mod1=warn=info,crate2=debug");
- assert_eq!(dirs.len(), 1);
- assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LevelFilter::Debug);
- assert!(filter.is_none());
- }
-
- #[test]
- fn parse_spec_invalid_level() {
- // test parse_spec with 'noNumber' as log level
- let (dirs, filter) = parse_spec("crate1::mod1=noNumber,crate2=debug");
- assert_eq!(dirs.len(), 1);
- assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LevelFilter::Debug);
- assert!(filter.is_none());
- }
-
- #[test]
- fn parse_spec_string_level() {
- // test parse_spec with 'warn' as log level
- let (dirs, filter) = parse_spec("crate1::mod1=wrong,crate2=warn");
- assert_eq!(dirs.len(), 1);
- assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LevelFilter::Warn);
- assert!(filter.is_none());
- }
-
- #[test]
- fn parse_spec_empty_level() {
- // test parse_spec with '' as log level
- let (dirs, filter) = parse_spec("crate1::mod1=wrong,crate2=");
- assert_eq!(dirs.len(), 1);
- assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LevelFilter::max());
- assert!(filter.is_none());
- }
-
- #[test]
- fn parse_spec_global() {
- // test parse_spec with no crate
- let (dirs, filter) = parse_spec("warn,crate2=debug");
- assert_eq!(dirs.len(), 2);
- assert_eq!(dirs[0].name, None);
- assert_eq!(dirs[0].level, LevelFilter::Warn);
- assert_eq!(dirs[1].name, Some("crate2".to_string()));
- assert_eq!(dirs[1].level, LevelFilter::Debug);
- assert!(filter.is_none());
- }
-
- #[test]
- fn parse_spec_valid_filter() {
- let (dirs, filter) = parse_spec("crate1::mod1=error,crate1::mod2,crate2=debug/abc");
- assert_eq!(dirs.len(), 3);
- assert_eq!(dirs[0].name, Some("crate1::mod1".to_string()));
- assert_eq!(dirs[0].level, LevelFilter::Error);
-
- assert_eq!(dirs[1].name, Some("crate1::mod2".to_string()));
- assert_eq!(dirs[1].level, LevelFilter::max());
-
- assert_eq!(dirs[2].name, Some("crate2".to_string()));
- assert_eq!(dirs[2].level, LevelFilter::Debug);
- assert!(filter.is_some() && filter.unwrap().to_string() == "abc");
- }
-
- #[test]
- fn parse_spec_invalid_crate_filter() {
- let (dirs, filter) = parse_spec("crate1::mod1=error=warn,crate2=debug/a.c");
- assert_eq!(dirs.len(), 1);
- assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LevelFilter::Debug);
- assert!(filter.is_some() && filter.unwrap().to_string() == "a.c");
- }
-
- #[test]
- fn parse_spec_empty_with_filter() {
- let (dirs, filter) = parse_spec("crate1/a*c");
- assert_eq!(dirs.len(), 1);
- assert_eq!(dirs[0].name, Some("crate1".to_string()));
- assert_eq!(dirs[0].level, LevelFilter::max());
- assert!(filter.is_some() && filter.unwrap().to_string() == "a*c");
- }
-}
diff --git a/env/src/regex.rs b/env/src/regex.rs
deleted file mode 100644
index 0df03e673..000000000
--- a/env/src/regex.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-extern crate regex;
-
-use std::fmt;
-
-use self::regex::Regex;
-
-pub struct Filter {
- inner: Regex,
-}
-
-impl Filter {
- pub fn new(spec: &str) -> Result<Filter, String> {
- match Regex::new(spec){
- Ok(r) => Ok(Filter { inner: r }),
- Err(e) => Err(e.to_string()),
- }
- }
-
- pub fn is_match(&self, s: &str) -> bool {
- self.inner.is_match(s)
- }
-}
-
-impl fmt::Display for Filter {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- self.inner.fmt(f)
- }
-}
diff --git a/env/src/string.rs b/env/src/string.rs
deleted file mode 100644
index 74d0e04db..000000000
--- a/env/src/string.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use std::fmt;
-
-pub struct Filter {
- inner: String,
-}
-
-impl Filter {
- pub fn new(spec: &str) -> Result<Filter, String> {
- Ok(Filter { inner: spec.to_string() })
- }
-
- pub fn is_match(&self, s: &str) -> bool {
- s.contains(&self.inner)
- }
-}
-
-impl fmt::Display for Filter {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- self.inner.fmt(f)
- }
-}
diff --git a/src/lib.rs b/src/lib.rs
index 50479f619..c222ae153 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -87,25 +87,6 @@
//!
//! The logging system may only be initialized once.
//!
-//! ### Examples
-//!
-//! ```rust,ignore
-//! #[macro_use]
-//! extern crate log;
-//! extern crate env_logger;
-//!
-//! fn main() {
-//! // Select env_logger, one possible logger implementation
-//! // (see https://doc.rust-lang.org/log/env_logger/index.html)
-//! env_logger::init();
-//!
-//! info!("starting up");
-//! error!("error: {}", 404);
-//!
-//! // ...
-//! }
-//! ```
-//!
//! # Available logging implementations
//!
//! In order to produce log output executables have to use
|
diff --git a/env/tests/regexp_filter.rs b/env/tests/regexp_filter.rs
deleted file mode 100644
index d23e9223e..000000000
--- a/env/tests/regexp_filter.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-#[macro_use] extern crate log;
-extern crate env_logger;
-
-use std::process;
-use std::env;
-use std::str;
-
-fn main() {
- if env::var("LOG_REGEXP_TEST").ok() == Some(String::from("1")) {
- child_main();
- } else {
- parent_main()
- }
-}
-
-fn child_main() {
- env_logger::init();
- info!("XYZ Message");
-}
-
-fn run_child(rust_log: String) -> bool {
- let exe = env::current_exe().unwrap();
- let out = process::Command::new(exe)
- .env("LOG_REGEXP_TEST", "1")
- .env("RUST_LOG", rust_log)
- .output()
- .unwrap_or_else(|e| panic!("Unable to start child process: {}", e));
- str::from_utf8(out.stderr.as_ref()).unwrap().contains("XYZ Message")
-}
-
-fn assert_message_printed(rust_log: &str) {
- if !run_child(rust_log.to_string()) {
- panic!("RUST_LOG={} should allow the test log message", rust_log)
- }
-}
-
-fn assert_message_not_printed(rust_log: &str) {
- if run_child(rust_log.to_string()) {
- panic!("RUST_LOG={} should not allow the test log message", rust_log)
- }
-}
-
-fn parent_main() {
- // test normal log severity levels
- assert_message_printed("info");
- assert_message_not_printed("warn");
-
- // test of regular expression filters
- assert_message_printed("info/XYZ");
- assert_message_not_printed("info/XXX");
-}
|
Remove env_logger from this repository
Let's find a suitable maintainer and move it out of the `log` repository itself. While still a high quality logger that we'd likely want to recommend, it may benefit from spreading out the maintenance burden! Tons of possible features were mentioned for `env_logger` on the [evaluation thread](https://internals.rust-lang.org/t/crate-evaluation-for-2017-05-16-log/5185/50) and may wish to make their way to the new repository.
**EDIT**
PRs that need to be resubmitted to the new repo:
- [x] #113
- [x] #219
|
Hey @alexcrichton, I've started to work on this split at [sebasmagri/env_logger](https://github.com/sebasmagri/env_logger).
I'll review the features mentioned in the evaluation thread and check out the API guidelines for the new repo.
For now, I'm pointing it to `log`'s git repo since there where some breaking changes in its enums. What would be the plan in `log`'s side to make a stable dep for `env_logger`?
@alexcrichton @sfackler by @brson suggestion, I've added you guys as collaborators in the new repo.
Is there any particular improvement that should be done for it?
Thanks @sebasmagri!
How do you want to handle outstanding PRs?
@jethrogb ideally the changes should be resubmitted to the new repo... Can you please point me to those?
Seems like we need to make some decisions about this - are we going to do a handover here, and how?
If we're confident doing it then it seems like we should maybe land the outstanding PRs, remove env_logger from this repo, and maybe reimport that state into @sebasmagri's.
cc @sfackler @alexcrichton
For the record, the open PRs that touch `env_logger` are #203 (though this is already open in the new repo as well), #196 which is just about adding a noop `flush` method to env_logger's `Logger`, and #113 which is not yet defined as per @dtolnay's feedback.
There has no been further changes to `env_logger` since I transplanted it.
I would love to give env-logger over to a motivated maintainer.
#200 has also made a small change to env_logger in this repo and #196 has now been merged. I've made both changes to the forked env_logger here: sebasmagri/env_logger#15.
@sebasmagri have you logged into crates.io yet? I tried adding you as an owner but it said you weren't registered :(
@alexcrichton I hadn't, you should be able to find me now.
@sebasmagri ok you're added as an owner, as soon as everything's sorted away I think we can just have a PR to remove it from this repo.
|
2017-09-17T05:41:09Z
|
0.3
|
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
|
rust-lang/log
| 217
|
rust-lang__log-217
|
[
"148"
] |
25e349c7389ab63a9f5303a9a6183aa9d723b0a0
|
diff --git a/.travis.yml b/.travis.yml
index 1b82ecd3a..479981582 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -12,6 +12,7 @@ script:
- ([ $TRAVIS_RUST_VERSION != nightly ] || cargo build --verbose --features nightly)
- cargo test --verbose
- ([ $TRAVIS_RUST_VERSION != nightly ] || cargo test --verbose --no-default-features)
+ - cargo test --verbose --manifest-path log-test/Cargo.toml
- cargo test --verbose --manifest-path env/Cargo.toml
- cargo test --verbose --manifest-path env/Cargo.toml --no-default-features
- cargo run --verbose --manifest-path tests/max_level_features/Cargo.toml
diff --git a/Cargo.toml b/Cargo.toml
index 7f4645379..2dfeab604 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,25 +13,27 @@ A lightweight logging facade for Rust
"""
categories = ["development-tools::debugging"]
-[[test]]
-name = "filters"
-harness = false
+[lib]
+doctest = false
[features]
-max_level_off = []
-max_level_error = []
-max_level_warn = []
-max_level_info = []
-max_level_debug = []
-max_level_trace = []
+max_level_off = ["log/max_level_off"]
+max_level_error = ["log/max_level_error"]
+max_level_warn = ["log/max_level_warn"]
+max_level_info = ["log/max_level_info"]
+max_level_debug = ["log/max_level_debug"]
+max_level_trace = ["log/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 = []
+release_max_level_off = ["log/release_max_level_off"]
+release_max_level_error = ["log/release_max_level_error"]
+release_max_level_warn = ["log/release_max_level_warn"]
+release_max_level_info = ["log/release_max_level_info"]
+release_max_level_debug = ["log/release_max_level_debug"]
+release_max_level_trace = ["log/release_max_level_trace"]
nightly = []
-use_std = []
+use_std = ["log/use_std"]
default = ["use_std"]
+
+[dependencies]
+log = { git = "https://github.com/rust-lang-nursery/log", default_features = false }
diff --git a/src/lib.rs b/src/lib.rs
index 6c222baef..014cade20 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -199,6 +199,7 @@
#[cfg(not(feature = "use_std"))]
extern crate core as std;
+extern crate log;
use std::cmp;
#[cfg(feature = "use_std")]
@@ -235,12 +236,9 @@ static mut LOGGER: *const Log = &NopLogger;
static STATE: AtomicUsize = ATOMIC_USIZE_INIT;
static REFCOUNT: AtomicUsize = ATOMIC_USIZE_INIT;
-const UNINITIALIZED: usize = 0;
const INITIALIZING: usize = 1;
const INITIALIZED: usize = 2;
-static MAX_LOG_LEVEL_FILTER: AtomicUsize = ATOMIC_USIZE_INIT;
-
static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO",
"DEBUG", "TRACE"];
@@ -370,6 +368,26 @@ impl LogLevel {
}
}
+ fn from_new(level: log::Level) -> LogLevel {
+ match level {
+ log::Level::Error => LogLevel::Error,
+ log::Level::Warn => LogLevel::Warn,
+ log::Level::Info => LogLevel::Info,
+ log::Level::Debug => LogLevel::Debug,
+ log::Level::Trace => LogLevel::Trace,
+ }
+ }
+
+ fn to_new(&self) -> log::Level {
+ match *self {
+ LogLevel::Error => log::Level::Error,
+ LogLevel::Warn => log::Level::Warn,
+ LogLevel::Info => log::Level::Info,
+ LogLevel::Debug => log::Level::Debug,
+ LogLevel::Trace => log::Level::Trace,
+ }
+ }
+
/// Returns the most verbose logging level.
#[inline]
pub fn max() -> LogLevel {
@@ -475,6 +493,29 @@ impl LogLevelFilter {
_ => None
}
}
+
+ fn from_new(filter: log::LevelFilter) -> LogLevelFilter {
+ match filter {
+ log::LevelFilter::Off => LogLevelFilter::Off,
+ log::LevelFilter::Error => LogLevelFilter::Error,
+ log::LevelFilter::Warn => LogLevelFilter::Warn,
+ log::LevelFilter::Info => LogLevelFilter::Info,
+ log::LevelFilter::Debug => LogLevelFilter::Debug,
+ log::LevelFilter::Trace => LogLevelFilter::Trace,
+ }
+ }
+
+ fn to_new(&self) -> log::LevelFilter {
+ match *self {
+ LogLevelFilter::Off => log::LevelFilter::Off,
+ LogLevelFilter::Error => log::LevelFilter::Error,
+ LogLevelFilter::Warn => log::LevelFilter::Warn,
+ LogLevelFilter::Info => log::LevelFilter::Info,
+ LogLevelFilter::Debug => log::LevelFilter::Debug,
+ LogLevelFilter::Trace => log::LevelFilter::Trace,
+ }
+ }
+
/// Returns the most verbose logging level filter.
#[inline]
pub fn max() -> LogLevelFilter {
@@ -611,8 +652,7 @@ impl LogLocation {
/// higher than the maximum log level filter will be ignored. A logger should
/// make sure to keep the maximum log level filter in sync with its current
/// configuration.
-#[allow(missing_copy_implementations)]
-pub struct MaxLogLevelFilter(());
+pub struct MaxLogLevelFilter(log::MaxLevelFilter);
impl fmt::Debug for MaxLogLevelFilter {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
@@ -628,7 +668,7 @@ impl MaxLogLevelFilter {
/// Sets the maximum log level.
pub fn set(&self, level: LogLevelFilter) {
- MAX_LOG_LEVEL_FILTER.store(level as usize, Ordering::SeqCst)
+ self.0.set(level.to_new())
}
}
@@ -639,7 +679,7 @@ impl MaxLogLevelFilter {
/// log level is set by the `MaxLogLevel` token passed to loggers.
#[inline(always)]
pub fn max_log_level() -> LogLevelFilter {
- unsafe { mem::transmute(MAX_LOG_LEVEL_FILTER.load(Ordering::Relaxed)) }
+ LogLevelFilter::from_new(log::max_level())
}
/// Sets the global logger.
@@ -687,14 +727,11 @@ pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
/// addition, `shutdown_logger` *must not* be called after this function.
pub unsafe fn set_logger_raw<M>(make_logger: M) -> Result<(), SetLoggerError>
where M: FnOnce(MaxLogLevelFilter) -> *const Log {
- if STATE.compare_and_swap(UNINITIALIZED, INITIALIZING,
- Ordering::SeqCst) != UNINITIALIZED {
- return Err(SetLoggerError(()));
- }
-
- LOGGER = make_logger(MaxLogLevelFilter(()));
- STATE.store(INITIALIZED, Ordering::SeqCst);
- Ok(())
+ log::set_logger_raw(|filter| {
+ LOGGER = make_logger(MaxLogLevelFilter(filter));
+ STATE.store(INITIALIZED, Ordering::SeqCst);
+ &LoggerAdaptor
+ }).map_err(|_| SetLoggerError(()))
}
/// Shuts down the global logger.
@@ -727,9 +764,6 @@ pub fn shutdown_logger() -> Result<Box<Log>, ShutdownLoggerError> {
/// success. At that point it is guaranteed that no other threads are
/// concurrently accessing the logger object.
pub fn shutdown_logger_raw() -> Result<*const Log, ShutdownLoggerError> {
- // Set the global log level to stop other thread from logging
- MAX_LOG_LEVEL_FILTER.store(0, Ordering::SeqCst);
-
// Set to INITIALIZING to prevent re-initialization after
if STATE.compare_and_swap(INITIALIZED, INITIALIZING,
Ordering::SeqCst) != INITIALIZED {
@@ -848,16 +882,65 @@ fn logger() -> Option<LoggerGuard> {
}
}
+struct LoggerAdaptor;
+
+impl log::Log for LoggerAdaptor {
+ fn log(&self, record: &log::Record) {
+ let (file, module_path) = unsafe {
+ if log::__SUPER_SECRET_STRINGS_ARE_STATIC {
+ (
+ &*(record.file() as *const str),
+ &*(record.module_path() as *const str),
+ )
+ } else {
+ ("", "")
+ }
+ };
+ if let Some(logger) = logger() {
+ let record = LogRecord {
+ metadata: LogMetadata {
+ level: LogLevel::from_new(record.level()),
+ target: record.target(),
+ },
+ location: &LogLocation {
+ __file: file,
+ __line: record.line(),
+ __module_path: module_path,
+ },
+ args: *record.args(),
+ };
+ logger.log(&record);
+ }
+ }
+
+ fn enabled(&self, metadata: &log::Metadata) -> bool {
+ match logger() {
+ Some(logger) => {
+ let metadata = LogMetadata {
+ level: LogLevel::from_new(metadata.level()),
+ target: metadata.target(),
+ };
+ logger.enabled(&metadata)
+ }
+ None => false
+ }
+ }
+
+ fn flush(&self) {}
+}
+
// WARNING
// This is not considered part of the crate's public API. It is subject to
// change at any time.
#[doc(hidden)]
pub fn __enabled(level: LogLevel, target: &str) -> bool {
- if let Some(logger) = logger() {
- logger.enabled(&LogMetadata { level: level, target: target })
- } else {
- false
- }
+ log::Log::enabled(
+ log::logger(),
+ &log::Metadata::builder()
+ .level(level.to_new())
+ .target(target)
+ .build()
+ )
}
// WARNING
@@ -866,17 +949,17 @@ pub fn __enabled(level: LogLevel, target: &str) -> bool {
#[doc(hidden)]
pub fn __log(level: LogLevel, target: &str, loc: &LogLocation,
args: fmt::Arguments) {
- if let Some(logger) = logger() {
- let record = LogRecord {
- metadata: LogMetadata {
- level: level,
- target: target,
- },
- location: loc,
- args: args
- };
- logger.log(&record)
- }
+ log::Log::log(
+ log::logger(),
+ &log::Record::builder()
+ .level(level.to_new())
+ .target(target)
+ .file(loc.__file)
+ .line(loc.__line)
+ .module_path(loc.__module_path)
+ .args(args)
+ .build()
+ )
}
// WARNING
@@ -885,35 +968,7 @@ pub fn __log(level: LogLevel, target: &str, loc: &LogLocation,
#[inline(always)]
#[doc(hidden)]
pub fn __static_max_level() -> LogLevelFilter {
- if !cfg!(debug_assertions) {
- // This is a release build. Check `release_max_level_*` first.
- if cfg!(feature = "release_max_level_off") {
- return LogLevelFilter::Off
- } else if cfg!(feature = "release_max_level_error") {
- return LogLevelFilter::Error
- } else if cfg!(feature = "release_max_level_warn") {
- return LogLevelFilter::Warn
- } else if cfg!(feature = "release_max_level_info") {
- return LogLevelFilter::Info
- } else if cfg!(feature = "release_max_level_debug") {
- return LogLevelFilter::Debug
- } else if cfg!(feature = "release_max_level_trace") {
- return LogLevelFilter::Trace
- }
- }
- if cfg!(feature = "max_level_off") {
- LogLevelFilter::Off
- } else if cfg!(feature = "max_level_error") {
- LogLevelFilter::Error
- } else if cfg!(feature = "max_level_warn") {
- LogLevelFilter::Warn
- } else if cfg!(feature = "max_level_info") {
- LogLevelFilter::Info
- } else if cfg!(feature = "max_level_debug") {
- LogLevelFilter::Debug
- } else {
- LogLevelFilter::Trace
- }
+ LogLevelFilter::from_new(log::STATIC_MAX_LEVEL)
}
#[cfg(test)]
|
diff --git a/log-test/Cargo.toml b/log-test/Cargo.toml
new file mode 100644
index 000000000..82eaf1add
--- /dev/null
+++ b/log-test/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "log-test"
+version = "0.1.0"
+authors = ["Steven Fackler <sfackler@gmail.com>"]
+
+[dependencies]
+log = { path = ".." }
+
+[[test]]
+name = "filters"
+harness = false
diff --git a/log-test/src/lib.rs b/log-test/src/lib.rs
new file mode 100644
index 000000000..cdfbe1aa5
--- /dev/null
+++ b/log-test/src/lib.rs
@@ -0,0 +1,6 @@
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn it_works() {
+ }
+}
diff --git a/tests/filters.rs b/log-test/tests/filters.rs
similarity index 100%
rename from tests/filters.rs
rename to log-test/tests/filters.rs
|
Ensure 0.3 works with the next major release
We'll want to publish a version of 0.3 that works as a compatibility layer to the 0.4 version of the `log` crate
|
If it's alright and no one else has started, I can start working on a shared backend crate for this.
I'm trying to think of the best way to have it be efficient, while still allowing for maximum change. Right now my best idea is to have a versioned API that would be somewhat like the following:
```rust
pub fn register_v1_log(log: *const V1Log) -> Result<(), ...>;
pub fn log_v1(record: V1Record);
trait V1Log {
fn log(&self, record: V1Record);
}
```
`V1Record` would be a mirror of what the `log` crate's current `LogRecord` struct is, and the `log` crate would simply have a newtype wrapper around it for the exported `LogRecord` type.
`V1Record` would be constructed with a `V1RecordBuilder`: `#[inline(always)]` builder methods should allow for the same performance we have now without a builder, and this would allow us to add more fields without bumping to `V2Record` immediately.
`V1Log` would have a blanket impl like this in `log`:
```rust
#[doc(hidden)]
impl<T: Log> V1Log for T {
fn log(&self, record: V1Record) {
<Self as Log>>::log(&LogRecord { inner: record });
}
}
```
For the next version of `log` which brings an incompatible `LogRecord` format, `log_impl` would introduce `V2Log` and `V2Record` to match, and would `impl From<V1Record> for V2Record` and vice versa. I would name `V1` rather than `V0_3` just because I wouldn't expect every single `log` crate release to need a new, incompatible record version.
Internally, `log_impl` would store an enum `VersionedLog` which could be a box of any of the `V*Log` traits, and would convert records accordingly when logged.
The `log_impl` would provide one other feature, a set of macros `if_trace_enabled!()` through `if_error_enabled!()`, which would be controlled through `max_level_*` and `release_max_level_*` crate features, similar to `log`'s current ones. These macros would then be used in `log` instead of the features, and the `log` features would simply forward to depending on the `log_impl` ones.
There would be overhead of converting records if the `log` macro version and logger version don't match, but I believe a scheme like this would fully support both public breaking API changes in `log`, and breaking changes in how `LogRecord` is internally structured.
If we don't implement any breaking changes in `LogRecord`s format, we could even just have `log_impl` with `V1*` always, and there would be no overhead.
Unresolved question with this idea: v0.3 takes in `Box<Log>`, which I don't believe can be converted to `Box<V1Log>`, even if a blanket implementation exists. Might make this unreasonable.
I'm not clear on what needs to be done here. @alexcrichton @sfackler have comments on @daboross's comments?
I'll implement what I described if it is deemed an alright thing.
The one difference may need to be that log just re-exports log_inner::V1Log as Log in order to not need double boxing but I'm not sure how this can be shown well in documentation... (without having users see the log_inner implementation detail of log).
I think it'll need to be a bit weirder than that because we're getting rid of shutdown in 0.4. One possible route is that 0.3 depends on 0.4 and forwards log events over to it. We'd then have a wrapping shim in 0.3 that would handle shutdown if you registered a logger through it.
We'll want 0.4 to be able to log events in a 0.3 logger too though, right?
With an inner/backend crate though, what if it just took `(fn(&Metadata) -> bool, fn(&Record))` instead of `Box<Log>`? That way we could have both `log 0.3` and `log 0.4` have separate ways of storing the `Log`, and then we'd be able to retain support for shutdown in log 0.3 while removing it in 0.4. Both versions would just register their specific function to access their global log storage when they register a logger.
I think passing just an `fn` pair to the backend might also solve the issue of having to double-box things in order to have a nice API. This would involve another indirect dynamic call, but I'm thinking that's a cost we could live with?
Yeah - this would handle that - an 0.3 logger is turned into an 0.4 logger with some shim to handle shutdown.
I'd also like to avoid allocating on the log path.
Definitely agree here with avoiding allocating.
I still think having a shared backend would be a more long-term solution, as then we wouldn't have to update 0.3 and 0.4 both to depend on 1.0 when we release it.
Is the benefit of having 0.3 depend on 0.4 just less code complexity, or is there another reason as well? I mean having less duplication in the project structure is valid, I just didn't think of it as too much of a concern.
It seems pretty reasonable to me to trade way less code complexity for making two commits when we cut 1.0.
Alright! I can get behind that.
|
2017-08-13T23:43:25Z
|
0.3
|
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
|
rust-lang/log
| 208
|
rust-lang__log-208
|
[
"204"
] |
8af5f3c688461a166a5097c395a5deb6c99a70ed
|
diff --git a/src/lib.rs b/src/lib.rs
index 50479f619..e31451324 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -190,8 +190,9 @@
//! To use the `log` crate without depending on `libstd`, you need to specify
//! `default-features = false` when specifying the dependency in `Cargo.toml`.
//! This makes no difference to libraries using `log` since the logging API
-//! remains the same. However executables will need to use the [`set_logger_raw`]
-//! function to initialize a logger.
+//! remains the same. However executables will need to use the [`try_set_logger_raw`]
+//! function to initialize a logger and the [`shutdown_logger_raw`] function to
+//! shut down the global logger before exiting:
//!
//! ```rust
//! # extern crate log;
@@ -205,7 +206,7 @@
//! # fn main() {}
//! pub fn try_init() -> Result<(), SetLoggerError> {
//! unsafe {
-//! log::set_logger_raw(|max_level| {
+//! log::try_set_logger_raw(|max_level| {
//! static LOGGER: SimpleLogger = SimpleLogger;
//! max_level.set(LevelFilter::Info);
//! &SimpleLogger
@@ -232,7 +233,8 @@
//! [level_link]: enum.Level.html
//! [`set_logger`]: fn.set_logger.html
//! [`MaxLevelFilter`]: struct.MaxLevelFilter.html
-//! [`set_logger_raw`]: fn.set_logger_raw.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
@@ -1064,7 +1066,7 @@ pub fn max_level() -> LevelFilter {
pub fn try_set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
where M: FnOnce(MaxLevelFilter) -> Box<Log>
{
- unsafe { set_logger_raw(|max_level| mem::transmute(make_logger(max_level))) }
+ unsafe { try_set_logger_raw(|max_level| mem::transmute(make_logger(max_level))) }
}
/// Sets the global logger.
@@ -1102,12 +1104,12 @@ pub fn set_logger(logger: Box<Log>, filter: LevelFilter) {
/// highest log level that the logger will not ignore.
///
/// This function may only be called once in the lifetime of a program. Any log
-/// events that occur before the call to `set_logger_raw` completes will be
+/// events that occur before the call to `try_set_logger_raw` completes will be
/// ignored.
///
/// This function does not typically need to be called manually. Logger
/// implementations should provide an initialization method that calls
-/// `set_logger_raw` internally.
+/// `try_set_logger_raw` internally.
///
/// # Errors
///
@@ -1146,7 +1148,7 @@ pub fn set_logger(logger: Box<Log>, filter: LevelFilter) {
///
/// # fn main(){
/// unsafe {
-/// log::set_logger_raw(|max_log_level| {
+/// log::try_set_logger_raw(|max_log_level| {
/// max_log_level.set(LevelFilter::Info);
/// &MY_LOGGER as *const MyLogger
/// })
@@ -1159,7 +1161,9 @@ pub fn set_logger(logger: Box<Log>, filter: LevelFilter) {
/// ```
///
/// [`set_logger`]: fn.set_logger.html
-pub unsafe fn set_logger_raw<M>(make_logger: M) -> Result<(), SetLoggerError>
+/// [`shutdown_logger`]: fn.shutdown_logger.html
+/// [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html
+pub unsafe fn try_set_logger_raw<M>(make_logger: M) -> Result<(), SetLoggerError>
where M: FnOnce(MaxLevelFilter) -> *const Log
{
if STATE.compare_and_swap(UNINITIALIZED, INITIALIZING, Ordering::SeqCst) != UNINITIALIZED {
|
diff --git a/tests/filters.rs b/tests/filters.rs
index 5fc55b2d4..4b4d09050 100644
--- a/tests/filters.rs
+++ b/tests/filters.rs
@@ -11,7 +11,7 @@ use log::try_set_logger;
fn try_set_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
where M: FnOnce(MaxLevelFilter) -> Box<Log>
{
- unsafe { log::set_logger_raw(|x| std::mem::transmute(make_logger(x))) }
+ unsafe { log::try_set_logger_raw(|x| std::mem::transmute(make_logger(x))) }
}
struct State {
diff --git a/tests/max_level_features/main.rs b/tests/max_level_features/main.rs
index 168f0249e..7e1186ce4 100644
--- a/tests/max_level_features/main.rs
+++ b/tests/max_level_features/main.rs
@@ -11,7 +11,7 @@ use log::try_set_logger;
fn try_set_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
where M: FnOnce(MaxLevelFilter) -> Box<Log> {
unsafe {
- log::set_logger_raw(|x| std::mem::transmute(make_logger(x)))
+ log::try_set_logger_raw(|x| std::mem::transmute(make_logger(x)))
}
}
|
Rename set_logger_raw to try_set_logger_raw
With respect to the changes made in #187, it makes sense to change set_logger_raw to panic on error (just like set_logger); where set_logger_raw panics on error and try_set_logger_raw returns error.
@alexcrichton @dtolnay
|
The rationale to change `set_logger` to panic-on-error was that most libraries would transitively call it through their logger's initialization function. I'd imagine, however, that `set_logger_raw` is quite rarely called, so I'd actually advoate for renaming `set_logger_raw` to `try_set_logger_raw` and *not* adding a panicking variant of `set_logger_raw`
@alexcrichton So should I go ahead with renaming set_logger_raw to try_set_logger_raw?
Sure!
|
2017-07-16T17:18:17Z
|
0.3
|
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
|
rust-lang/log
| 196
|
rust-lang__log-196
|
[
"117"
] |
c77cd5e37f3036f59a29f4f0d2bc36efe6ec10ff
|
diff --git a/env/src/lib.rs b/env/src/lib.rs
index cc3983352..4c6ca69c3 100644
--- a/env/src/lib.rs
+++ b/env/src/lib.rs
@@ -375,6 +375,8 @@ impl Log for Logger {
},
};
}
+
+ fn flush(&self) {}
}
struct Directive {
diff --git a/src/lib.rs b/src/lib.rs
index f485c1b54..9f3bfccbc 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -150,6 +150,7 @@
//! println!("{} - {}", record.level(), record.args());
//! }
//! }
+//! fn flush(&self) {}
//! }
//!
//! # fn main() {}
@@ -173,6 +174,7 @@
//! # impl log::Log for SimpleLogger {
//! # fn enabled(&self, _: &Metadata) -> bool { false }
//! # fn log(&self, _: &log::Record) {}
+//! # fn flush(&self) {}
//! # }
//! # fn main() {}
//! # #[cfg(feature = "use_std")]
@@ -189,19 +191,15 @@
//! `default-features = false` when specifying the dependency in `Cargo.toml`.
//! This makes no difference to libraries using `log` since the logging API
//! remains the same. However executables will need to use the [`set_logger_raw`]
-//! function to initialize a logger and the [`shutdown_logger_raw`] function to
-//! shut down the global logger before exiting:
+//! function to initialize a logger.
//!
//! ```rust
//! # extern crate log;
-//! # use log::{Level, LevelFilter, SetLoggerError, ShutdownLoggerError,
-//! # Metadata};
+//! # 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) {}
-//! # }
-//! # impl SimpleLogger {
//! # fn flush(&self) {}
//! # }
//! # fn main() {}
@@ -214,12 +212,6 @@
//! })
//! }
//! }
-//! pub fn shutdown() -> Result<(), ShutdownLoggerError> {
-//! log::shutdown_logger_raw().map(|logger| {
-//! let logger = unsafe { &*(logger as *const SimpleLogger) };
-//! logger.flush();
-//! })
-//! }
//! ```
//!
//! # Features
@@ -241,7 +233,6 @@
//! [`set_logger`]: fn.set_logger.html
//! [`MaxLevelFilter`]: struct.MaxLevelFilter.html
//! [`set_logger_raw`]: fn.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
@@ -275,7 +266,6 @@ use std::cmp;
use std::error;
use std::fmt;
use std::mem;
-use std::ops::Deref;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
@@ -283,29 +273,15 @@ use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
mod macros;
mod serde;
-// The setup here is a bit weird to make shutdown_logger_raw work.
-//
-// There are four different states that we care about: the logger's
+// 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), the logger's active, or the logger is
-// shut down after calling shutdown_logger_raw.
+// LOGGER hasn't actually been set yet), or the logger's active.
//
// 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.
-//
-// The shutdown_logger_raw routine needs to make sure that no threads are
-// actively logging before it returns. The number of actively logging threads is
-// tracked in the REFCOUNT static. The routine first sets STATE back to
-// INITIALIZING. All logging calls past that point will immediately return
-// without accessing the logger. At that point, the at_exit routine just waits
-// for the refcount to reach 0 before deallocating the logger. Note that the
-// refcount does not necessarily monotonically decrease at this point, as new
-// log calls still increment and decrement it, but the interval in between is
-// small enough that the wait is really just for the active log calls to finish.
static mut LOGGER: *const Log = &NopLogger;
static STATE: AtomicUsize = ATOMIC_USIZE_INIT;
-static REFCOUNT: AtomicUsize = ATOMIC_USIZE_INIT;
const UNINITIALIZED: usize = 0;
const INITIALIZING: usize = 1;
@@ -317,7 +293,6 @@ static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DE
static SET_LOGGER_ERROR: &'static str = "attempted to set a logger after the logging system \
was already initialized";
-static SHUTDOWN_LOGGER_ERROR: &'static str = "attempted to shut down the logger without an active logger";
static LEVEL_PARSE_ERROR: &'static str = "attempted to convert a string that doesn't match an existing log level";
/// An enum representing the available verbosity levels of the logger.
@@ -613,6 +588,7 @@ impl LevelFilter {
/// record.location().module_path(),
/// record.args());
/// }
+/// fn flush(&self) {}
/// }
/// ```
///
@@ -691,6 +667,7 @@ impl<'a> Record<'a> {
/// println!("{} - {}", record.level(), record.args());
/// }
/// }
+/// fn flush(&self) {}
/// }
///
/// # fn main(){}
@@ -729,6 +706,9 @@ pub trait Log: Sync + Send {
/// 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
@@ -740,6 +720,7 @@ impl Log for NopLogger {
}
fn log(&self, _: &Record) {}
+ fn flush(&self) {}
}
/// The location of a log message.
@@ -776,6 +757,7 @@ impl Log for NopLogger {
/// location.line(),
/// record.args());
/// }
+/// fn flush(&self) {}
/// }
/// ```
///
@@ -906,6 +888,7 @@ pub fn max_level() -> LevelFilter {
/// println!("Rust says: {} - {}", record.level(), record.args());
/// }
/// }
+/// fn flush(&self) {}
/// }
///
/// fn try_init() -> Result<(), SetLoggerError> {
@@ -981,8 +964,7 @@ pub fn set_logger(logger: Box<Log>, filter: LevelFilter) {
/// # Safety
///
/// The pointer returned by `make_logger` must remain valid for the entire
-/// duration of the program or until [`shutdown_logger_raw`] is called. In
-/// addition, [`shutdown_logger`] *must not* be called after this function.
+/// duration of the program.
///
/// # Examples
///
@@ -1006,14 +988,15 @@ pub fn set_logger(logger: Box<Log>, filter: LevelFilter) {
/// println!("{} - {}", record.level(), record.args());
/// }
/// }
+/// fn flush(&self) {}
/// }
///
/// # fn main(){
/// unsafe {
-/// log::set_logger_raw(|max_log_level| {
+/// log::set_logger_raw(|max_log_level| {
/// max_log_level.set(LevelFilter::Info);
/// &MY_LOGGER as *const MyLogger
-/// })
+/// })
/// };
///
/// info!("hello log");
@@ -1023,8 +1006,6 @@ pub fn set_logger(logger: Box<Log>, filter: LevelFilter) {
/// ```
///
/// [`set_logger`]: fn.set_logger.html
-/// [`shutdown_logger`]: fn.shutdown_logger.html
-/// [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html
pub unsafe fn set_logger_raw<M>(make_logger: M) -> Result<(), SetLoggerError>
where M: FnOnce(MaxLevelFilter) -> *const Log
{
@@ -1037,55 +1018,6 @@ pub unsafe fn set_logger_raw<M>(make_logger: M) -> Result<(), SetLoggerError>
Ok(())
}
-/// Shuts down the global logger.
-///
-/// This function may only be called once in the lifetime of a program, and may
-/// not be called before `set_logger`. Once the global logger has been shut
-/// down, it can no longer be re-initialized by `set_logger`. Any log events
-/// that occur after the call to `shutdown_logger` completes will be ignored.
-///
-/// The logger that was originally created by the call to to `set_logger` is
-/// returned on success. At that point it is guaranteed that no other threads
-/// are concurrently accessing the logger object.
-#[cfg(feature = "use_std")]
-pub fn shutdown_logger() -> Result<Box<Log>, ShutdownLoggerError> {
- shutdown_logger_raw().map(|l| unsafe { mem::transmute(l) })
-}
-
-/// Shuts down the global logger.
-///
-/// This function is similar to `shutdown_logger` except that it is usable in
-/// `no_std` code.
-///
-/// This function may only be called once in the lifetime of a program, and may
-/// not be called before `set_logger_raw`. Once the global logger has been shut
-/// down, it can no longer be re-initialized by `set_logger_raw`. Any log
-/// events that occur after the call to `shutdown_logger_raw` completes will be
-/// ignored.
-///
-/// The pointer that was originally passed to `set_logger_raw` is returned on
-/// success. At that point it is guaranteed that no other threads are
-/// concurrently accessing the logger object.
-pub fn shutdown_logger_raw() -> Result<*const Log, ShutdownLoggerError> {
- // Set the global log level to stop other thread from logging
- MAX_LOG_LEVEL_FILTER.store(0, Ordering::SeqCst);
-
- // Set to INITIALIZING to prevent re-initialization after
- if STATE.compare_and_swap(INITIALIZED, INITIALIZING, Ordering::SeqCst) != INITIALIZED {
- return Err(ShutdownLoggerError(()));
- }
-
- while REFCOUNT.load(Ordering::SeqCst) != 0 {
- // FIXME add a sleep here when it doesn't involve timers
- }
-
- unsafe {
- let logger = LOGGER;
- LOGGER = &NopLogger;
- Ok(logger)
- }
-}
-
/// The type returned by [`set_logger`] if [`set_logger`] has already been called.
/// [`set_logger`]: fn.set_logger.html
#[allow(missing_copy_implementations)]
@@ -1106,28 +1038,6 @@ impl error::Error for SetLoggerError {
}
}
-/// The type returned by [`shutdown_logger_raw`] if [`shutdown_logger_raw`] has
-/// already been called or if [`set_logger_raw`] has not been called yet.
-/// [`set_logger_raw`]: fn.set_logger_raw.html
-/// [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html
-#[allow(missing_copy_implementations)]
-#[derive(Debug)]
-pub struct ShutdownLoggerError(());
-
-impl fmt::Display for ShutdownLoggerError {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.write_str(SHUTDOWN_LOGGER_ERROR)
- }
-}
-
-// The Error trait is not available in libcore
-#[cfg(feature = "use_std")]
-impl error::Error for ShutdownLoggerError {
- fn description(&self) -> &str {
- SHUTDOWN_LOGGER_ERROR
- }
-}
-
/// 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)]
@@ -1190,29 +1100,11 @@ mod panic {
}
}
-struct LoggerGuard(&'static Log);
-
-impl Drop for LoggerGuard {
- fn drop(&mut self) {
- REFCOUNT.fetch_sub(1, Ordering::SeqCst);
- }
-}
-
-impl Deref for LoggerGuard {
- type Target = Log;
-
- fn deref(&self) -> &(Log + 'static) {
- self.0
- }
-}
-
-fn logger() -> Option<LoggerGuard> {
- REFCOUNT.fetch_add(1, Ordering::SeqCst);
+fn logger() -> Option<&'static Log> {
if STATE.load(Ordering::SeqCst) != INITIALIZED {
- REFCOUNT.fetch_sub(1, Ordering::SeqCst);
None
} else {
- Some(LoggerGuard(unsafe { &*LOGGER }))
+ Some(unsafe { &*LOGGER })
}
}
|
diff --git a/tests/filters.rs b/tests/filters.rs
index f40af728e..5fc55b2d4 100644
--- a/tests/filters.rs
+++ b/tests/filters.rs
@@ -29,6 +29,7 @@ impl Log for Logger {
fn log(&self, record: &Record) {
*self.0.last_log.lock().unwrap() = Some(record.level());
}
+ fn flush(&self) {}
}
fn main() {
diff --git a/tests/max_level_features/main.rs b/tests/max_level_features/main.rs
index 49f607d84..168f0249e 100644
--- a/tests/max_level_features/main.rs
+++ b/tests/max_level_features/main.rs
@@ -30,6 +30,8 @@ impl Log for Logger {
fn log(&self, record: &Record) {
*self.0.last_log.lock().unwrap() = Some(record.level());
}
+
+ fn flush(&self) {}
}
fn main() {
|
Remove logger shutdown
This adds some complexity to the logger plus extra cost on all logger calls. In our discussion of this issue the review team also concluded that it would be prudent to maybe add a top-level flushing method to explicitly ensure that a common part of shutdown, flushing, can still be manually performed. Flushing would be a noop by default.
|
Hi all,
I'm interested in diving into this one, but I could use a little guidance. Is this about exposing a `flush`, or removing `shutdown`? Or, rather, is it about removing the state (and therefore the check) from the logger's state machine?
Thanks!
All of the above! Removing shutdown allows https://github.com/rust-lang-nursery/log/blob/master/src/lib.rs#L264 and the related logic to go away. Flush is just a new method on `Log` with a default implementation.
|
2017-06-05T19:55:04Z
|
0.3
|
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
|
rust-lang/log
| 184
|
rust-lang__log-184
|
[
"182"
] |
5fac11ad3ba99dacd652c2bab92f6416e93a6115
|
diff --git a/src/lib.rs b/src/lib.rs
index 8ca360c1c..c6eaa2651 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -269,8 +269,7 @@ const INITIALIZED: usize = 2;
static MAX_LOG_LEVEL_FILTER: AtomicUsize = ATOMIC_USIZE_INIT;
-static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO",
- "DEBUG", "TRACE"];
+static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
static SET_LOGGER_ERROR: &'static str = "attempted to set a logger after the logging system \
was already initialized";
@@ -369,8 +368,8 @@ fn eq_ignore_ascii_case(a: &str, b: &str) -> bool {
if a.len() == b.len() {
a.bytes()
- .zip(b.bytes())
- .all(|(a, b)| to_ascii_uppercase(a) == to_ascii_uppercase(b))
+ .zip(b.bytes())
+ .all(|(a, b)| to_ascii_uppercase(a) == to_ascii_uppercase(b))
} else {
false
}
@@ -379,12 +378,14 @@ fn eq_ignore_ascii_case(a: &str, b: &str) -> bool {
impl FromStr for Level {
type Err = ParseLevelError;
fn from_str(level: &str) -> Result<Level, Self::Err> {
- 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(()))
+ 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(()))
}
}
@@ -402,7 +403,7 @@ impl Level {
3 => Some(Level::Info),
4 => Some(Level::Debug),
5 => Some(Level::Trace),
- _ => None
+ _ => None,
}
}
@@ -491,9 +492,11 @@ impl Ord for LevelFilter {
impl FromStr for LevelFilter {
type Err = ParseLevelError;
fn from_str(level: &str) -> Result<LevelFilter, Self::Err> {
- ok_or(LOG_LEVEL_NAMES.iter()
- .position(|&name| eq_ignore_ascii_case(name, level))
- .map(|p| LevelFilter::from_usize(p).unwrap()), ParseLevelError(()))
+ ok_or(LOG_LEVEL_NAMES
+ .iter()
+ .position(|&name| eq_ignore_ascii_case(name, level))
+ .map(|p| LevelFilter::from_usize(p).unwrap()),
+ ParseLevelError(()))
}
}
@@ -512,7 +515,7 @@ impl LevelFilter {
3 => Some(LevelFilter::Info),
4 => Some(LevelFilter::Debug),
5 => Some(LevelFilter::Trace),
- _ => None
+ _ => None,
}
}
/// Returns the most verbose logging level filter.
@@ -668,7 +671,7 @@ impl<'a> Metadata<'a> {
}
/// A trait encapsulating the operations required of a logger
-pub trait Log: Sync+Send {
+pub trait Log: Sync + Send {
/// Determines if a log message with the specified metadata would be
/// logged.
///
@@ -689,7 +692,9 @@ pub trait Log: Sync+Send {
struct NopLogger;
impl Log for NopLogger {
- fn enabled(&self, _: &Metadata) -> bool { false }
+ fn enabled(&self, _: &Metadata) -> bool {
+ false
+ }
fn log(&self, _: &Record) {}
}
@@ -823,7 +828,8 @@ pub fn max_level() -> LevelFilter {
/// Requires the `use_std` feature (enabled by default).
#[cfg(feature = "use_std")]
pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
- where M: FnOnce(MaxLevelFilter) -> Box<Log> {
+ where M: FnOnce(MaxLevelFilter) -> Box<Log>
+{
unsafe { set_logger_raw(|max_level| mem::transmute(make_logger(max_level))) }
}
@@ -850,9 +856,9 @@ pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
/// duration of the program or until `shutdown_logger_raw` is called. In
/// addition, `shutdown_logger` *must not* be called after this function.
pub unsafe fn set_logger_raw<M>(make_logger: M) -> Result<(), SetLoggerError>
- where M: FnOnce(MaxLevelFilter) -> *const Log {
- if STATE.compare_and_swap(UNINITIALIZED, INITIALIZING,
- Ordering::SeqCst) != UNINITIALIZED {
+ where M: FnOnce(MaxLevelFilter) -> *const Log
+{
+ if STATE.compare_and_swap(UNINITIALIZED, INITIALIZING, Ordering::SeqCst) != UNINITIALIZED {
return Err(SetLoggerError(()));
}
@@ -895,8 +901,7 @@ pub fn shutdown_logger_raw() -> Result<*const Log, ShutdownLoggerError> {
MAX_LOG_LEVEL_FILTER.store(0, Ordering::SeqCst);
// Set to INITIALIZING to prevent re-initialization after
- if STATE.compare_and_swap(INITIALIZED, INITIALIZING,
- Ordering::SeqCst) != INITIALIZED {
+ if STATE.compare_and_swap(INITIALIZED, INITIALIZING, Ordering::SeqCst) != INITIALIZED {
return Err(ShutdownLoggerError(()));
}
@@ -949,7 +954,7 @@ impl fmt::Display for ShutdownLoggerError {
#[cfg(feature = "use_std")]
impl error::Error for ShutdownLoggerError {
fn description(&self) -> &str {
- SHUTDOWN_LOGGER_ERROR
+ SHUTDOWN_LOGGER_ERROR
}
}
@@ -993,9 +998,11 @@ mod panic {
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
- None => match info.payload().downcast_ref::<String>() {
- Some(s) => &s[..],
- None => "Box<Any>",
+ None => {
+ match info.payload().downcast_ref::<String>() {
+ Some(s) => &s[..],
+ None => "Box<Any>",
+ }
}
};
@@ -1044,7 +1051,10 @@ fn logger() -> Option<LoggerGuard> {
#[doc(hidden)]
pub fn __enabled(level: Level, target: &str) -> bool {
if let Some(logger) = logger() {
- logger.enabled(&Metadata { level: level, target: target })
+ logger.enabled(&Metadata {
+ level: level,
+ target: target,
+ })
} else {
false
}
@@ -1054,8 +1064,7 @@ pub fn __enabled(level: Level, target: &str) -> bool {
// This is not considered part of the crate's public API. It is subject to
// change at any time.
#[doc(hidden)]
-pub fn __log(level: Level, target: &str, loc: &Location,
- args: fmt::Arguments) {
+pub fn __log(level: Level, target: &str, loc: &Location, args: fmt::Arguments) {
if let Some(logger) = logger() {
let record = Record {
metadata: Metadata {
@@ -1063,7 +1072,7 @@ pub fn __log(level: Level, target: &str, loc: &Location,
target: target,
},
location: loc,
- args: args
+ args: args,
};
logger.log(&record)
}
@@ -1078,17 +1087,17 @@ pub fn __static_max_level() -> LevelFilter {
if !cfg!(debug_assertions) {
// This is a release build. Check `release_max_level_*` first.
if cfg!(feature = "release_max_level_off") {
- return LevelFilter::Off
+ return LevelFilter::Off;
} else if cfg!(feature = "release_max_level_error") {
- return LevelFilter::Error
+ return LevelFilter::Error;
} else if cfg!(feature = "release_max_level_warn") {
- return LevelFilter::Warn
+ return LevelFilter::Warn;
} else if cfg!(feature = "release_max_level_info") {
- return LevelFilter::Info
+ return LevelFilter::Info;
} else if cfg!(feature = "release_max_level_debug") {
- return LevelFilter::Debug
+ return LevelFilter::Debug;
} else if cfg!(feature = "release_max_level_trace") {
- return LevelFilter::Trace
+ return LevelFilter::Trace;
}
}
if cfg!(feature = "max_level_off") {
@@ -1108,99 +1117,96 @@ pub fn __static_max_level() -> LevelFilter {
#[cfg(test)]
mod tests {
- extern crate std;
- use tests::std::string::ToString;
- use super::{Level, LevelFilter, ParseLevelError};
-
- #[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 = "use_std")]
- fn test_error_trait() {
- use std::error::Error;
- use super::SetLoggerError;
- let e = SetLoggerError(());
- assert_eq!(e.description(), "attempted to set a logger after the logging system \
+ extern crate std;
+ use tests::std::string::ToString;
+ use super::{Level, LevelFilter, ParseLevelError};
+
+ #[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 = "use_std")]
+ fn test_error_trait() {
+ use std::error::Error;
+ use super::SetLoggerError;
+ let e = SetLoggerError(());
+ assert_eq!(e.description(),
+ "attempted to set a logger after the logging system \
was already initialized");
- }
+ }
}
diff --git a/src/serde.rs b/src/serde.rs
index 579237d74..bfb9174cb 100644
--- a/src/serde.rs
+++ b/src/serde.rs
@@ -2,7 +2,8 @@
extern crate serde;
use self::serde::ser::{Serialize, Serializer};
-use self::serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, EnumAccess, VariantAccess, Error};
+use self::serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, EnumAccess,
+ VariantAccess, Error};
use {Level, LevelFilter, LOG_LEVEL_NAMES};
@@ -42,9 +43,7 @@ impl<'de> Deserialize<'de> for Level {
where E: Error
{
// Case insensitive.
- FromStr::from_str(s).map_err(|_| {
- Error::unknown_variant(s, &LOG_LEVEL_NAMES[1..])
- })
+ FromStr::from_str(s).map_err(|_| Error::unknown_variant(s, &LOG_LEVEL_NAMES[1..]))
}
}
@@ -113,9 +112,7 @@ impl<'de> Deserialize<'de> for LevelFilter {
where E: Error
{
// Case insensitive.
- FromStr::from_str(s).map_err(|_| {
- Error::unknown_variant(s, &LOG_LEVEL_NAMES)
- })
+ FromStr::from_str(s).map_err(|_| Error::unknown_variant(s, &LOG_LEVEL_NAMES))
}
}
@@ -159,13 +156,27 @@ mod tests {
use {Level, LevelFilter};
+ fn level_token(variant: &'static str) -> Token {
+ Token::UnitVariant {
+ name: "Level",
+ variant: variant,
+ }
+ }
+
+ fn level_filter_token(variant: &'static str) -> Token {
+ Token::UnitVariant {
+ name: "LevelFilter",
+ variant: variant,
+ }
+ }
+
#[test]
fn test_level_ser_de() {
- let cases = [(Level::Error, [Token::UnitVariant { name: "Level", variant: "ERROR" }]),
- (Level::Warn, [Token::UnitVariant { name: "Level", variant: "WARN" }]),
- (Level::Info, [Token::UnitVariant { name: "Level", variant: "INFO" }]),
- (Level::Debug, [Token::UnitVariant { name: "Level", variant: "DEBUG" }]),
- (Level::Trace, [Token::UnitVariant { name: "Level", variant: "TRACE" }])];
+ 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);
@@ -174,11 +185,11 @@ mod tests {
#[test]
fn test_level_case_insensitive() {
- let cases = [(Level::Error, [Token::UnitVariant { name: "Level", variant: "error" }]),
- (Level::Warn, [Token::UnitVariant { name: "Level", variant: "warn" }]),
- (Level::Info, [Token::UnitVariant { name: "Level", variant: "info" }]),
- (Level::Debug, [Token::UnitVariant { name: "Level", variant: "debug" }]),
- (Level::Trace, [Token::UnitVariant { name: "Level", variant: "trace" }])];
+ 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);
@@ -187,19 +198,19 @@ mod tests {
#[test]
fn test_level_de_error() {
- assert_de_tokens_error::<Level>(
- &[Token::UnitVariant { name: "Level", variant: "errorx" }],
- "unknown variant `errorx`, expected one of `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`");
+ let msg = "unknown variant `errorx`, expected one of \
+ `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`";
+ assert_de_tokens_error::<Level>(&[level_token("errorx")], msg);
}
#[test]
fn test_level_filter_ser_de() {
- let cases = [(LevelFilter::Off, [Token::UnitVariant { name: "LevelFilter", variant: "OFF" }]),
- (LevelFilter::Error, [Token::UnitVariant { name: "LevelFilter", variant: "ERROR" }]),
- (LevelFilter::Warn, [Token::UnitVariant { name: "LevelFilter", variant: "WARN" }]),
- (LevelFilter::Info, [Token::UnitVariant { name: "LevelFilter", variant: "INFO" }]),
- (LevelFilter::Debug, [Token::UnitVariant { name: "LevelFilter", variant: "DEBUG" }]),
- (LevelFilter::Trace, [Token::UnitVariant { name: "LevelFilter", variant: "TRACE" }])];
+ 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);
@@ -208,12 +219,12 @@ mod tests {
#[test]
fn test_level_filter_case_insensitive() {
- let cases = [(LevelFilter::Off, [Token::UnitVariant { name: "LevelFilter", variant: "off" }]),
- (LevelFilter::Error, [Token::UnitVariant { name: "LevelFilter", variant: "error" }]),
- (LevelFilter::Warn, [Token::UnitVariant { name: "LevelFilter", variant: "warn" }]),
- (LevelFilter::Info, [Token::UnitVariant { name: "LevelFilter", variant: "info" }]),
- (LevelFilter::Debug, [Token::UnitVariant { name: "LevelFilter", variant: "debug" }]),
- (LevelFilter::Trace, [Token::UnitVariant { name: "LevelFilter", variant: "trace" }])];
+ 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);
@@ -222,8 +233,8 @@ mod tests {
#[test]
fn test_level_filter_de_error() {
- assert_de_tokens_error::<LevelFilter>(
- &[Token::UnitVariant { name: "LevelFilter", variant: "errorx" }],
- "unknown variant `errorx`, expected one of `OFF`, `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`");
+ let msg = "unknown variant `errorx`, expected one of \
+ `OFF`, `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`";
+ assert_de_tokens_error::<LevelFilter>(&[level_filter_token("errorx")], msg);
}
}
|
diff --git a/tests/filters.rs b/tests/filters.rs
index 0497c11c6..fc8cac863 100644
--- a/tests/filters.rs
+++ b/tests/filters.rs
@@ -1,4 +1,5 @@
-#[macro_use] extern crate log;
+#[macro_use]
+extern crate log;
use std::sync::{Arc, Mutex};
use log::{Level, LevelFilter, Log, Record, Metadata};
@@ -8,10 +9,9 @@ use log::MaxLevelFilter;
use log::set_logger;
#[cfg(not(feature = "use_std"))]
fn set_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
- where M: FnOnce(MaxLevelFilter) -> Box<Log> {
- unsafe {
- log::set_logger_raw(|x| std::mem::transmute(make_logger(x)))
- }
+ where M: FnOnce(MaxLevelFilter) -> Box<Log>
+{
+ unsafe { log::set_logger_raw(|x| std::mem::transmute(make_logger(x))) }
}
struct State {
@@ -34,13 +34,14 @@ impl Log for Logger {
fn main() {
let mut a = None;
set_logger(|max| {
- let me = Arc::new(State {
- last_log: Mutex::new(None),
- filter: max,
- });
- a = Some(me.clone());
- Box::new(Logger(me))
- }).unwrap();
+ let me = Arc::new(State {
+ last_log: Mutex::new(None),
+ filter: max,
+ });
+ a = Some(me.clone());
+ Box::new(Logger(me))
+ })
+ .unwrap();
let a = a.unwrap();
test(&a, LevelFilter::Off);
@@ -65,7 +66,7 @@ fn test(a: &State, filter: LevelFilter) {
last(&a, t(Level::Trace, filter));
fn t(lvl: Level, filter: LevelFilter) -> Option<Level> {
- if lvl <= filter {Some(lvl)} else {None}
+ if lvl <= filter { Some(lvl) } else { None }
}
}
|
Consider rustfmt
Moved from https://github.com/rust-lang-nursery/log/issues/150#issuecomment-304629732:
> Could we make `rust fmt` mandatory for this crate ?
|
I agree with using rustfmt.
I generally disagree with requiring rustfmt for a build to pass. The tradeoff is scaring away new contributors. If someone makes a PR, I would prefer that they remember it as a reasonable discussion about meaningful things, rather than as a struggle to satisfy a grumpy buildbot. If the code looks mostly fine then nobody will notice or care anyway. Somebody can run rustfmt every month or so and it takes 10 seconds to clean everything up, so there isn't really anything to gain from enforcing it in the build.
Well your take was more accurate to what I intended.
My idea was in fact to find a way to ensure the code was formated.
I use rustfmt regularly and when I used it on this crate in a branch, it touched a lot of lines that did not need to be formated and made my commit noisy.
I feel your idea of behind the scene occasional formating a better solution.
|
2017-05-30T04:05:16Z
|
0.3
|
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
|
rust-lang/log
| 162
|
rust-lang__log-162
|
[
"142"
] |
cf501f637578394612ea88f103e3b117cbf9f71e
|
diff --git a/env/src/lib.rs b/env/src/lib.rs
index 7e2f9da7e..b30d0ff69 100644
--- a/env/src/lib.rs
+++ b/env/src/lib.rs
@@ -17,7 +17,7 @@
//! #[macro_use] extern crate log;
//! extern crate env_logger;
//!
-//! use log::LogLevel;
+//! use log::Level;
//!
//! fn main() {
//! env_logger::init().unwrap();
@@ -25,7 +25,7 @@
//! debug!("this is a debug {}", "message");
//! error!("this is printed by default");
//!
-//! if log_enabled!(LogLevel::Info) {
+//! if log_enabled!(Level::Info) {
//! let x = 3 * 4; // expensive computation
//! info!("the answer was: {}", x);
//! }
@@ -80,7 +80,7 @@
//! form:
//!
//! ```text
-//! path::to::module=log_level
+//! path::to::module=level
//! ```
//!
//! The path to the module is rooted in the name of the crate it was compiled
@@ -89,12 +89,12 @@
//! Furthermore, this path is a prefix-search, so all modules nested in the
//! specified module will also have logging enabled.
//!
-//! The actual `log_level` is optional to specify. If omitted, all logging will
+//! The actual `level` is optional to specify. If omitted, all logging will
//! be enabled. If specified, it must be one of the strings `debug`, `error`,
//! `info`, `warn`, or `trace`.
//!
//! As the log level for a module is optional, the module to enable logging for
-//! is also optional. If only a `log_level` is provided, then the global log
+//! is also optional. If only a `level` is provided, then the global log
//! level for all modules is set to this value.
//!
//! Some examples of valid values of `RUST_LOG` are:
@@ -142,7 +142,7 @@ use std::io::prelude::*;
use std::io;
use std::mem;
-use log::{Log, LogLevel, LogLevelFilter, LogRecord, SetLoggerError, LogMetadata};
+use log::{Log, Level, LevelFilter, Record, SetLoggerError, Metadata};
#[cfg(feature = "regex")]
#[path = "regex.rs"]
@@ -163,7 +163,7 @@ pub enum LogTarget {
pub struct Logger {
directives: Vec<LogDirective>,
filter: Option<filter::Filter>,
- format: Box<Fn(&LogRecord) -> String + Sync + Send>,
+ format: Box<Fn(&Record) -> String + Sync + Send>,
target: LogTarget,
}
@@ -179,16 +179,16 @@ pub struct Logger {
/// extern crate env_logger;
///
/// use std::env;
-/// use log::{LogRecord, LogLevelFilter};
+/// use log::{Record, LevelFilter};
/// use env_logger::LogBuilder;
///
/// fn main() {
-/// let format = |record: &LogRecord| {
+/// let format = |record: &Record| {
/// format!("{} - {}", record.level(), record.args())
/// };
///
/// let mut builder = LogBuilder::new();
-/// builder.format(format).filter(None, LogLevelFilter::Info);
+/// builder.format(format).filter(None, LevelFilter::Info);
///
/// if env::var("RUST_LOG").is_ok() {
/// builder.parse(&env::var("RUST_LOG").unwrap());
@@ -203,7 +203,7 @@ pub struct Logger {
pub struct LogBuilder {
directives: Vec<LogDirective>,
filter: Option<filter::Filter>,
- format: Box<Fn(&LogRecord) -> String + Sync + Send>,
+ format: Box<Fn(&Record) -> String + Sync + Send>,
target: LogTarget,
}
@@ -213,7 +213,7 @@ impl LogBuilder {
LogBuilder {
directives: Vec::new(),
filter: None,
- format: Box::new(|record: &LogRecord| {
+ format: Box::new(|record: &Record| {
format!("{}:{}: {}", record.level(),
record.location().module_path(), record.args())
}),
@@ -227,7 +227,7 @@ impl LogBuilder {
/// If no module is provided then the filter will apply to all log messages.
pub fn filter(&mut self,
module: Option<&str>,
- level: LogLevelFilter) -> &mut Self {
+ level: LevelFilter) -> &mut Self {
self.directives.push(LogDirective {
name: module.map(|s| s.to_string()),
level: level,
@@ -240,7 +240,7 @@ impl LogBuilder {
/// This function is called on each record logged to produce a string which
/// is actually printed out.
pub fn format<F: 'static>(&mut self, format: F) -> &mut Self
- where F: Fn(&LogRecord) -> String + Sync + Send
+ where F: Fn(&Record) -> String + Sync + Send
{
self.format = Box::new(format);
self
@@ -288,7 +288,7 @@ impl LogBuilder {
// Adds the default filter if none exist
self.directives.push(LogDirective {
name: None,
- level: LogLevelFilter::Error,
+ level: LevelFilter::Error,
});
} else {
// Sort the directives by length of their name, this allows a
@@ -320,13 +320,13 @@ impl Logger {
builder.build()
}
- pub fn filter(&self) -> LogLevelFilter {
+ pub fn filter(&self) -> LevelFilter {
self.directives.iter()
.map(|d| d.level).max()
- .unwrap_or(LogLevelFilter::Off)
+ .unwrap_or(LevelFilter::Off)
}
- fn enabled(&self, level: LogLevel, target: &str) -> bool {
+ fn enabled(&self, level: Level, target: &str) -> bool {
// Search for the longest match, the vector is assumed to be pre-sorted.
for directive in self.directives.iter().rev() {
match directive.name {
@@ -341,11 +341,11 @@ impl Logger {
}
impl Log for Logger {
- fn enabled(&self, metadata: &LogMetadata) -> bool {
+ fn enabled(&self, metadata: &Metadata) -> bool {
self.enabled(metadata.level(), metadata.target())
}
- fn log(&self, record: &LogRecord) {
+ fn log(&self, record: &Record) {
if !Log::enabled(self, record.metadata()) {
return;
}
@@ -367,7 +367,7 @@ impl Log for Logger {
struct LogDirective {
name: Option<String>,
- level: LogLevelFilter,
+ level: LevelFilter,
}
/// Initializes the global logger with an env logger.
@@ -407,10 +407,10 @@ fn parse_logging_spec(spec: &str) -> (Vec<LogDirective>, Option<filter::Filter>)
// treat that as a global fallback
match part0.parse() {
Ok(num) => (num, None),
- Err(_) => (LogLevelFilter::max(), Some(part0)),
+ Err(_) => (LevelFilter::max(), Some(part0)),
}
}
- (Some(part0), Some(""), None) => (LogLevelFilter::max(), Some(part0)),
+ (Some(part0), Some(""), None) => (LevelFilter::max(), Some(part0)),
(Some(part0), Some(part1), None) => {
match part1.parse() {
Ok(num) => (num, Some(part0)),
@@ -448,7 +448,7 @@ fn parse_logging_spec(spec: &str) -> (Vec<LogDirective>, Option<filter::Filter>)
#[cfg(test)]
mod tests {
- use log::{LogLevel, LogLevelFilter};
+ use log::{Level, LevelFilter};
use super::{LogBuilder, Logger, LogDirective, parse_logging_spec};
@@ -460,27 +460,27 @@ mod tests {
#[test]
fn filter_info() {
- let logger = LogBuilder::new().filter(None, LogLevelFilter::Info).build();
- assert!(logger.enabled(LogLevel::Info, "crate1"));
- assert!(!logger.enabled(LogLevel::Debug, "crate1"));
+ let logger = LogBuilder::new().filter(None, LevelFilter::Info).build();
+ assert!(logger.enabled(Level::Info, "crate1"));
+ assert!(!logger.enabled(Level::Debug, "crate1"));
}
#[test]
fn filter_beginning_longest_match() {
let logger = LogBuilder::new()
- .filter(Some("crate2"), LogLevelFilter::Info)
- .filter(Some("crate2::mod"), LogLevelFilter::Debug)
- .filter(Some("crate1::mod1"), LogLevelFilter::Warn)
+ .filter(Some("crate2"), LevelFilter::Info)
+ .filter(Some("crate2::mod"), LevelFilter::Debug)
+ .filter(Some("crate1::mod1"), LevelFilter::Warn)
.build();
- assert!(logger.enabled(LogLevel::Debug, "crate2::mod1"));
- assert!(!logger.enabled(LogLevel::Debug, "crate2"));
+ assert!(logger.enabled(Level::Debug, "crate2::mod1"));
+ assert!(!logger.enabled(Level::Debug, "crate2"));
}
#[test]
fn parse_default() {
let logger = LogBuilder::new().parse("info,crate1::mod1=warn").build();
- assert!(logger.enabled(LogLevel::Warn, "crate1::mod1"));
- assert!(logger.enabled(LogLevel::Info, "crate2::mod2"));
+ assert!(logger.enabled(Level::Warn, "crate1::mod1"));
+ assert!(logger.enabled(Level::Info, "crate2::mod2"));
}
#[test]
@@ -488,66 +488,66 @@ mod tests {
let logger = make_logger(vec![
LogDirective {
name: Some("crate2".to_string()),
- level: LogLevelFilter::Info
+ level: LevelFilter::Info
},
LogDirective {
name: Some("crate1::mod1".to_string()),
- level: LogLevelFilter::Warn
+ level: LevelFilter::Warn
}
]);
- assert!(logger.enabled(LogLevel::Warn, "crate1::mod1"));
- assert!(!logger.enabled(LogLevel::Info, "crate1::mod1"));
- assert!(logger.enabled(LogLevel::Info, "crate2"));
- assert!(!logger.enabled(LogLevel::Debug, "crate2"));
+ assert!(logger.enabled(Level::Warn, "crate1::mod1"));
+ assert!(!logger.enabled(Level::Info, "crate1::mod1"));
+ assert!(logger.enabled(Level::Info, "crate2"));
+ assert!(!logger.enabled(Level::Debug, "crate2"));
}
#[test]
fn no_match() {
let logger = make_logger(vec![
- LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info },
- LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn }
+ LogDirective { name: Some("crate2".to_string()), level: LevelFilter::Info },
+ LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
- assert!(!logger.enabled(LogLevel::Warn, "crate3"));
+ assert!(!logger.enabled(Level::Warn, "crate3"));
}
#[test]
fn match_beginning() {
let logger = make_logger(vec![
- LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info },
- LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn }
+ LogDirective { name: Some("crate2".to_string()), level: LevelFilter::Info },
+ LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
- assert!(logger.enabled(LogLevel::Info, "crate2::mod1"));
+ assert!(logger.enabled(Level::Info, "crate2::mod1"));
}
#[test]
fn match_beginning_longest_match() {
let logger = make_logger(vec![
- LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info },
- LogDirective { name: Some("crate2::mod".to_string()), level: LogLevelFilter::Debug },
- LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn }
+ LogDirective { name: Some("crate2".to_string()), level: LevelFilter::Info },
+ LogDirective { name: Some("crate2::mod".to_string()), level: LevelFilter::Debug },
+ LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
- assert!(logger.enabled(LogLevel::Debug, "crate2::mod1"));
- assert!(!logger.enabled(LogLevel::Debug, "crate2"));
+ assert!(logger.enabled(Level::Debug, "crate2::mod1"));
+ assert!(!logger.enabled(Level::Debug, "crate2"));
}
#[test]
fn match_default() {
let logger = make_logger(vec![
- LogDirective { name: None, level: LogLevelFilter::Info },
- LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn }
+ LogDirective { name: None, level: LevelFilter::Info },
+ LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
- assert!(logger.enabled(LogLevel::Warn, "crate1::mod1"));
- assert!(logger.enabled(LogLevel::Info, "crate2::mod2"));
+ assert!(logger.enabled(Level::Warn, "crate1::mod1"));
+ assert!(logger.enabled(Level::Info, "crate2::mod2"));
}
#[test]
fn zero_level() {
let logger = make_logger(vec![
- LogDirective { name: None, level: LogLevelFilter::Info },
- LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Off }
+ LogDirective { name: None, level: LevelFilter::Info },
+ LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Off }
]);
- assert!(!logger.enabled(LogLevel::Error, "crate1::mod1"));
- assert!(logger.enabled(LogLevel::Info, "crate2::mod2"));
+ assert!(!logger.enabled(Level::Error, "crate1::mod1"));
+ assert!(logger.enabled(Level::Info, "crate2::mod2"));
}
#[test]
@@ -555,13 +555,13 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1::mod1=error,crate1::mod2,crate2=debug");
assert_eq!(dirs.len(), 3);
assert_eq!(dirs[0].name, Some("crate1::mod1".to_string()));
- assert_eq!(dirs[0].level, LogLevelFilter::Error);
+ assert_eq!(dirs[0].level, LevelFilter::Error);
assert_eq!(dirs[1].name, Some("crate1::mod2".to_string()));
- assert_eq!(dirs[1].level, LogLevelFilter::max());
+ assert_eq!(dirs[1].level, LevelFilter::max());
assert_eq!(dirs[2].name, Some("crate2".to_string()));
- assert_eq!(dirs[2].level, LogLevelFilter::Debug);
+ assert_eq!(dirs[2].level, LevelFilter::Debug);
assert!(filter.is_none());
}
@@ -571,37 +571,37 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1::mod1=warn=info,crate2=debug");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LogLevelFilter::Debug);
+ assert_eq!(dirs[0].level, LevelFilter::Debug);
assert!(filter.is_none());
}
#[test]
- fn parse_logging_spec_invalid_log_level() {
+ fn parse_logging_spec_invalid_level() {
// test parse_logging_spec with 'noNumber' as log level
let (dirs, filter) = parse_logging_spec("crate1::mod1=noNumber,crate2=debug");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LogLevelFilter::Debug);
+ assert_eq!(dirs[0].level, LevelFilter::Debug);
assert!(filter.is_none());
}
#[test]
- fn parse_logging_spec_string_log_level() {
+ fn parse_logging_spec_string_level() {
// test parse_logging_spec with 'warn' as log level
let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2=warn");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LogLevelFilter::Warn);
+ assert_eq!(dirs[0].level, LevelFilter::Warn);
assert!(filter.is_none());
}
#[test]
- fn parse_logging_spec_empty_log_level() {
+ fn parse_logging_spec_empty_level() {
// test parse_logging_spec with '' as log level
let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2=");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LogLevelFilter::max());
+ assert_eq!(dirs[0].level, LevelFilter::max());
assert!(filter.is_none());
}
@@ -611,9 +611,9 @@ mod tests {
let (dirs, filter) = parse_logging_spec("warn,crate2=debug");
assert_eq!(dirs.len(), 2);
assert_eq!(dirs[0].name, None);
- assert_eq!(dirs[0].level, LogLevelFilter::Warn);
+ assert_eq!(dirs[0].level, LevelFilter::Warn);
assert_eq!(dirs[1].name, Some("crate2".to_string()));
- assert_eq!(dirs[1].level, LogLevelFilter::Debug);
+ assert_eq!(dirs[1].level, LevelFilter::Debug);
assert!(filter.is_none());
}
@@ -622,13 +622,13 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1::mod1=error,crate1::mod2,crate2=debug/abc");
assert_eq!(dirs.len(), 3);
assert_eq!(dirs[0].name, Some("crate1::mod1".to_string()));
- assert_eq!(dirs[0].level, LogLevelFilter::Error);
+ assert_eq!(dirs[0].level, LevelFilter::Error);
assert_eq!(dirs[1].name, Some("crate1::mod2".to_string()));
- assert_eq!(dirs[1].level, LogLevelFilter::max());
+ assert_eq!(dirs[1].level, LevelFilter::max());
assert_eq!(dirs[2].name, Some("crate2".to_string()));
- assert_eq!(dirs[2].level, LogLevelFilter::Debug);
+ assert_eq!(dirs[2].level, LevelFilter::Debug);
assert!(filter.is_some() && filter.unwrap().to_string() == "abc");
}
@@ -637,7 +637,7 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1::mod1=error=warn,crate2=debug/a.c");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
- assert_eq!(dirs[0].level, LogLevelFilter::Debug);
+ assert_eq!(dirs[0].level, LevelFilter::Debug);
assert!(filter.is_some() && filter.unwrap().to_string() == "a.c");
}
@@ -646,7 +646,7 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1/a*c");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate1".to_string()));
- assert_eq!(dirs[0].level, LogLevelFilter::max());
+ assert_eq!(dirs[0].level, LevelFilter::max());
assert!(filter.is_some() && filter.unwrap().to_string() == "a*c");
}
}
diff --git a/src/lib.rs b/src/lib.rs
index 04a410e14..60b685b9e 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -101,16 +101,16 @@
//! ```rust
//! extern crate log;
//!
-//! use log::{LogRecord, LogLevel, LogMetadata};
+//! use log::{Record, Level, Metadata};
//!
//! struct SimpleLogger;
//!
//! impl log::Log for SimpleLogger {
-//! fn enabled(&self, metadata: &LogMetadata) -> bool {
-//! metadata.level() <= LogLevel::Info
+//! fn enabled(&self, metadata: &Metadata) -> bool {
+//! metadata.level() <= Level::Info
//! }
//!
-//! fn log(&self, record: &LogRecord) {
+//! fn log(&self, record: &Record) {
//! if self.enabled(record.metadata()) {
//! println!("{} - {}", record.level(), record.args());
//! }
@@ -121,8 +121,8 @@
//! ```
//!
//! Loggers are installed by calling the [`set_logger`] function. It takes a
-//! closure which is provided a [`MaxLogLevelFilter`] token and returns a
-//! [`Log`] trait object. The [`MaxLogLevelFilter`] token controls the global
+//! closure which is provided a [`MaxLevelFilter`] token and returns a
+//! [`Log`] trait object. The [`MaxLevelFilter`] token controls the global
//! maximum log level. The logging facade uses this as an optimization to
//! improve performance of log messages at levels that are disabled. In the
//! case of our example logger, we'll want to set the maximum log level to
@@ -133,17 +133,17 @@
//!
//! ```rust
//! # extern crate log;
-//! # use log::{LogLevel, LogLevelFilter, SetLoggerError, LogMetadata};
+//! # use log::{Level, LevelFilter, SetLoggerError, Metadata};
//! # struct SimpleLogger;
//! # impl log::Log for SimpleLogger {
-//! # fn enabled(&self, _: &LogMetadata) -> bool { false }
-//! # fn log(&self, _: &log::LogRecord) {}
+//! # fn enabled(&self, _: &Metadata) -> bool { false }
+//! # fn log(&self, _: &log::Record) {}
//! # }
//! # fn main() {}
//! # #[cfg(feature = "use_std")]
//! pub fn init() -> Result<(), SetLoggerError> {
-//! log::set_logger(|max_log_level| {
-//! max_log_level.set(LogLevelFilter::Info);
+//! log::set_logger(|max_level| {
+//! max_level.set(LevelFilter::Info);
//! Box::new(SimpleLogger)
//! })
//! }
@@ -160,12 +160,12 @@
//!
//! ```rust
//! # extern crate log;
-//! # use log::{LogLevel, LogLevelFilter, SetLoggerError, ShutdownLoggerError,
-//! # LogMetadata};
+//! # use log::{Level, LevelFilter, SetLoggerError, ShutdownLoggerError,
+//! # Metadata};
//! # struct SimpleLogger;
//! # impl log::Log for SimpleLogger {
-//! # fn enabled(&self, _: &LogMetadata) -> bool { false }
-//! # fn log(&self, _: &log::LogRecord) {}
+//! # fn enabled(&self, _: &Metadata) -> bool { false }
+//! # fn log(&self, _: &log::Record) {}
//! # }
//! # impl SimpleLogger {
//! # fn flush(&self) {}
@@ -173,9 +173,9 @@
//! # fn main() {}
//! pub fn init() -> Result<(), SetLoggerError> {
//! unsafe {
-//! log::set_logger_raw(|max_log_level| {
+//! log::set_logger_raw(|max_level| {
//! static LOGGER: SimpleLogger = SimpleLogger;
-//! max_log_level.set(LogLevelFilter::Info);
+//! max_level.set(LevelFilter::Info);
//! &SimpleLogger
//! })
//! }
@@ -189,9 +189,9 @@
//! ```
//!
//! [`Log`]: trait.Log.html
-//! [level_link]: enum.LogLevel.html
+//! [level_link]: enum.Level.html
//! [`set_logger`]: fn.set_logger.html
-//! [`MaxLogLevelFilter`]: struct.MaxLogLevelFilter.html
+//! [`MaxLevelFilter`]: struct.MaxLevelFilter.html
//! [`set_logger_raw`]: fn.set_logger_raw.html
//! [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html
@@ -258,17 +258,17 @@ static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO",
/// An enum representing the available verbosity levels of the logging framework.
///
-/// Typical usage includes: checking if a certain `LogLevel` is enabled with
-/// [`log_enabled!`](macro.log_enabled.html), specifying the `LogLevel` of
-/// [`log!`](macro.log.html), and comparing a `LogLevel` directly to a
-/// [`LogLevelFilter`](enum.LogLevelFilter.html).
+/// 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 LogLevel {
+pub enum Level {
/// The "error" level.
///
/// Designates very serious errors.
- Error = 1, // This way these line up with the discriminants for LogLevelFilter below
+ Error = 1, // This way these line up with the discriminants for LevelFilter below
/// The "warn" level.
///
/// Designates hazardous situations.
@@ -287,44 +287,44 @@ pub enum LogLevel {
Trace,
}
-impl Clone for LogLevel {
+impl Clone for Level {
#[inline]
- fn clone(&self) -> LogLevel {
+ fn clone(&self) -> Level {
*self
}
}
-impl PartialEq for LogLevel {
+impl PartialEq for Level {
#[inline]
- fn eq(&self, other: &LogLevel) -> bool {
+ fn eq(&self, other: &Level) -> bool {
*self as usize == *other as usize
}
}
-impl PartialEq<LogLevelFilter> for LogLevel {
+impl PartialEq<LevelFilter> for Level {
#[inline]
- fn eq(&self, other: &LogLevelFilter) -> bool {
+ fn eq(&self, other: &LevelFilter) -> bool {
*self as usize == *other as usize
}
}
-impl PartialOrd for LogLevel {
+impl PartialOrd for Level {
#[inline]
- fn partial_cmp(&self, other: &LogLevel) -> Option<cmp::Ordering> {
+ fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
-impl PartialOrd<LogLevelFilter> for LogLevel {
+impl PartialOrd<LevelFilter> for Level {
#[inline]
- fn partial_cmp(&self, other: &LogLevelFilter) -> Option<cmp::Ordering> {
+ fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> {
Some((*self as usize).cmp(&(*other as usize)))
}
}
-impl Ord for LogLevel {
+impl Ord for Level {
#[inline]
- fn cmp(&self, other: &LogLevel) -> cmp::Ordering {
+ fn cmp(&self, other: &Level) -> cmp::Ordering {
(*self as usize).cmp(&(*other as usize))
}
}
@@ -355,60 +355,60 @@ fn eq_ignore_ascii_case(a: &str, b: &str) -> bool {
}
}
-impl FromStr for LogLevel {
+impl FromStr for Level {
type Err = ();
- fn from_str(level: &str) -> Result<LogLevel, ()> {
+ fn from_str(level: &str) -> Result<Level, ()> {
ok_or(LOG_LEVEL_NAMES.iter()
.position(|&name| eq_ignore_ascii_case(name, level))
.into_iter()
.filter(|&idx| idx != 0)
- .map(|idx| LogLevel::from_usize(idx).unwrap())
+ .map(|idx| Level::from_usize(idx).unwrap())
.next(), ())
}
}
-impl fmt::Display for LogLevel {
+impl fmt::Display for Level {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad(LOG_LEVEL_NAMES[*self as usize])
}
}
-impl LogLevel {
- fn from_usize(u: usize) -> Option<LogLevel> {
+impl Level {
+ fn from_usize(u: usize) -> Option<Level> {
match u {
- 1 => Some(LogLevel::Error),
- 2 => Some(LogLevel::Warn),
- 3 => Some(LogLevel::Info),
- 4 => Some(LogLevel::Debug),
- 5 => Some(LogLevel::Trace),
+ 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() -> LogLevel {
- LogLevel::Trace
+ pub fn max() -> Level {
+ Level::Trace
}
- /// Converts the `LogLevel` to the equivalent `LogLevelFilter`.
+ /// Converts the `Level` to the equivalent `LevelFilter`.
#[inline]
- pub fn to_log_level_filter(&self) -> LogLevelFilter {
- LogLevelFilter::from_usize(*self as usize).unwrap()
+ pub fn to_level_filter(&self) -> LevelFilter {
+ LevelFilter::from_usize(*self as usize).unwrap()
}
}
/// An enum representing the available verbosity level filters of the logging
/// framework.
///
-/// A `LogLevelFilter` may be compared directly to a [`LogLevel`](enum.LogLevel.html).
-/// Use this type to [`get()`](struct.MaxLogLevelFilter.html#method.get) and
-/// [`set()`](struct.MaxLogLevelFilter.html#method.set) the
-/// [`MaxLogLevelFilter`](struct.MaxLogLevelFilter.html), or to match with the getter
-/// [`max_log_level()`](fn.max_log_level.html).
+/// A `LevelFilter` may be compared directly to a [`Level`](enum.Level.html).
+/// Use this type to [`get()`](struct.MaxLevelFilter.html#method.get) and
+/// [`set()`](struct.MaxLevelFilter.html#method.set) the
+/// [`MaxLevelFilter`](struct.MaxLevelFilter.html), or to match with the getter
+/// [`max_level()`](fn.max_level.html).
#[repr(usize)]
#[derive(Copy, Eq, Debug, Hash)]
-pub enum LogLevelFilter {
+pub enum LevelFilter {
/// A level lower than all log levels.
Off,
/// Corresponds to the `Error` log level.
@@ -425,87 +425,87 @@ pub enum LogLevelFilter {
// Deriving generates terrible impls of these traits
-impl Clone for LogLevelFilter {
+impl Clone for LevelFilter {
#[inline]
- fn clone(&self) -> LogLevelFilter {
+ fn clone(&self) -> LevelFilter {
*self
}
}
-impl PartialEq for LogLevelFilter {
+impl PartialEq for LevelFilter {
#[inline]
- fn eq(&self, other: &LogLevelFilter) -> bool {
+ fn eq(&self, other: &LevelFilter) -> bool {
*self as usize == *other as usize
}
}
-impl PartialEq<LogLevel> for LogLevelFilter {
+impl PartialEq<Level> for LevelFilter {
#[inline]
- fn eq(&self, other: &LogLevel) -> bool {
+ fn eq(&self, other: &Level) -> bool {
other.eq(self)
}
}
-impl PartialOrd for LogLevelFilter {
+impl PartialOrd for LevelFilter {
#[inline]
- fn partial_cmp(&self, other: &LogLevelFilter) -> Option<cmp::Ordering> {
+ fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
-impl PartialOrd<LogLevel> for LogLevelFilter {
+impl PartialOrd<Level> for LevelFilter {
#[inline]
- fn partial_cmp(&self, other: &LogLevel) -> Option<cmp::Ordering> {
+ fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
other.partial_cmp(self).map(|x| x.reverse())
}
}
-impl Ord for LogLevelFilter {
+impl Ord for LevelFilter {
#[inline]
- fn cmp(&self, other: &LogLevelFilter) -> cmp::Ordering {
+ fn cmp(&self, other: &LevelFilter) -> cmp::Ordering {
(*self as usize).cmp(&(*other as usize))
}
}
-impl FromStr for LogLevelFilter {
+impl FromStr for LevelFilter {
type Err = ();
- fn from_str(level: &str) -> Result<LogLevelFilter, ()> {
+ fn from_str(level: &str) -> Result<LevelFilter, ()> {
ok_or(LOG_LEVEL_NAMES.iter()
.position(|&name| eq_ignore_ascii_case(name, level))
- .map(|p| LogLevelFilter::from_usize(p).unwrap()), ())
+ .map(|p| LevelFilter::from_usize(p).unwrap()), ())
}
}
-impl fmt::Display for LogLevelFilter {
+impl fmt::Display for LevelFilter {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", LOG_LEVEL_NAMES[*self as usize])
}
}
-impl LogLevelFilter {
- fn from_usize(u: usize) -> Option<LogLevelFilter> {
+impl LevelFilter {
+ fn from_usize(u: usize) -> Option<LevelFilter> {
match u {
- 0 => Some(LogLevelFilter::Off),
- 1 => Some(LogLevelFilter::Error),
- 2 => Some(LogLevelFilter::Warn),
- 3 => Some(LogLevelFilter::Info),
- 4 => Some(LogLevelFilter::Debug),
- 5 => Some(LogLevelFilter::Trace),
+ 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() -> LogLevelFilter {
- LogLevelFilter::Trace
+ pub fn max() -> LevelFilter {
+ LevelFilter::Trace
}
- /// Converts `self` to the equivalent `LogLevel`.
+ /// Converts `self` to the equivalent `Level`.
///
- /// Returns `None` if `self` is `LogLevelFilter::Off`.
+ /// Returns `None` if `self` is `LevelFilter::Off`.
#[inline]
- pub fn to_log_level(&self) -> Option<LogLevel> {
- LogLevel::from_usize(*self as usize)
+ pub fn to_level(&self) -> Option<Level> {
+ Level::from_usize(*self as usize)
}
}
@@ -515,30 +515,30 @@ impl LogLevelFilter {
/// [`log`]: trait.Log.html#tymethod.log
/// [`Log`]: trait.Log.html
#[derive(Debug)]
-pub struct LogRecord<'a> {
- metadata: LogMetadata<'a>,
- location: &'a LogLocation,
+pub struct Record<'a> {
+ metadata: Metadata<'a>,
+ location: &'a Location,
args: fmt::Arguments<'a>,
}
-impl<'a> LogRecord<'a> {
+impl<'a> Record<'a> {
/// The message body.
pub fn args(&self) -> &fmt::Arguments<'a> {
&self.args
}
/// Metadata about the log directive.
- pub fn metadata(&self) -> &LogMetadata {
+ pub fn metadata(&self) -> &Metadata {
&self.metadata
}
/// The location of the log directive.
- pub fn location(&self) -> &LogLocation {
+ pub fn location(&self) -> &Location {
self.location
}
/// The verbosity level of the message.
- pub fn level(&self) -> LogLevel {
+ pub fn level(&self) -> Level {
self.metadata.level()
}
@@ -550,14 +550,14 @@ impl<'a> LogRecord<'a> {
/// Metadata about a log message.
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
-pub struct LogMetadata<'a> {
- level: LogLevel,
+pub struct Metadata<'a> {
+ level: Level,
target: &'a str,
}
-impl<'a> LogMetadata<'a> {
+impl<'a> Metadata<'a> {
/// The verbosity level of the message.
- pub fn level(&self) -> LogLevel {
+ pub fn level(&self) -> Level {
self.level
}
@@ -575,23 +575,23 @@ pub trait Log: Sync+Send {
/// 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: &LogMetadata) -> bool;
+ fn enabled(&self, metadata: &Metadata) -> bool;
- /// Logs the `LogRecord`.
+ /// 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: &LogRecord);
+ fn log(&self, record: &Record);
}
// Just used as a dummy initial value for LOGGER
struct NopLogger;
impl Log for NopLogger {
- fn enabled(&self, _: &LogMetadata) -> bool { false }
+ fn enabled(&self, _: &Metadata) -> bool { false }
- fn log(&self, _: &LogRecord) {}
+ fn log(&self, _: &Record) {}
}
/// The location of a log message.
@@ -602,7 +602,7 @@ impl Log for NopLogger {
/// `log!` macro. They are subject to change at any time and should never be
/// accessed directly.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
-pub struct LogLocation {
+pub struct Location {
#[doc(hidden)]
pub __module_path: &'static str,
#[doc(hidden)]
@@ -611,7 +611,7 @@ pub struct LogLocation {
pub __line: u32,
}
-impl LogLocation {
+impl Location {
/// The module path of the message.
pub fn module_path(&self) -> &str {
self.__module_path
@@ -637,22 +637,22 @@ impl LogLocation {
/// make sure to keep the maximum log level filter in sync with its current
/// configuration.
#[allow(missing_copy_implementations)]
-pub struct MaxLogLevelFilter(());
+pub struct MaxLevelFilter(());
-impl fmt::Debug for MaxLogLevelFilter {
+impl fmt::Debug for MaxLevelFilter {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- write!(fmt, "MaxLogLevelFilter")
+ write!(fmt, "MaxLevelFilter")
}
}
-impl MaxLogLevelFilter {
+impl MaxLevelFilter {
/// Gets the current maximum log level filter.
- pub fn get(&self) -> LogLevelFilter {
- max_log_level()
+ pub fn get(&self) -> LevelFilter {
+ max_level()
}
/// Sets the maximum log level.
- pub fn set(&self, level: LogLevelFilter) {
+ pub fn set(&self, level: LevelFilter) {
MAX_LOG_LEVEL_FILTER.store(level as usize, Ordering::SeqCst)
}
}
@@ -661,15 +661,15 @@ impl MaxLogLevelFilter {
///
/// 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 `MaxLogLevel` token passed to loggers.
+/// log level is set by the `MaxLevel` token passed to loggers.
#[inline(always)]
-pub fn max_log_level() -> LogLevelFilter {
+pub fn max_level() -> LevelFilter {
unsafe { mem::transmute(MAX_LOG_LEVEL_FILTER.load(Ordering::Relaxed)) }
}
/// Sets the global logger.
///
-/// The `make_logger` closure is passed a `MaxLogLevel` object, which the
+/// The `make_logger` closure is passed a `MaxLevel` object, which the
/// logger should use to keep the global maximum log level in sync with the
/// highest log level that the logger will not ignore.
///
@@ -684,7 +684,7 @@ pub fn max_log_level() -> LogLevelFilter {
/// Requires the `use_std` feature (enabled by default).
#[cfg(feature = "use_std")]
pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
- where M: FnOnce(MaxLogLevelFilter) -> Box<Log> {
+ where M: FnOnce(MaxLevelFilter) -> Box<Log> {
unsafe { set_logger_raw(|max_level| mem::transmute(make_logger(max_level))) }
}
@@ -693,7 +693,7 @@ pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
/// This function is similar to `set_logger` except that it is usable in
/// `no_std` code.
///
-/// The `make_logger` closure is passed a `MaxLogLevel` object, which the
+/// The `make_logger` closure is passed a `MaxLevel` object, which the
/// logger should use to keep the global maximum log level in sync with the
/// highest log level that the logger will not ignore.
///
@@ -711,13 +711,13 @@ pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
/// duration of the program or until `shutdown_logger_raw` is called. In
/// addition, `shutdown_logger` *must not* be called after this function.
pub unsafe fn set_logger_raw<M>(make_logger: M) -> Result<(), SetLoggerError>
- where M: FnOnce(MaxLogLevelFilter) -> *const Log {
+ where M: FnOnce(MaxLevelFilter) -> *const Log {
if STATE.compare_and_swap(UNINITIALIZED, INITIALIZING,
Ordering::SeqCst) != UNINITIALIZED {
return Err(SetLoggerError(()));
}
- LOGGER = make_logger(MaxLogLevelFilter(()));
+ LOGGER = make_logger(MaxLevelFilter(()));
STATE.store(INITIALIZED, Ordering::SeqCst);
Ok(())
}
@@ -877,9 +877,9 @@ fn logger() -> Option<LoggerGuard> {
// This is not considered part of the crate's public API. It is subject to
// change at any time.
#[doc(hidden)]
-pub fn __enabled(level: LogLevel, target: &str) -> bool {
+pub fn __enabled(level: Level, target: &str) -> bool {
if let Some(logger) = logger() {
- logger.enabled(&LogMetadata { level: level, target: target })
+ logger.enabled(&Metadata { level: level, target: target })
} else {
false
}
@@ -889,11 +889,11 @@ pub fn __enabled(level: LogLevel, target: &str) -> bool {
// This is not considered part of the crate's public API. It is subject to
// change at any time.
#[doc(hidden)]
-pub fn __log(level: LogLevel, target: &str, loc: &LogLocation,
+pub fn __log(level: Level, target: &str, loc: &Location,
args: fmt::Arguments) {
if let Some(logger) = logger() {
- let record = LogRecord {
- metadata: LogMetadata {
+ let record = Record {
+ metadata: Metadata {
level: level,
target: target,
},
@@ -909,35 +909,35 @@ pub fn __log(level: LogLevel, target: &str, loc: &LogLocation,
// change at any time.
#[inline(always)]
#[doc(hidden)]
-pub fn __static_max_level() -> LogLevelFilter {
+pub fn __static_max_level() -> LevelFilter {
if !cfg!(debug_assertions) {
// This is a release build. Check `release_max_level_*` first.
if cfg!(feature = "release_max_level_off") {
- return LogLevelFilter::Off
+ return LevelFilter::Off
} else if cfg!(feature = "release_max_level_error") {
- return LogLevelFilter::Error
+ return LevelFilter::Error
} else if cfg!(feature = "release_max_level_warn") {
- return LogLevelFilter::Warn
+ return LevelFilter::Warn
} else if cfg!(feature = "release_max_level_info") {
- return LogLevelFilter::Info
+ return LevelFilter::Info
} else if cfg!(feature = "release_max_level_debug") {
- return LogLevelFilter::Debug
+ return LevelFilter::Debug
} else if cfg!(feature = "release_max_level_trace") {
- return LogLevelFilter::Trace
+ return LevelFilter::Trace
}
}
if cfg!(feature = "max_level_off") {
- LogLevelFilter::Off
+ LevelFilter::Off
} else if cfg!(feature = "max_level_error") {
- LogLevelFilter::Error
+ LevelFilter::Error
} else if cfg!(feature = "max_level_warn") {
- LogLevelFilter::Warn
+ LevelFilter::Warn
} else if cfg!(feature = "max_level_info") {
- LogLevelFilter::Info
+ LevelFilter::Info
} else if cfg!(feature = "max_level_debug") {
- LogLevelFilter::Debug
+ LevelFilter::Debug
} else {
- LogLevelFilter::Trace
+ LevelFilter::Trace
}
}
@@ -945,23 +945,23 @@ pub fn __static_max_level() -> LogLevelFilter {
mod tests {
extern crate std;
use tests::std::string::ToString;
- use super::{LogLevel, LogLevelFilter};
+ use super::{Level, LevelFilter};
#[test]
- fn test_loglevelfilter_from_str() {
+ fn test_levelfilter_from_str() {
let tests = [
- ("off", Ok(LogLevelFilter::Off)),
- ("error", Ok(LogLevelFilter::Error)),
- ("warn", Ok(LogLevelFilter::Warn)),
- ("info", Ok(LogLevelFilter::Info)),
- ("debug", Ok(LogLevelFilter::Debug)),
- ("trace", Ok(LogLevelFilter::Trace)),
- ("OFF", Ok(LogLevelFilter::Off)),
- ("ERROR", Ok(LogLevelFilter::Error)),
- ("WARN", Ok(LogLevelFilter::Warn)),
- ("INFO", Ok(LogLevelFilter::Info)),
- ("DEBUG", Ok(LogLevelFilter::Debug)),
- ("TRACE", Ok(LogLevelFilter::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)),
+ ("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(())),
];
for &(s, ref expected) in &tests {
@@ -970,19 +970,19 @@ mod tests {
}
#[test]
- fn test_loglevel_from_str() {
+ fn test_level_from_str() {
let tests = [
("OFF", Err(())),
- ("error", Ok(LogLevel::Error)),
- ("warn", Ok(LogLevel::Warn)),
- ("info", Ok(LogLevel::Info)),
- ("debug", Ok(LogLevel::Debug)),
- ("trace", Ok(LogLevel::Trace)),
- ("ERROR", Ok(LogLevel::Error)),
- ("WARN", Ok(LogLevel::Warn)),
- ("INFO", Ok(LogLevel::Info)),
- ("DEBUG", Ok(LogLevel::Debug)),
- ("TRACE", Ok(LogLevel::Trace)),
+ ("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(())),
];
for &(s, ref expected) in &tests {
@@ -991,42 +991,42 @@ mod tests {
}
#[test]
- fn test_loglevel_show() {
- assert_eq!("INFO", LogLevel::Info.to_string());
- assert_eq!("ERROR", LogLevel::Error.to_string());
+ fn test_level_show() {
+ assert_eq!("INFO", Level::Info.to_string());
+ assert_eq!("ERROR", Level::Error.to_string());
}
#[test]
- fn test_loglevelfilter_show() {
- assert_eq!("OFF", LogLevelFilter::Off.to_string());
- assert_eq!("ERROR", LogLevelFilter::Error.to_string());
+ fn test_levelfilter_show() {
+ assert_eq!("OFF", LevelFilter::Off.to_string());
+ assert_eq!("ERROR", LevelFilter::Error.to_string());
}
#[test]
fn test_cross_cmp() {
- assert!(LogLevel::Debug > LogLevelFilter::Error);
- assert!(LogLevelFilter::Warn < LogLevel::Trace);
- assert!(LogLevelFilter::Off < LogLevel::Error);
+ assert!(Level::Debug > LevelFilter::Error);
+ assert!(LevelFilter::Warn < Level::Trace);
+ assert!(LevelFilter::Off < Level::Error);
}
#[test]
fn test_cross_eq() {
- assert!(LogLevel::Error == LogLevelFilter::Error);
- assert!(LogLevelFilter::Off != LogLevel::Error);
- assert!(LogLevel::Trace == LogLevelFilter::Trace);
+ assert!(Level::Error == LevelFilter::Error);
+ assert!(LevelFilter::Off != Level::Error);
+ assert!(Level::Trace == LevelFilter::Trace);
}
#[test]
- fn test_to_log_level() {
- assert_eq!(Some(LogLevel::Error), LogLevelFilter::Error.to_log_level());
- assert_eq!(None, LogLevelFilter::Off.to_log_level());
- assert_eq!(Some(LogLevel::Debug), LogLevelFilter::Debug.to_log_level());
+ 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_log_level_filter() {
- assert_eq!(LogLevelFilter::Error, LogLevel::Error.to_log_level_filter());
- assert_eq!(LogLevelFilter::Trace, LogLevel::Trace.to_log_level_filter());
+ fn test_to_level_filter() {
+ assert_eq!(LevelFilter::Error, Level::Error.to_level_filter());
+ assert_eq!(LevelFilter::Trace, Level::Trace.to_level_filter());
}
#[test]
diff --git a/src/macros.rs b/src/macros.rs
index f9a7788d2..1843e177f 100644
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -9,7 +9,7 @@
// except according to those terms.
/// The standard logging macro.
///
-/// This macro will generically log with the specified `LogLevel` and `format!`
+/// This macro will generically log with the specified `Level` and `format!`
/// based argument list.
///
/// The `max_level_*` features can be used to statically disable logging at
@@ -20,27 +20,27 @@
/// ```rust
/// # #[macro_use]
/// # extern crate log;
-/// use log::LogLevel;
+/// use log::Level;
///
/// # fn main() {
/// let data = (42, "Forty-two");
/// let private_data = "private";
///
-/// log!(LogLevel::Error, "Received errors: {}, {}", data.0, data.1);
-/// log!(target: "app_events", LogLevel::Warn, "App warning: {}, {}, {}",
+/// 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]
macro_rules! log {
(target: $target:expr, $lvl:expr, $($arg:tt)+) => ({
- static _LOC: $crate::LogLocation = $crate::LogLocation {
+ static _LOC: $crate::Location = $crate::Location {
__line: line!(),
__file: file!(),
__module_path: module_path!(),
};
let lvl = $lvl;
- if lvl <= $crate::__static_max_level() && lvl <= $crate::max_log_level() {
+ if lvl <= $crate::__static_max_level() && lvl <= $crate::max_level() {
$crate::__log(lvl, $target, &_LOC, format_args!($($arg)+))
}
});
@@ -66,10 +66,10 @@ macro_rules! log {
#[macro_export]
macro_rules! error {
(target: $target:expr, $($arg:tt)*) => (
- log!(target: $target, $crate::LogLevel::Error, $($arg)*);
+ log!(target: $target, $crate::Level::Error, $($arg)*);
);
($($arg:tt)*) => (
- log!($crate::LogLevel::Error, $($arg)*);
+ log!($crate::Level::Error, $($arg)*);
)
}
@@ -97,10 +97,10 @@ macro_rules! error {
#[macro_export]
macro_rules! warn {
(target: $target:expr, $($arg:tt)*) => (
- log!(target: $target, $crate::LogLevel::Warn, $($arg)*);
+ log!(target: $target, $crate::Level::Warn, $($arg)*);
);
($($arg:tt)*) => (
- log!($crate::LogLevel::Warn, $($arg)*);
+ log!($crate::Level::Warn, $($arg)*);
)
}
@@ -131,10 +131,10 @@ macro_rules! warn {
#[macro_export]
macro_rules! info {
(target: $target:expr, $($arg:tt)*) => (
- log!(target: $target, $crate::LogLevel::Info, $($arg)*);
+ log!(target: $target, $crate::Level::Info, $($arg)*);
);
($($arg:tt)*) => (
- log!($crate::LogLevel::Info, $($arg)*);
+ log!($crate::Level::Info, $($arg)*);
)
}
@@ -165,10 +165,10 @@ macro_rules! info {
#[macro_export]
macro_rules! debug {
(target: $target:expr, $($arg:tt)*) => (
- log!(target: $target, $crate::LogLevel::Debug, $($arg)*);
+ log!(target: $target, $crate::Level::Debug, $($arg)*);
);
($($arg:tt)*) => (
- log!($crate::LogLevel::Debug, $($arg)*);
+ log!($crate::Level::Debug, $($arg)*);
)
}
@@ -202,10 +202,10 @@ macro_rules! debug {
#[macro_export]
macro_rules! trace {
(target: $target:expr, $($arg:tt)*) => (
- log!(target: $target, $crate::LogLevel::Trace, $($arg)*);
+ log!(target: $target, $crate::Level::Trace, $($arg)*);
);
($($arg:tt)*) => (
- log!($crate::LogLevel::Trace, $($arg)*);
+ log!($crate::Level::Trace, $($arg)*);
)
}
@@ -220,7 +220,7 @@ macro_rules! trace {
/// ```rust
/// # #[macro_use]
/// # extern crate log;
-/// use log::LogLevel::Debug;
+/// use log::Level::Debug;
///
/// # fn foo() {
/// if log_enabled!(Debug) {
@@ -236,7 +236,7 @@ macro_rules! trace {
macro_rules! log_enabled {
(target: $target:expr, $lvl:expr) => ({
let lvl = $lvl;
- lvl <= $crate::__static_max_level() && lvl <= $crate::max_log_level() &&
+ lvl <= $crate::__static_max_level() && lvl <= $crate::max_level() &&
$crate::__enabled(lvl, $target)
});
($lvl:expr) => (log_enabled!(target: module_path!(), $lvl))
|
diff --git a/tests/filters.rs b/tests/filters.rs
index e08d46db1..0497c11c6 100644
--- a/tests/filters.rs
+++ b/tests/filters.rs
@@ -1,32 +1,32 @@
#[macro_use] extern crate log;
use std::sync::{Arc, Mutex};
-use log::{LogLevel, LogLevelFilter, Log, LogRecord, LogMetadata};
-use log::MaxLogLevelFilter;
+use log::{Level, LevelFilter, Log, Record, Metadata};
+use log::MaxLevelFilter;
#[cfg(feature = "use_std")]
use log::set_logger;
#[cfg(not(feature = "use_std"))]
fn set_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
- where M: FnOnce(MaxLogLevelFilter) -> Box<Log> {
+ where M: FnOnce(MaxLevelFilter) -> Box<Log> {
unsafe {
log::set_logger_raw(|x| std::mem::transmute(make_logger(x)))
}
}
struct State {
- last_log: Mutex<Option<LogLevel>>,
- filter: MaxLogLevelFilter,
+ last_log: Mutex<Option<Level>>,
+ filter: MaxLevelFilter,
}
struct Logger(Arc<State>);
impl Log for Logger {
- fn enabled(&self, _: &LogMetadata) -> bool {
+ fn enabled(&self, _: &Metadata) -> bool {
true
}
- fn log(&self, record: &LogRecord) {
+ fn log(&self, record: &Record) {
*self.0.last_log.lock().unwrap() = Some(record.level());
}
}
@@ -43,33 +43,33 @@ fn main() {
}).unwrap();
let a = a.unwrap();
- test(&a, LogLevelFilter::Off);
- test(&a, LogLevelFilter::Error);
- test(&a, LogLevelFilter::Warn);
- test(&a, LogLevelFilter::Info);
- test(&a, LogLevelFilter::Debug);
- test(&a, LogLevelFilter::Trace);
+ 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: LogLevelFilter) {
+fn test(a: &State, filter: LevelFilter) {
a.filter.set(filter);
error!("");
- last(&a, t(LogLevel::Error, filter));
+ last(&a, t(Level::Error, filter));
warn!("");
- last(&a, t(LogLevel::Warn, filter));
+ last(&a, t(Level::Warn, filter));
info!("");
- last(&a, t(LogLevel::Info, filter));
+ last(&a, t(Level::Info, filter));
debug!("");
- last(&a, t(LogLevel::Debug, filter));
+ last(&a, t(Level::Debug, filter));
trace!("");
- last(&a, t(LogLevel::Trace, filter));
+ last(&a, t(Level::Trace, filter));
- fn t(lvl: LogLevel, filter: LogLevelFilter) -> Option<LogLevel> {
+ fn t(lvl: Level, filter: LevelFilter) -> Option<Level> {
if lvl <= filter {Some(lvl)} else {None}
}
}
-fn last(state: &State, expected: Option<LogLevel>) {
+fn last(state: &State, expected: Option<Level>) {
let mut lvl = state.last_log.lock().unwrap();
assert_eq!(*lvl, expected);
*lvl = None;
diff --git a/tests/max_level_features/main.rs b/tests/max_level_features/main.rs
index 3d1f291d5..c2bbabf1f 100644
--- a/tests/max_level_features/main.rs
+++ b/tests/max_level_features/main.rs
@@ -1,32 +1,32 @@
#[macro_use] extern crate log;
use std::sync::{Arc, Mutex};
-use log::{LogLevel, LogLevelFilter, Log, LogRecord, LogMetadata};
-use log::MaxLogLevelFilter;
+use log::{Level, LevelFilter, Log, Record, Metadata};
+use log::MaxLevelFilter;
#[cfg(feature = "use_std")]
use log::set_logger;
#[cfg(not(feature = "use_std"))]
fn set_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
- where M: FnOnce(MaxLogLevelFilter) -> Box<Log> {
+ where M: FnOnce(MaxLevelFilter) -> Box<Log> {
unsafe {
log::set_logger_raw(|x| std::mem::transmute(make_logger(x)))
}
}
struct State {
- last_log: Mutex<Option<LogLevel>>,
- filter: MaxLogLevelFilter,
+ last_log: Mutex<Option<Level>>,
+ filter: MaxLevelFilter,
}
struct Logger(Arc<State>);
impl Log for Logger {
- fn enabled(&self, _: &LogMetadata) -> bool {
+ fn enabled(&self, _: &Metadata) -> bool {
true
}
- fn log(&self, record: &LogRecord) {
+ fn log(&self, record: &Record) {
*self.0.last_log.lock().unwrap() = Some(record.level());
}
}
@@ -43,26 +43,26 @@ fn main() {
}).unwrap();
let a = a.unwrap();
- test(&a, LogLevelFilter::Off);
- test(&a, LogLevelFilter::Error);
- test(&a, LogLevelFilter::Warn);
- test(&a, LogLevelFilter::Info);
- test(&a, LogLevelFilter::Debug);
- test(&a, LogLevelFilter::Trace);
+ 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: LogLevelFilter) {
+fn test(a: &State, filter: LevelFilter) {
a.filter.set(filter);
error!("");
- last(&a, t(LogLevel::Error, filter));
+ last(&a, t(Level::Error, filter));
warn!("");
- last(&a, t(LogLevel::Warn, filter));
+ last(&a, t(Level::Warn, filter));
info!("");
- last(&a, t(LogLevel::Info, filter));
+ last(&a, t(Level::Info, filter));
debug!("");
if cfg!(debug_assertions) {
- last(&a, t(LogLevel::Debug, filter));
+ last(&a, t(Level::Debug, filter));
} else {
last(&a, None);
}
@@ -70,12 +70,12 @@ fn test(a: &State, filter: LogLevelFilter) {
trace!("");
last(&a, None);
- fn t(lvl: LogLevel, filter: LogLevelFilter) -> Option<LogLevel> {
+ fn t(lvl: Level, filter: LevelFilter) -> Option<Level> {
if lvl <= filter {Some(lvl)} else {None}
}
}
-fn last(state: &State, expected: Option<LogLevel>) {
+fn last(state: &State, expected: Option<Level>) {
let mut lvl = state.last_log.lock().unwrap();
assert_eq!(*lvl, expected);
*lvl = None;
|
Reduce "stuttering" in types
Rename types like `log::LogRecord` to `log::Record`
|
I'd like to try working on this.
To confirm:
`LogLevel` -> `Level`
`LogLevelFilter` -> `LevelFilter`
`LogRecord` -> `Record`
`LogMetadata` -> `Metadata`, etc.?
Just types? What about functions like `log::LogLevel::to_log_level_filter()`? Should it become `log::Level::to_level_filter`?
Should `MaxLogLevelFilter` become `MaxLevelFilter`?
That all sounds great to me @omh1280! @sfackler does anything else come to mind for you?
|
2017-05-22T00:58:25Z
|
0.3
|
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
|
rust-lang/log
| 70
|
rust-lang__log-70
|
[
"13"
] |
7067c9b8c1f1a46ab66fd23b7df0e7aa00fe3a87
|
diff --git a/.travis.yml b/.travis.yml
index 15b6a4778..5dfb476ed 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -7,8 +7,10 @@ rust:
- nightly
script:
- cargo build --verbose
+ - ([ $TRAVIS_RUST_VERSION != nightly ] || cargo build --verbose --no-default-features)
- ([ $TRAVIS_RUST_VERSION != nightly ] || cargo build --verbose --features nightly)
- - cargo test --verbose
+ - ([ $TRAVIS_RUST_VERSION == 1.0.0 ] || cargo test --verbose)
+ - ([ $TRAVIS_RUST_VERSION != nightly ] || cargo test --verbose --no-default-features)
- cargo test --verbose --manifest-path env/Cargo.toml
- cargo run --verbose --manifest-path tests/max_level_features/Cargo.toml
- cargo run --verbose --manifest-path tests/max_level_features/Cargo.toml --release
diff --git a/Cargo.toml b/Cargo.toml
index 9b6bf7485..7b9675b14 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,7 +17,7 @@ name = "filters"
harness = false
[dependencies]
-libc = "0.2"
+libc = {version = "0.2", optional = true}
[features]
max_level_off = []
@@ -35,3 +35,5 @@ release_max_level_debug = []
release_max_level_trace = []
nightly = []
+use_std = ["libc"]
+default = ["use_std"]
diff --git a/src/lib.rs b/src/lib.rs
index 4e4a5a3d9..a6cf8eccd 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -136,6 +136,7 @@
//! # fn log(&self, _: &log::LogRecord) {}
//! # }
//! # fn main() {}
+//! # #[cfg(feature = "use_std")]
//! pub fn init() -> Result<(), SetLoggerError> {
//! log::set_logger(|max_log_level| {
//! max_log_level.set(LogLevelFilter::Info);
@@ -143,6 +144,45 @@
//! })
//! }
//! ```
+//!
+//! # Use with `no_std`
+//!
+//! To use the `log` crate without depending on `libstd`, you need to specify
+//! `default-features = false` when specifying the dependency in `Cargo.toml`.
+//! This makes no difference to libraries using `log` since the logging API
+//! remains the same. However executables will need to use the `set_logger_raw`
+//! function to initialize a logger and the `shutdown_logger_raw` function to
+//! shut down the global logger before exiting:
+//!
+//! ```rust
+//! # extern crate log;
+//! # use log::{LogLevel, LogLevelFilter, SetLoggerError, ShutdownLoggerError,
+//! # LogMetadata};
+//! # struct SimpleLogger;
+//! # impl log::Log for SimpleLogger {
+//! # fn enabled(&self, _: &LogMetadata) -> bool { false }
+//! # fn log(&self, _: &log::LogRecord) {}
+//! # }
+//! # impl SimpleLogger {
+//! # fn flush(&self) {}
+//! # }
+//! # fn main() {}
+//! pub fn init() -> Result<(), SetLoggerError> {
+//! unsafe {
+//! log::set_logger_raw(|max_log_level| {
+//! static LOGGER: SimpleLogger = SimpleLogger;
+//! max_log_level.set(LogLevelFilter::Info);
+//! &SimpleLogger
+//! })
+//! }
+//! }
+//! pub fn shutdown() -> Result<(), ShutdownLoggerError> {
+//! log::shutdown_logger_raw().map(|logger| {
+//! let logger = unsafe { &*(logger as *const SimpleLogger) };
+//! logger.flush();
+//! })
+//! }
+//! ```
#![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",
@@ -150,10 +190,16 @@
#![warn(missing_docs)]
#![cfg_attr(feature = "nightly", feature(panic_handler))]
+#![cfg_attr(not(feature = "use_std"), no_std)]
+
+#[cfg(not(feature = "use_std"))]
+extern crate core as std;
+
+#[cfg(feature = "use_std")]
extern crate libc;
-use std::ascii::AsciiExt;
use std::cmp;
+#[cfg(feature = "use_std")]
use std::error;
use std::fmt;
use std::mem;
@@ -163,32 +209,32 @@ use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
#[macro_use]
mod macros;
-// The setup here is a bit weird to make at_exit work.
+// The setup here is a bit weird to make shutdown_logger_raw work.
//
// There are four 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), the logger's active, or the logger's
-// shutting down inside of at_exit.
+// LOGGER hasn't actually been set yet), the logger's active, or the logger is
+// shut down after calling shutdown_logger_raw.
//
-// The LOGGER static is normally a Box<Box<Log>> with some special possible
-// values as well. The uninitialized and initializing states are represented by
-// the values 0 and 1 respectively. The shutting down state is also represented
-// by 1. Any other value is a valid pointer to the logger.
+// 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.
//
-// The at_exit routine needs to make sure that no threads are actively logging
-// when it deallocates the logger. The number of actively logging threads is
-// tracked in the REFCOUNT static. The routine first sets LOGGER back to 1.
-// All logging calls past that point will immediately return without accessing
-// the logger. At that point, the at_exit routine just waits for the refcount
-// to reach 0 before deallocating the logger. Note that the refcount does not
-// necessarily monotonically decrease at this point, as new log calls still
-// increment and decrement it, but the interval in between is small enough that
-// the wait is really just for the active log calls to finish.
-static LOGGER: AtomicUsize = ATOMIC_USIZE_INIT;
+// The shutdown_logger_raw routine needs to make sure that no threads are
+// actively logging before it returns. The number of actively logging threads is
+// tracked in the REFCOUNT static. The routine first sets STATE back to
+// INITIALIZING. All logging calls past that point will immediately return
+// without accessing the logger. At that point, the at_exit routine just waits
+// for the refcount to reach 0 before deallocating the logger. Note that the
+// refcount does not necessarily monotonically decrease at this point, as new
+// log calls still increment and decrement it, but the interval in between is
+// small enough that the wait is really just for the active log calls to finish.
+static mut LOGGER: Option<*const Log> = None;
+static STATE: AtomicUsize = ATOMIC_USIZE_INIT;
static REFCOUNT: AtomicUsize = ATOMIC_USIZE_INIT;
const UNINITIALIZED: usize = 0;
const INITIALIZING: usize = 1;
+const INITIALIZED: usize = 2;
static MAX_LOG_LEVEL_FILTER: AtomicUsize = ATOMIC_USIZE_INIT;
@@ -272,11 +318,30 @@ fn ok_or<T, E>(t: Option<T>, e: E) -> Result<T, 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 LogLevel {
type Err = ();
fn from_str(level: &str) -> Result<LogLevel, ()> {
ok_or(LOG_LEVEL_NAMES.iter()
- .position(|&name| name.eq_ignore_ascii_case(level))
+ .position(|&name| eq_ignore_ascii_case(name, level))
.into_iter()
.filter(|&idx| idx != 0)
.map(|idx| LogLevel::from_usize(idx).unwrap())
@@ -384,7 +449,7 @@ impl FromStr for LogLevelFilter {
type Err = ();
fn from_str(level: &str) -> Result<LogLevelFilter, ()> {
ok_or(LOG_LEVEL_NAMES.iter()
- .position(|&name| name.eq_ignore_ascii_case(level))
+ .position(|&name| eq_ignore_ascii_case(name, level))
.map(|p| LogLevelFilter::from_usize(p).unwrap()), ())
}
}
@@ -578,32 +643,93 @@ pub fn max_log_level() -> LogLevelFilter {
/// This function does not typically need to be called manually. Logger
/// implementations should provide an initialization method that calls
/// `set_logger` internally.
+#[cfg(feature = "use_std")]
pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
where M: FnOnce(MaxLogLevelFilter) -> Box<Log> {
- if LOGGER.compare_and_swap(UNINITIALIZED, INITIALIZING,
- Ordering::SeqCst) != UNINITIALIZED {
- return Err(SetLoggerError(()));
- }
+ let result = unsafe {
+ set_logger_raw(|max_level| mem::transmute(make_logger(max_level)))
+ };
+
+ return match result {
+ Ok(()) => {
+ assert_eq!(unsafe { libc::atexit(shutdown) }, 0);
+ Ok(())
+ }
+ Err(_) => Err(SetLoggerError(())),
+ };
- let logger = Box::new(make_logger(MaxLogLevelFilter(())));
- let logger = unsafe { mem::transmute::<Box<Box<Log>>, usize>(logger) };
- LOGGER.store(logger, Ordering::SeqCst);
+ extern fn shutdown() {
+ shutdown_logger_raw().map(|logger| unsafe {
+ mem::transmute::<_, Box<Log>>(logger);
+ }).ok();
+ }
+}
- unsafe {
- assert_eq!(libc::atexit(shutdown), 0);
+/// Sets the global logger from a raw pointer.
+///
+/// This function is similar to `set_logger` except that it is usable in
+/// `no_std` code. Another difference is that the logger is not automatically
+/// shut down on program exit, and `shutdown_logger_raw` must be called to
+/// manually shut it down.
+///
+/// The `make_logger` closure is passed a `MaxLogLevel` object, which the
+/// logger should use to keep the global maximum log level in sync with the
+/// highest log level that the logger will not ignore.
+///
+/// This function may only be called once in the lifetime of a program. Any log
+/// events that occur before the call to `set_logger_raw` completes will be
+/// ignored.
+///
+/// This function does not typically need to be called manually. Logger
+/// implementations should provide an initialization method that calls
+/// `set_logger_raw` internally.
+///
+/// # Safety
+///
+/// The pointer returned by `make_logger` must remain valid for the entire
+/// duration of the program or until `shutdown_logger_raw` is called.
+pub unsafe fn set_logger_raw<M>(make_logger: M) -> Result<(), SetLoggerError>
+ where M: FnOnce(MaxLogLevelFilter) -> *const Log {
+ if STATE.compare_and_swap(UNINITIALIZED, INITIALIZING,
+ Ordering::SeqCst) != UNINITIALIZED {
+ return Err(SetLoggerError(()));
}
- return Ok(());
- extern fn shutdown() {
- // Set to INITIALIZING to prevent re-initialization after
- let logger = LOGGER.swap(INITIALIZING, Ordering::SeqCst);
+ LOGGER = Some(make_logger(MaxLogLevelFilter(())));
+ STATE.store(INITIALIZED, Ordering::SeqCst);
+ Ok(())
+}
- while REFCOUNT.load(Ordering::SeqCst) != 0 {
- // FIXME add a sleep here when it doesn't involve timers
- }
+/// Shuts down the global logger.
+///
+/// This function may only be called once in the lifetime of a program, and may
+/// not be called before `set_logger_raw`. Once the global logger has been shut
+/// down, it can no longer be re-initialized by `set_logger_raw`. Any log
+/// events that occur after the call to `shutdown_logger_raw` completes will be
+/// ignored.
+///
+/// The pointer that was originally passed to `set_logger_raw` is returned on
+/// success. At that point it is guaranteed that no other threads are
+/// concurrently accessing the logger object.
+///
+/// This function should not be called when the global logger was registered
+/// using `set_logger`, since in that case the logger will automatically be shut
+/// down when the program exits
+pub fn shutdown_logger_raw() -> Result<*const Log, ShutdownLoggerError> {
+ // Set the global log level to stop other thread from logging
+ MAX_LOG_LEVEL_FILTER.store(0, Ordering::SeqCst);
- unsafe { mem::transmute::<usize, Box<Box<Log>>>(logger); }
+ // Set to INITIALIZING to prevent re-initialization after
+ if STATE.compare_and_swap(INITIALIZED, INITIALIZING,
+ Ordering::SeqCst) != INITIALIZED {
+ return Err(ShutdownLoggerError(()));
}
+
+ while REFCOUNT.load(Ordering::SeqCst) != 0 {
+ // FIXME add a sleep here when it doesn't involve timers
+ }
+
+ Ok(unsafe { LOGGER.unwrap() })
}
/// The type returned by `set_logger` if `set_logger` has already been called.
@@ -618,23 +744,43 @@ impl fmt::Display for SetLoggerError {
}
}
+// The Error trait is not available in libcore
+#[cfg(feature = "use_std")]
impl error::Error for SetLoggerError {
fn description(&self) -> &str { "set_logger() called multiple times" }
}
+/// The type returned by `shutdown_logger_raw` if `shutdown_logger_raw` has
+/// already been called or if `set_logger_raw` has not been called yet.
+#[allow(missing_copy_implementations)]
+#[derive(Debug)]
+pub struct ShutdownLoggerError(());
+
+impl fmt::Display for ShutdownLoggerError {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ write!(fmt, "attempted to shut down a logger without an active logger")
+ }
+}
+
+// The Error trait is not available in libcore
+#[cfg(feature = "use_std")]
+impl error::Error for ShutdownLoggerError {
+ fn description(&self) -> &str { "shutdown_logger_raw() called without an active logger" }
+}
+
/// Registers a panic handler which logs at the error level.
///
/// The format is the same as the default panic handler. The reporting module is
/// `log::panic`.
///
/// Requires the `nightly` feature.
-#[cfg(feature = "nightly")]
+#[cfg(all(feature = "nightly", feature = "use_std"))]
pub fn log_panics() {
std::panic::set_handler(panic::log);
}
// inner module so that the reporting module is log::panic instead of log
-#[cfg(feature = "nightly")]
+#[cfg(all(feature = "nightly", feature = "use_std"))]
mod panic {
use std::panic::PanicInfo;
use std::thread;
@@ -664,8 +810,7 @@ mod panic {
}
}
-
-struct LoggerGuard(usize);
+struct LoggerGuard(&'static Log);
impl Drop for LoggerGuard {
fn drop(&mut self) {
@@ -674,21 +819,20 @@ impl Drop for LoggerGuard {
}
impl Deref for LoggerGuard {
- type Target = Box<Log>;
+ type Target = Log;
- fn deref(&self) -> &Box<Log+'static> {
- unsafe { mem::transmute(self.0) }
+ fn deref(&self) -> &(Log + 'static) {
+ self.0
}
}
fn logger() -> Option<LoggerGuard> {
REFCOUNT.fetch_add(1, Ordering::SeqCst);
- let logger = LOGGER.load(Ordering::SeqCst);
- if logger == UNINITIALIZED || logger == INITIALIZING {
+ if STATE.load(Ordering::SeqCst) != INITIALIZED {
REFCOUNT.fetch_sub(1, Ordering::SeqCst);
None
} else {
- Some(LoggerGuard(logger))
+ Some(LoggerGuard(unsafe { &*LOGGER.unwrap() }))
}
}
@@ -762,8 +906,9 @@ pub fn __static_max_level() -> LogLevelFilter {
#[cfg(test)]
mod tests {
- use std::error::Error;
- use super::{LogLevel, LogLevelFilter, SetLoggerError};
+ extern crate std;
+ use tests::std::string::ToString;
+ use super::{LogLevel, LogLevelFilter};
#[test]
fn test_loglevelfilter_from_str() {
@@ -848,7 +993,10 @@ mod tests {
}
#[test]
+ #[cfg(feature = "use_std")]
fn test_error_trait() {
+ use std::error::Error;
+ use super::SetLoggerError;
let e = SetLoggerError(());
assert_eq!(e.description(), "set_logger() called multiple times");
}
|
diff --git a/tests/filters.rs b/tests/filters.rs
index 6f352eca9..e08d46db1 100644
--- a/tests/filters.rs
+++ b/tests/filters.rs
@@ -1,9 +1,19 @@
#[macro_use] extern crate log;
use std::sync::{Arc, Mutex};
-use log::{LogLevel, set_logger, LogLevelFilter, Log, LogRecord, LogMetadata};
+use log::{LogLevel, LogLevelFilter, Log, LogRecord, LogMetadata};
use log::MaxLogLevelFilter;
+#[cfg(feature = "use_std")]
+use log::set_logger;
+#[cfg(not(feature = "use_std"))]
+fn set_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
+ where M: FnOnce(MaxLogLevelFilter) -> Box<Log> {
+ unsafe {
+ log::set_logger_raw(|x| std::mem::transmute(make_logger(x)))
+ }
+}
+
struct State {
last_log: Mutex<Option<LogLevel>>,
filter: MaxLogLevelFilter,
diff --git a/tests/max_level_features/main.rs b/tests/max_level_features/main.rs
index 707bff6ae..3d1f291d5 100644
--- a/tests/max_level_features/main.rs
+++ b/tests/max_level_features/main.rs
@@ -1,9 +1,19 @@
#[macro_use] extern crate log;
use std::sync::{Arc, Mutex};
-use log::{LogLevel, set_logger, LogLevelFilter, Log, LogRecord, LogMetadata};
+use log::{LogLevel, LogLevelFilter, Log, LogRecord, LogMetadata};
use log::MaxLogLevelFilter;
+#[cfg(feature = "use_std")]
+use log::set_logger;
+#[cfg(not(feature = "use_std"))]
+fn set_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
+ where M: FnOnce(MaxLogLevelFilter) -> Box<Log> {
+ unsafe {
+ log::set_logger_raw(|x| std::mem::transmute(make_logger(x)))
+ }
+}
+
struct State {
last_log: Mutex<Option<LogLevel>>,
filter: MaxLogLevelFilter,
|
Use core not std
I believe everything in the logging interface just requires core, not std. (The `Box<Log>` could become a `Unique<Log>` as it is never deallocated.) This is important for allowing the interface to reach its full potential, e.g. serial port debugging before allocation is set up. https://github.com/rust-lang/bitflags was similarly changed to use core for the same reason.
If this sounds good, I would be happy to do the implementation work.
|
Ah, missed the `rt::at_exit` call. Perhaps the use of `std`, `rt`, and `Box` could be controlled by a cargo feature?
Edit: there is also `eq_ignore_ascii_case` but that doesn't need allocation or anything, so it could be moved defined elsewhere than std?
I submitted a PR for this: #68
|
2016-01-12T19:36:57Z
|
0.3
|
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.