From 9c92958b5caf3f72b898ef8a9281e6d4d78c66a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 1 Jan 2017 14:49:00 -0800 Subject: [PATCH 01/61] Fork as `slog-scope-stdlog` --- Cargo.toml | 6 +- lib.rs | 208 +++++++++-------------------------------------------- 2 files changed, 35 insertions(+), 179 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5ce124d..106dcaa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] -name = "slog-stdlog" -version = "1.1.0" +name = "slog-scope-stdlog" +version = "0.2.0" authors = ["Dawid Ciężarkiewicz "] description = "Standard Rust log crate adapter to slog-rs" keywords = ["slog", "logging", "json", "log"] @@ -15,7 +15,7 @@ path = "lib.rs" [dependencies] slog = "1.1" +slog-scope = "0.2.2" slog-term = "1.3" log = "0.3.6" -lazy_static = "0.2.1" crossbeam = "0.2.9" diff --git a/lib.rs b/lib.rs index 7cff4c3..f78d356 100644 --- a/lib.rs +++ b/lib.rs @@ -1,70 +1,45 @@ -//! Standard Rust log crate adapter to slog-rs +//! Standard Rust log crate adapter to slog-rs based on slog-scope. //! -//! This crate allows using `slog` features with code -//! using legacy `log` statements. +//! Note: this is a fork of a `slog-stdlog` that unlike original does +//! share logging scopes with `slog-scope` crate. It is currently advised +//! to prefer `slog-scope-stdlog`. //! -//! `log` crate expects a global logger to be registered -//! (popular one is `env_logger`) as a handler for all -//! `info!(...)` and similar. +//! This crate provides two way compatibility with legacy `log` crate logging. //! -//! `slog-stdlog` will register itself as `log` global handler and forward all -//! legacy logging statements to `slog`'s `Logger`. That means existing logging -//! `debug!` (even in dependencies crates) work and utilize `slog` composable -//! drains. +//! ### `log` -> `slog` //! -//! See `init()` documentation for minimal working example. +//! After calling `init` legacy `log` crate logging statements (eg. `debug!(...)`) will +//! be redirected just like they originated from the logger returned by `slog_scope::logger()`. +//! See documentation of `slog-scope` for examples of logging scope usage. //! -//! Note: While `slog-scope` provides a similiar functionality, the `slog-scope` and `slog-stdlog` -//! keep track of distinct logging scopes. +//! ### `slog` -> `log` //! -//! ## Compile-time log level filtering +//! `StdLog` is a `slog::Drain` implementation that will log logging `Record`s just like +//! they were created using legacy `log` statements. //! -//! For filtering `debug!` and other `log` statements at compile-time, configure the features on -//! the `log` crate in your `Cargo.toml`: +//! ### Warning +//! +//! Be careful when using both methods at the same time, as a loop can be easily created: +//! `log` -> `slog` -> `log` -> ... //! -//! ```norust -//! log = { version = "*", features = ["max_level_trace", "release_max_level_warn"] } -//! ``` #![warn(missing_docs)] #[macro_use] extern crate slog; extern crate slog_term; +extern crate slog_scope; extern crate log; -#[macro_use] -extern crate lazy_static; -extern crate crossbeam; -use slog::{DrainExt, ser}; +use slog::ser; use log::LogMetadata; -use std::sync::Arc; -use std::cell::RefCell; use std::{io, fmt}; use std::io::Write; use slog::Level; -use crossbeam::sync::ArcCell; - -thread_local! { - static TL_SCOPES: RefCell> = RefCell::new(Vec::with_capacity(8)) -} - -lazy_static! { - static ref GLOBAL_LOGGER : ArcCell = ArcCell::new( - Arc::new( - slog::Logger::root(slog::Discard, o!()) - ) - ); -} - -fn set_global_logger(l: slog::Logger) { - let _ = GLOBAL_LOGGER.set(Arc::new(l)); -} struct Logger; - fn log_to_slog_level(level: log::LogLevel) -> Level { match level { log::LogLevel::Trace => Level::Trace, @@ -88,62 +63,18 @@ impl log::Log for Logger { let module = r.location().__module_path; let file = r.location().__file; let line = r.location().line(); - with_current_logger(|l| { - let s = slog::RecordStatic { - level: level, - file: file, - line: line, - column: 0, - function: "", - module: module, - target: target, - }; - l.log(&slog::Record::new(&s, *args, &[])) - }) - } -} - -/// Set a `slog::Logger` as a global `log` create handler -/// -/// This will forward all `log` records to `slog` logger. -/// -/// ``` -/// // only use `o` macro from `slog` crate -/// #[macro_use(o)] -/// extern crate slog; -/// #[macro_use] -/// extern crate log; -/// extern crate slog_stdlog; -/// -/// fn main() { -/// let root = slog::Logger::root( -/// slog::Discard, -/// o!("build-id" => "8dfljdf"), -/// ); -/// slog_stdlog::set_logger(root).unwrap(); -/// // Note: this `info!(...)` macro comes from `log` crate -/// info!("standard logging redirected to slog"); -/// } -/// ``` -pub fn set_logger(logger: slog::Logger) -> Result<(), log::SetLoggerError> { - log::set_logger(|max_log_level| { - max_log_level.set(log::LogLevelFilter::max()); - set_global_logger(logger); - Box::new(Logger) - }) -} -/// Set a `slog::Logger` as a global `log` create handler -/// -/// This will forward `log` records that satisfy `log_level_filter` to `slog` logger. -pub fn set_logger_level(logger: slog::Logger, - log_level_filter: log::LogLevelFilter) - -> Result<(), log::SetLoggerError> { - log::set_logger(|max_log_level| { - max_log_level.set(log_level_filter); - set_global_logger(logger); - Box::new(Logger) - }) + let s = slog::RecordStatic { + level: level, + file: file, + line: line, + column: 0, + function: "", + module: module, + target: target, + }; + slog_scope::logger().log(&slog::Record::new(&s, *args, &[])) + } } /// Minimal initialization with default drain @@ -164,87 +95,12 @@ pub fn set_logger_level(logger: slog::Logger, /// } /// ``` pub fn init() -> Result<(), log::SetLoggerError> { - let drain = slog::level_filter(Level::Info, slog_term::streamer().compact().build()); - set_logger(slog::Logger::root(drain.fuse(), o!())) -} - -struct ScopeGuard; - - -impl ScopeGuard { - fn new(logger: slog::Logger) -> Self { - TL_SCOPES.with(|s| { - s.borrow_mut().push(logger); - }); - - ScopeGuard - } -} - -impl Drop for ScopeGuard { - fn drop(&mut self) { - TL_SCOPES.with(|s| { - s.borrow_mut().pop().expect("TL_SCOPES should contain a logger"); - }) - } -} - - -/// Access the currently active logger -/// -/// The reference logger will be either: -/// * global logger, or -/// * currently active scope logger -/// -/// **Warning**: Calling `scope` inside `f` -/// will result in a panic. -pub fn with_current_logger(f: F) -> R - where F: FnOnce(&slog::Logger) -> R -{ - TL_SCOPES.with(|s| { - let s = s.borrow(); - if s.is_empty() { - f(&GLOBAL_LOGGER.get()) - } else { - f(&s[s.len() - 1]) - } - }) -} - -/// Access the `Logger` for the current logging scope -pub fn logger() -> slog::Logger { - TL_SCOPES.with(|s| { - let s = s.borrow(); - if s.is_empty() { - (*GLOBAL_LOGGER.get()).clone() - } else { - s[s.len() - 1].clone() - } + log::set_logger(|max_log_level| { + max_log_level.set(log::LogLevelFilter::max()); + Box::new(Logger) }) } -/// Execute code in a logging scope -/// -/// Logging scopes allow using different logger for legacy logging -/// statements in part of the code. -/// -/// Logging scopes can be nested and are panic safe. -/// -/// `logger` is the `Logger` to use during the duration of `f`. -/// `with_current_logger` can be used to build it as a child of currently active -/// logger. -/// -/// `f` is a code to be executed in the logging scope. -/// -/// Note: Thread scopes are thread-local. Each newly spawned thread starts -/// with a global logger, as a current logger. -pub fn scope(logger: slog::Logger, f: SF) -> R - where SF: FnOnce() -> R -{ - let _guard = ScopeGuard::new(logger); - f() -} - /// Drain logging `Record`s into `log` crate /// /// Using `StdLog` is effectively the same as using `log::info!(...)` and From e372c45258dc9df5f7ace729c3a773e29600e90e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 1 Jan 2017 14:50:41 -0800 Subject: [PATCH 02/61] Fix `clippy` warnings --- lib.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib.rs b/lib.rs index f78d356..cf3ad4a 100644 --- a/lib.rs +++ b/lib.rs @@ -139,12 +139,12 @@ impl<'a> fmt::Display for LazyLogString<'a> { let res = { || -> io::Result<()> { - for (ref k, ref v) in self.logger_values.iter() { + for (k, v) in self.logger_values.iter() { try!(ser.io().write_all(", ".as_bytes())); try!(v.serialize(self.info, k, &mut ser)); } - for &(ref k, ref v) in self.info.values().iter() { + for &(k, v) in self.info.values().iter() { try!(ser.io().write_all(", ".as_bytes())); try!(v.serialize(self.info, k, &mut ser)); } @@ -167,8 +167,7 @@ impl slog::Drain for StdLog { fn log(&self, info: &slog::Record, logger_values : &slog::OwnedKeyValueList) -> io::Result<()> { let level = match info.level() { - slog::Level::Critical => log::LogLevel::Error, - slog::Level::Error => log::LogLevel::Error, + slog::Level::Critical | slog::Level::Error => log::LogLevel::Error, slog::Level::Warning => log::LogLevel::Warn, slog::Level::Info => log::LogLevel::Info, slog::Level::Debug => log::LogLevel::Debug, From ae016930c6d24c9cb63aae1804823816ba98ba46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 1 Jan 2017 14:51:05 -0800 Subject: [PATCH 03/61] `cargo fmt` --- lib.rs | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/lib.rs b/lib.rs index cf3ad4a..74b4d25 100644 --- a/lib.rs +++ b/lib.rs @@ -114,12 +114,11 @@ pub struct StdLog; struct LazyLogString<'a> { info: &'a slog::Record<'a>, - logger_values : &'a slog::OwnedKeyValueList + logger_values: &'a slog::OwnedKeyValueList, } impl<'a> LazyLogString<'a> { - - fn new(info : &'a slog::Record, logger_values : &'a slog::OwnedKeyValueList) -> Self { + fn new(info: &'a slog::Record, logger_values: &'a slog::OwnedKeyValueList) -> Self { LazyLogString { info: info, @@ -137,20 +136,21 @@ impl<'a> fmt::Display for LazyLogString<'a> { let mut ser = KSV::new(io, ": ".into()); let res = { - || -> io::Result<()> { - - for (k, v) in self.logger_values.iter() { - try!(ser.io().write_all(", ".as_bytes())); - try!(v.serialize(self.info, k, &mut ser)); - } - - for &(k, v) in self.info.values().iter() { - try!(ser.io().write_all(", ".as_bytes())); - try!(v.serialize(self.info, k, &mut ser)); - } - Ok(()) - } - }().map_err(|_| fmt::Error); + || -> io::Result<()> { + + for (k, v) in self.logger_values.iter() { + try!(ser.io().write_all(", ".as_bytes())); + try!(v.serialize(self.info, k, &mut ser)); + } + + for &(k, v) in self.info.values().iter() { + try!(ser.io().write_all(", ".as_bytes())); + try!(v.serialize(self.info, k, &mut ser)); + } + Ok(()) + } + }() + .map_err(|_| fmt::Error); try!(res); @@ -164,7 +164,7 @@ impl<'a> fmt::Display for LazyLogString<'a> { impl slog::Drain for StdLog { type Error = io::Error; - fn log(&self, info: &slog::Record, logger_values : &slog::OwnedKeyValueList) -> io::Result<()> { + fn log(&self, info: &slog::Record, logger_values: &slog::OwnedKeyValueList) -> io::Result<()> { let level = match info.level() { slog::Level::Critical | slog::Level::Error => log::LogLevel::Error, From f2462e91da4a9aae37a4ea0fda09015fb72fbd43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 1 Jan 2017 15:04:03 -0800 Subject: [PATCH 04/61] Fix README and CHANGELOG --- CHANGELOG.md | 15 ++------------- README.md | 17 ++++++++++++----- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a5f89eb..78cf680 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,18 +4,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## 1.1.0 +## 0.2.0 - 2017-01-01 ### Changed -* BREAKING: Rewrite handling of owned values. - -## 1.0.1 - 2016-10-02 -### Changed - -* Fixed `StdLog` not serializing the key-value pairs. -* `StdLog` message to `log` crate is lazily-evaluated. - - -## 1.0.0 - 2016-09-21 - -First stable release. +* Release as a fork of `slog-stdlog` diff --git a/README.md b/README.md index c411e63..994deb1 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ -## slog-stdlog - Standard Rust log crate adapter for [slog-rs] +## slog-scope-stdlog - Standard Rust log crate adapter for [slog-rs] - integrated with [`slog-scope`][slog-scope]

- - Travis CI Build Status + + Travis CI Build Status - - slog-stdlog on crates.io + + slog-scope-stdlog on crates.io @@ -14,4 +14,11 @@

+This is a preferred (over original `slog-stdlog`) method of backward +compatibility with legacy `log` crate. + +The difference is: this library does not define own logging scopes +functionality, and instead relies on `slog_scope::scope`. + [slog-rs]: //github.com/slog-rs/slog +[slog-scope]: //github.com/slog-rs/scope From 7b509504f67b70dc4fe30636d2fbf1b5a0c1cc52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 1 Jan 2017 15:08:25 -0800 Subject: [PATCH 05/61] Fix documentation examples --- lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib.rs b/lib.rs index 74b4d25..36bc158 100644 --- a/lib.rs +++ b/lib.rs @@ -86,10 +86,10 @@ impl log::Log for Logger { /// ``` /// #[macro_use] /// extern crate log; -/// extern crate slog_stdlog; +/// extern crate slog_scope_stdlog; /// /// fn main() { -/// slog_stdlog::init().unwrap(); +/// slog_scope_stdlog::init().unwrap(); /// // Note: this `info!(...)` macro comes from `log` crate /// info!("standard logging redirected to slog"); /// } From 18bfca63c19f15f2cac9594bffe19f0ae3914f29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 1 Jan 2017 15:13:01 -0800 Subject: [PATCH 06/61] Add `.gitignore` --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1e7caa9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +Cargo.lock +target/ From a2d8f5e8c10351ebe7ea10ce57fc6093962394fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 1 Jan 2017 15:13:41 -0800 Subject: [PATCH 07/61] Clean up `.travis.yml` --- .travis.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index bd66197..9be8a47 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,10 +3,6 @@ rust: - stable - beta - nightly - -before_install: - - sudo apt-get update -qq - - sudo apt-get install -qq graphviz script: - make all From e58c6b8418073788df79a1272d3890cbb0482666 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Mon, 2 Jan 2017 21:27:09 -0800 Subject: [PATCH 08/61] Cargo.toml: Fix links --- Cargo.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 106dcaa..5b0d487 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,9 +5,9 @@ authors = ["Dawid Ciężarkiewicz "] description = "Standard Rust log crate adapter to slog-rs" keywords = ["slog", "logging", "json", "log"] license = "MPL-2.0" -documentation = "https://dpc.github.io/slog-rs/" -homepage = "https://github.com/dpc/slog-rs" -repository = "https://github.com/dpc/slog-rs" +documentation = "https://docs.rs/slog-scope-stdlog" +homepage = "https://github.com/slog-rs/scope-stdlog" +repository = "https://github.com/slog-rs/scope-stdlog" readme = "README.md" [lib] From 480f1ffd2a979df7a98195864a261bbde6972c2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 5 Mar 2017 16:31:52 -0800 Subject: [PATCH 09/61] Port to slog v2 --- .gitignore | 7 ++- CHANGELOG.md | 21 ++++++- Cargo.toml | 8 +-- README.md | 9 +-- lib.rs | 157 ++++++++++++--------------------------------------- 5 files changed, 66 insertions(+), 136 deletions(-) diff --git a/.gitignore b/.gitignore index 1e7caa9..6e8e3dc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ -Cargo.lock -target/ +/target +/Cargo.lock +/tags +/.cargo +/rusty-tags.vi diff --git a/CHANGELOG.md b/CHANGELOG.md index 78cf680..d43085f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,24 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## 0.2.0 - 2017-01-01 +## 2.0.0-0.1 ### Changed -* Release as a fork of `slog-stdlog` +* Port to slog v2 +* Base on `slog-scope` + +## 1.1.0 +### Changed + +* BREAKING: Rewrite handling of owned values. + +## 1.0.1 - 2016-10-02 +### Changed + +* Fixed `StdLog` not serializing the key-value pairs. +* `StdLog` message to `log` crate is lazily-evaluated. + + +## 1.0.0 - 2016-09-21 + +First stable release. diff --git a/Cargo.toml b/Cargo.toml index 5b0d487..5b1b5a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] -name = "slog-scope-stdlog" -version = "0.2.0" +name = "slog-stdlog" +version = "2.0.0-0.1" authors = ["Dawid Ciężarkiewicz "] description = "Standard Rust log crate adapter to slog-rs" keywords = ["slog", "logging", "json", "log"] @@ -14,8 +14,8 @@ readme = "README.md" path = "lib.rs" [dependencies] -slog = "1.1" -slog-scope = "0.2.2" +slog = ">= 2.0.0-1.0, < 2.0.0-2" +slog-scope = "0.3.0" slog-term = "1.3" log = "0.3.6" crossbeam = "0.2.9" diff --git a/README.md b/README.md index 994deb1..b16917d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## slog-scope-stdlog - Standard Rust log crate adapter for [slog-rs] - integrated with [`slog-scope`][slog-scope] +## slog-stdlog - Standard Rust log crate adapter for [slog-rs]

@@ -14,11 +14,6 @@

-This is a preferred (over original `slog-stdlog`) method of backward -compatibility with legacy `log` crate. - -The difference is: this library does not define own logging scopes -functionality, and instead relies on `slog_scope::scope`. +In slog v2 the `slog-stdlog` scopes are based on `slog-scope`. [slog-rs]: //github.com/slog-rs/slog -[slog-scope]: //github.com/slog-rs/scope diff --git a/lib.rs b/lib.rs index 36bc158..5327dc3 100644 --- a/lib.rs +++ b/lib.rs @@ -1,26 +1,26 @@ -//! Standard Rust log crate adapter to slog-rs based on slog-scope. +//! Standard Rust log crate adapter to slog-rs //! -//! Note: this is a fork of a `slog-stdlog` that unlike original does -//! share logging scopes with `slog-scope` crate. It is currently advised -//! to prefer `slog-scope-stdlog`. +//! Note: `slog-stdlog` for slog v2, unlike previous releases uses logging +//! scopes provided by `slog-scope` crate instead of providing it's own ones. //! //! This crate provides two way compatibility with legacy `log` crate logging. //! //! ### `log` -> `slog` //! -//! After calling `init` legacy `log` crate logging statements (eg. `debug!(...)`) will -//! be redirected just like they originated from the logger returned by `slog_scope::logger()`. -//! See documentation of `slog-scope` for examples of logging scope usage. +//! After calling `init` legacy `log` crate logging statements (eg. +//! `debug!(...)`) will be redirected just like they originated from the logger +//! returned by `slog_scope::logger()`. See documentation of `slog-scope` for +//! examples of logging scope usage. //! //! ### `slog` -> `log` //! -//! `StdLog` is a `slog::Drain` implementation that will log logging `Record`s just like -//! they were created using legacy `log` statements. +//! `StdLog` is a `slog::Drain` implementation that will log logging `Record`s +//! just like they were created using legacy `log` statements. //! //! ### Warning //! -//! Be careful when using both methods at the same time, as a loop can be easily created: -//! `log` -> `slog` -> `log` -> ... +//! Be careful when using both methods at the same time, as a loop can be easily +//! created: `log` -> `slog` -> `log` -> ... //! #![warn(missing_docs)] @@ -30,13 +30,11 @@ extern crate slog_term; extern crate slog_scope; extern crate log; -use slog::ser; - use log::LogMetadata; use std::{io, fmt}; -use std::io::Write; use slog::Level; +use slog::KV; struct Logger; @@ -65,15 +63,17 @@ impl log::Log for Logger { let line = r.location().line(); let s = slog::RecordStatic { + location: &slog::RecordLocation { + file: file, + line: line, + column: 0, + function: "", + module: module, + }, level: level, - file: file, - line: line, - column: 0, - function: "", - module: module, - target: target, + tag: target, }; - slog_scope::logger().log(&slog::Record::new(&s, *args, &[])) + slog_scope::logger().log(&slog::Record::new(&s, args, b!())) } } @@ -86,10 +86,10 @@ impl log::Log for Logger { /// ``` /// #[macro_use] /// extern crate log; -/// extern crate slog_scope_stdlog; +/// extern crate slog_stdlog; /// /// fn main() { -/// slog_scope_stdlog::init().unwrap(); +/// slog_stdlog::init().unwrap(); /// // Note: this `info!(...)` macro comes from `log` crate /// info!("standard logging redirected to slog"); /// } @@ -114,11 +114,11 @@ pub struct StdLog; struct LazyLogString<'a> { info: &'a slog::Record<'a>, - logger_values: &'a slog::OwnedKeyValueList, + logger_values: &'a slog::OwnedKVList, } impl<'a> LazyLogString<'a> { - fn new(info: &'a slog::Record, logger_values: &'a slog::OwnedKeyValueList) -> Self { + fn new(info: &'a slog::Record, logger_values: &'a slog::OwnedKVList) -> Self { LazyLogString { info: info, @@ -133,20 +133,12 @@ impl<'a> fmt::Display for LazyLogString<'a> { try!(write!(f, "{}", self.info.msg())); let io = io::Cursor::new(Vec::new()); - let mut ser = KSV::new(io, ": ".into()); + let mut ser = KSV::new(io); let res = { || -> io::Result<()> { - - for (k, v) in self.logger_values.iter() { - try!(ser.io().write_all(", ".as_bytes())); - try!(v.serialize(self.info, k, &mut ser)); - } - - for &(k, v) in self.info.values().iter() { - try!(ser.io().write_all(", ".as_bytes())); - try!(v.serialize(self.info, k, &mut ser)); - } + try!(self.logger_values.serialize(self.info, &mut ser)); + try!(self.info.kv().serialize(self.info, &mut ser)); Ok(()) } }() @@ -163,8 +155,9 @@ impl<'a> fmt::Display for LazyLogString<'a> { } impl slog::Drain for StdLog { - type Error = io::Error; - fn log(&self, info: &slog::Record, logger_values: &slog::OwnedKeyValueList) -> io::Result<()> { + type Err = io::Error; + type Ok = (); + fn log(&self, info: &slog::Record, logger_values: &slog::OwnedKVList) -> io::Result<()> { let level = match info.level() { slog::Level::Critical | slog::Level::Error => log::LogLevel::Error, @@ -174,7 +167,7 @@ impl slog::Drain for StdLog { slog::Level::Trace => log::LogLevel::Trace, }; - let target = info.target(); + let target = info.tag(); let location = log::LogLocation { __module_path: info.module(), @@ -193,102 +186,24 @@ impl slog::Drain for StdLog { /// Key-Separator-Value serializer struct KSV { - separator: String, io: W, } impl KSV { - fn new(io: W, separator: String) -> Self { + fn new(io: W) -> Self { KSV { io: io, - separator: separator, } } - fn io(&mut self) -> &mut W { - &mut self.io - } - fn into_inner(self) -> W { self.io } } -impl ser::Serializer for KSV { - fn emit_none(&mut self, key: &str) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, "None")); - Ok(()) - } - fn emit_unit(&mut self, key: &str) -> ser::Result { - try!(write!(self.io, "{}", key)); - Ok(()) - } - - fn emit_bool(&mut self, key: &str, val: bool) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - - fn emit_char(&mut self, key: &str, val: char) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - - fn emit_usize(&mut self, key: &str, val: usize) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_isize(&mut self, key: &str, val: isize) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - - fn emit_u8(&mut self, key: &str, val: u8) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_i8(&mut self, key: &str, val: i8) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_u16(&mut self, key: &str, val: u16) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_i16(&mut self, key: &str, val: i16) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_u32(&mut self, key: &str, val: u32) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_i32(&mut self, key: &str, val: i32) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_f32(&mut self, key: &str, val: f32) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_u64(&mut self, key: &str, val: u64) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_i64(&mut self, key: &str, val: i64) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_f64(&mut self, key: &str, val: f64) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_str(&mut self, key: &str, val: &str) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); - Ok(()) - } - fn emit_arguments(&mut self, key: &str, val: &fmt::Arguments) -> ser::Result { - try!(write!(self.io, "{}{}{}", key, self.separator, val)); +impl slog::Serializer for KSV { + fn emit_arguments(&mut self, key: &str, val: &fmt::Arguments) -> slog::Result { + try!(write!(self.io, ", {}: {}", key, val)); Ok(()) } } From 6cec1ace1f36b1b9382ef680e5c025ec13062a15 Mon Sep 17 00:00:00 2001 From: Robin Stocker Date: Mon, 6 Feb 2017 16:58:32 +1100 Subject: [PATCH 10/61] Document how to do compile-time log level filtering It wasn't obvious to me how to do it, having this in the docs would have helped me figure it out quicker. --- lib.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib.rs b/lib.rs index 5327dc3..71b992a 100644 --- a/lib.rs +++ b/lib.rs @@ -22,6 +22,14 @@ //! Be careful when using both methods at the same time, as a loop can be easily //! created: `log` -> `slog` -> `log` -> ... //! +//! ## Compile-time log level filtering +//! +//! For filtering `debug!` and other `log` statements at compile-time, configure the features on +//! the `log` crate in your `Cargo.toml`: +//! +//! ```norust +//! log = { version = "*", features = ["max_level_trace", "release_max_level_warn"] } +//! ``` #![warn(missing_docs)] #[macro_use] From a3416a8f86c40104763fe66742f731755a236fd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 5 Mar 2017 16:35:51 -0800 Subject: [PATCH 11/61] Update documentation --- README.md | 8 ++++---- lib.rs | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b16917d..06e7bd4 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ ## slog-stdlog - Standard Rust log crate adapter for [slog-rs]

- - Travis CI Build Status + + Travis CI Build Status - - slog-scope-stdlog on crates.io + + slog-stdlog on crates.io diff --git a/lib.rs b/lib.rs index 71b992a..dbad9e7 100644 --- a/lib.rs +++ b/lib.rs @@ -24,8 +24,8 @@ //! //! ## Compile-time log level filtering //! -//! For filtering `debug!` and other `log` statements at compile-time, configure the features on -//! the `log` crate in your `Cargo.toml`: +//! For filtering `debug!` and other `log` statements at compile-time, configure +//! the features on the `log` crate in your `Cargo.toml`: //! //! ```norust //! log = { version = "*", features = ["max_level_trace", "release_max_level_warn"] } From c1aefbd6ce407645c3c0a8b4618c67ac7a53830c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 5 Mar 2017 17:53:45 -0800 Subject: [PATCH 12/61] Update dependencies --- CHANGELOG.md | 5 +++++ Cargo.toml | 6 +++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d43085f..77a9c7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 2.0.0-0.2 +### Fixed + +* Dependencies + ## 2.0.0-0.1 ### Changed diff --git a/Cargo.toml b/Cargo.toml index 5b1b5a0..8b58796 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "2.0.0-0.1" +version = "2.0.0-0.2" authors = ["Dawid Ciężarkiewicz "] description = "Standard Rust log crate adapter to slog-rs" keywords = ["slog", "logging", "json", "log"] @@ -15,7 +15,7 @@ path = "lib.rs" [dependencies] slog = ">= 2.0.0-1.0, < 2.0.0-2" -slog-scope = "0.3.0" -slog-term = "1.3" +slog-scope = ">= 2.0.0-1.0, < 2.0.0-2" +slog-term = ">= 2.0.0-1.0, < 2.0.0-2" log = "0.3.6" crossbeam = "0.2.9" From 8c75dc3e561a143c971655f7071ad5585042269b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 5 Mar 2017 17:57:08 -0800 Subject: [PATCH 13/61] Cargo.toml: Fix links --- CHANGELOG.md | 4 ++++ Cargo.toml | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77a9c7e..c8e6c24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +### Unreleased + +* Fixed links in `Cargo.toml` + ## 2.0.0-0.2 ### Fixed diff --git a/Cargo.toml b/Cargo.toml index 8b58796..c98c5b6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,9 +5,9 @@ authors = ["Dawid Ciężarkiewicz "] description = "Standard Rust log crate adapter to slog-rs" keywords = ["slog", "logging", "json", "log"] license = "MPL-2.0" -documentation = "https://docs.rs/slog-scope-stdlog" -homepage = "https://github.com/slog-rs/scope-stdlog" -repository = "https://github.com/slog-rs/scope-stdlog" +documentation = "https://docs.rs/slog-stdlog" +homepage = "https://github.com/slog-rs/stdlog" +repository = "https://github.com/slog-rs/stdlog" readme = "README.md" [lib] From dbefb1a6f71c2a5eeee6c80401d2f66a743017e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Mon, 20 Mar 2017 23:34:19 -0700 Subject: [PATCH 14/61] Bump version --- CHANGELOG.md | 4 +++- Cargo.toml | 8 ++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8e6c24..bf9132c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -### Unreleased +## 2.0.0-1.0 - 2017-03-20 +### Changed * Fixed links in `Cargo.toml` +* Updated slog dependency ## 2.0.0-0.2 ### Fixed diff --git a/Cargo.toml b/Cargo.toml index c98c5b6..1bdf161 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "2.0.0-0.2" +version = "2.0.0-1.0" authors = ["Dawid Ciężarkiewicz "] description = "Standard Rust log crate adapter to slog-rs" keywords = ["slog", "logging", "json", "log"] @@ -14,8 +14,8 @@ readme = "README.md" path = "lib.rs" [dependencies] -slog = ">= 2.0.0-1.0, < 2.0.0-2" -slog-scope = ">= 2.0.0-1.0, < 2.0.0-2" -slog-term = ">= 2.0.0-1.0, < 2.0.0-2" +slog = "~2.0.0-2" +slog-scope = "~2.0.0-2" +slog-term = "~2.0.0-2" log = "0.3.6" crossbeam = "0.2.9" From a4f5fef02e17e7bad005035074ec98c0bb7d71cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 2 Apr 2017 22:45:19 -0700 Subject: [PATCH 15/61] Bump version --- CHANGELOG.md | 3 +-- Cargo.toml | 8 ++++---- README.md | 6 +++--- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf9132c..6fd7ed7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,9 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## 2.0.0-1.0 - 2017-03-20 +## 2.0.0-3.0 - 2017-04-02 ### Changed -* Fixed links in `Cargo.toml` * Updated slog dependency ## 2.0.0-0.2 diff --git a/Cargo.toml b/Cargo.toml index 1bdf161..ad00fd9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "2.0.0-1.0" +version = "2.0.0-3.0" authors = ["Dawid Ciężarkiewicz "] description = "Standard Rust log crate adapter to slog-rs" keywords = ["slog", "logging", "json", "log"] @@ -14,8 +14,8 @@ readme = "README.md" path = "lib.rs" [dependencies] -slog = "~2.0.0-2" -slog-scope = "~2.0.0-2" -slog-term = "~2.0.0-2" +slog = "~2.0.0-3" +slog-scope = "~2.0.0-3" +slog-term = "~2.0.0-3" log = "0.3.6" crossbeam = "0.2.9" diff --git a/README.md b/README.md index 06e7bd4..898bc12 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,3 @@ -## slog-stdlog - Standard Rust log crate adapter for [slog-rs] -

Travis CI Build Status @@ -14,6 +12,8 @@

-In slog v2 the `slog-stdlog` scopes are based on `slog-scope`. +## slog-stdlog - Standard Rust log crate adapter for [slog-rs] + +For more information, help, to report issues etc. see [slog-rs][slog-rs]. [slog-rs]: //github.com/slog-rs/slog From 7a69121f258dc3850e6ed40294d7fe0dd986aea3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sat, 29 Apr 2017 18:27:14 -0700 Subject: [PATCH 16/61] Bump version --- CHANGELOG.md | 6 ++++++ Cargo.toml | 8 ++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fd7ed7..ca09b0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 2.0.0-4.0 - 2017-04-29 + +### Changed + +* Updated slog dependency + ## 2.0.0-3.0 - 2017-04-02 ### Changed diff --git a/Cargo.toml b/Cargo.toml index ad00fd9..1010db4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "2.0.0-3.0" +version = "2.0.0-4.0" authors = ["Dawid Ciężarkiewicz "] description = "Standard Rust log crate adapter to slog-rs" keywords = ["slog", "logging", "json", "log"] @@ -14,8 +14,8 @@ readme = "README.md" path = "lib.rs" [dependencies] -slog = "~2.0.0-3" -slog-scope = "~2.0.0-3" -slog-term = "~2.0.0-3" +slog = "2" +slog-scope = "2" +slog-term = "~2.0.0-4" log = "0.3.6" crossbeam = "0.2.9" From 444f93e8015ccadc95001b71c2b89d16744e691b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sat, 29 Apr 2017 20:12:35 -0700 Subject: [PATCH 17/61] Prepare major release --- Cargo.toml | 7 +++-- README.md | 4 ++- lib.rs | 76 ++++++++++++++++++++++++++++-------------------------- 3 files changed, 45 insertions(+), 42 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1010db4..ba5b58a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "slog-stdlog" -version = "2.0.0-4.0" +version = "2.0.0" authors = ["Dawid Ciężarkiewicz "] -description = "Standard Rust log crate adapter to slog-rs" +description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] license = "MPL-2.0" documentation = "https://docs.rs/slog-stdlog" @@ -15,7 +15,6 @@ path = "lib.rs" [dependencies] slog = "2" -slog-scope = "2" -slog-term = "~2.0.0-4" +slog-scope = "3" log = "0.3.6" crossbeam = "0.2.9" diff --git a/README.md b/README.md index 898bc12..44d7043 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,9 @@

-## slog-stdlog - Standard Rust log crate adapter for [slog-rs] +## slog-stdlog - `log` crate adapter for [slog-rs] + +See [slog-stdlog documentaiton](https://docs.rs/slog-stdlog) for details. For more information, help, to report issues etc. see [slog-rs][slog-rs]. diff --git a/lib.rs b/lib.rs index dbad9e7..f07f7a6 100644 --- a/lib.rs +++ b/lib.rs @@ -1,21 +1,24 @@ -//! Standard Rust log crate adapter to slog-rs +//! `log` crate adapter for slog-rs //! -//! Note: `slog-stdlog` for slog v2, unlike previous releases uses logging -//! scopes provided by `slog-scope` crate instead of providing it's own ones. +//! This crate provides two way compatibility with legacy (ha! or shall we +//! say... standard) `log` crate logging. //! -//! This crate provides two way compatibility with legacy `log` crate logging. +//! Note: `slog-stdlog` v2, unlike previous releases, uses logging scopes +//! provided by `slog-scope` crate instead of it's own. //! //! ### `log` -> `slog` //! -//! After calling `init` legacy `log` crate logging statements (eg. -//! `debug!(...)`) will be redirected just like they originated from the logger -//! returned by `slog_scope::logger()`. See documentation of `slog-scope` for -//! examples of logging scope usage. +//! After calling `init()` `slog-stdlog` will take a role of `log` crate +//! backend, forwarding all the `log` logging to `slog_scope::logger()`. +//! In other words, any `log` crate logging statement will behave like it was `slog` +//! logging statement executed with logger returned by `slog_scope::logger()`. +//! See documentation of `slog-scope` for more information about logging scopes. //! //! ### `slog` -> `log` //! -//! `StdLog` is a `slog::Drain` implementation that will log logging `Record`s -//! just like they were created using legacy `log` statements. +//! `StdLog` is `slog::Drain` that will pass all `Record`s passing through it to +//! `log` crate just like they were crated with `log` crate logging macros in +//! the first place. //! //! ### Warning //! @@ -34,7 +37,6 @@ #[macro_use] extern crate slog; -extern crate slog_term; extern crate slog_scope; extern crate log; @@ -72,24 +74,24 @@ impl log::Log for Logger { let s = slog::RecordStatic { location: &slog::RecordLocation { - file: file, - line: line, - column: 0, - function: "", - module: module, - }, + file: file, + line: line, + column: 0, + function: "", + module: module, + }, level: level, tag: target, }; - slog_scope::logger().log(&slog::Record::new(&s, args, b!())) + slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!()))) + } } -/// Minimal initialization with default drain +/// Register `slog-stdlog` as `log` backend. /// -/// The exact default drain is unspecified and will -/// change in future versions! Use `set_logger` instead -/// to build customized drain. +/// This will pass all logging statements crated with `log` +/// crate to current `slog-scope::logger()`. /// /// ``` /// #[macro_use] @@ -104,15 +106,17 @@ impl log::Log for Logger { /// ``` pub fn init() -> Result<(), log::SetLoggerError> { log::set_logger(|max_log_level| { - max_log_level.set(log::LogLevelFilter::max()); - Box::new(Logger) - }) + max_log_level.set(log::LogLevelFilter::max()); + Box::new(Logger) + }) } /// Drain logging `Record`s into `log` crate /// -/// Using `StdLog` is effectively the same as using `log::info!(...)` and -/// other standard logging statements. +/// Any `Record` passing through this `Drain` will be forwarded +/// to `log` crate, just like it was created with `log` crate macros +/// in the first place. The message and key-value pairs will be formated +/// to be one string. /// /// Caution needs to be taken to prevent circular loop where `Logger` /// installed via `slog-stdlog::set_logger` would log things to a `StdLog` @@ -144,13 +148,13 @@ impl<'a> fmt::Display for LazyLogString<'a> { let mut ser = KSV::new(io); let res = { - || -> io::Result<()> { - try!(self.logger_values.serialize(self.info, &mut ser)); - try!(self.info.kv().serialize(self.info, &mut ser)); - Ok(()) - } - }() - .map_err(|_| fmt::Error); + || -> io::Result<()> { + try!(self.logger_values.serialize(self.info, &mut ser)); + try!(self.info.kv().serialize(self.info, &mut ser)); + Ok(()) + } + }() + .map_err(|_| fmt::Error); try!(res); @@ -199,9 +203,7 @@ struct KSV { impl KSV { fn new(io: W) -> Self { - KSV { - io: io, - } + KSV { io: io } } fn into_inner(self) -> W { From a285b9ae3495e1300d813848db761768b497f296 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Sun, 28 May 2017 22:33:47 -0700 Subject: [PATCH 18/61] Bump `slog-scope` dependency and update docs --- CHANGELOG.md | 7 +++++++ Cargo.toml | 6 +++--- lib.rs | 22 ++++++++++++++++------ 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca09b0f..b133467 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 3.0.0 - 2017-05-28 +### Changed + +* Update to slog-scope v4 wh default to panicking instead of discarding + messages. Be warned! +* Relicensed under MPL-2.0/MIT/Apache-2.0 + ## 2.0.0-4.0 - 2017-04-29 ### Changed diff --git a/Cargo.toml b/Cargo.toml index ba5b58a..e821ac3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,10 +1,10 @@ [package] name = "slog-stdlog" -version = "2.0.0" +version = "3.0.0" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] -license = "MPL-2.0" +license = "MPL-2.0/MIT/Apache-2.0" documentation = "https://docs.rs/slog-stdlog" homepage = "https://github.com/slog-rs/stdlog" repository = "https://github.com/slog-rs/stdlog" @@ -15,6 +15,6 @@ path = "lib.rs" [dependencies] slog = "2" -slog-scope = "3" +slog-scope = "4" log = "0.3.6" crossbeam = "0.2.9" diff --git a/lib.rs b/lib.rs index f07f7a6..612172c 100644 --- a/lib.rs +++ b/lib.rs @@ -1,15 +1,11 @@ //! `log` crate adapter for slog-rs //! -//! This crate provides two way compatibility with legacy (ha! or shall we -//! say... standard) `log` crate logging. -//! -//! Note: `slog-stdlog` v2, unlike previous releases, uses logging scopes -//! provided by `slog-scope` crate instead of it's own. +//! This crate provides two way compatibility with Rust standard `log` crate. //! //! ### `log` -> `slog` //! //! After calling `init()` `slog-stdlog` will take a role of `log` crate -//! backend, forwarding all the `log` logging to `slog_scope::logger()`. +//! back-end, forwarding all the `log` logging to `slog_scope::logger()`. //! In other words, any `log` crate logging statement will behave like it was `slog` //! logging statement executed with logger returned by `slog_scope::logger()`. //! See documentation of `slog-scope` for more information about logging scopes. @@ -20,6 +16,20 @@ //! `log` crate just like they were crated with `log` crate logging macros in //! the first place. //! +//! ## `slog-scope` +//! +//! Since `log` does not have any form of context, and does not support `Logger` +//! `slog-stdlog` relies on "logging scopes" to establish it. +//! +//! You must set up logging context for `log` -> `slog` via `slog_scope::scope` +//! or `slog_scope::set_global_logger`. Setting a global logger upfront via +//! `slog_scope::set_global_logger` is highly recommended. +//! +//! Note: Since `slog-stdlog` v2, unlike previous releases, `slog-stdlog` uses +//! logging scopes provided by `slog-scope` crate instead of it's own. +//! +//! Refer to `slog-scope` crate documentation for more information. +//! //! ### Warning //! //! Be careful when using both methods at the same time, as a loop can be easily From 53950a9b4b76285031035e26b2c0fd4e3f7a8c60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Mon, 29 May 2017 18:14:28 -0700 Subject: [PATCH 19/61] Fix example for `init` --- lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib.rs b/lib.rs index 612172c..0bd433f 100644 --- a/lib.rs +++ b/lib.rs @@ -109,7 +109,7 @@ impl log::Log for Logger { /// extern crate slog_stdlog; /// /// fn main() { -/// slog_stdlog::init().unwrap(); +/// let _guard = slog_stdlog::init().unwrap(); /// // Note: this `info!(...)` macro comes from `log` crate /// info!("standard logging redirected to slog"); /// } From 027387da712be615c61c1b08c3535b2893271478 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Mon, 29 May 2017 18:15:21 -0700 Subject: [PATCH 20/61] Fix documentation --- CHANGELOG.md | 5 +++++ Cargo.toml | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b133467..561c78d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 3.0.1 - 2017-05-29 +### Fixed + +* Documentation example for `init` + ## 3.0.0 - 2017-05-28 ### Changed diff --git a/Cargo.toml b/Cargo.toml index e821ac3..529dc7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "3.0.0" +version = "3.0.1" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] From cb372483f01a74648802f4e4588b3030f78ac738 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Mon, 29 May 2017 19:10:11 -0700 Subject: [PATCH 21/61] Improve documentation --- Cargo.toml | 3 +++ lib.rs | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 529dc7c..67cc2df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,3 +18,6 @@ slog = "2" slog-scope = "4" log = "0.3.6" crossbeam = "0.2.9" + +[dev-dependencies] +slog-term = "2" diff --git a/lib.rs b/lib.rs index 0bd433f..5285b2a 100644 --- a/lib.rs +++ b/lib.rs @@ -8,8 +8,11 @@ //! back-end, forwarding all the `log` logging to `slog_scope::logger()`. //! In other words, any `log` crate logging statement will behave like it was `slog` //! logging statement executed with logger returned by `slog_scope::logger()`. +//! //! See documentation of `slog-scope` for more information about logging scopes. //! +//! See [`init` documentation](fn.init.html) for an example. +//! //! ### `slog` -> `log` //! //! `StdLog` is `slog::Drain` that will pass all `Record`s passing through it to @@ -107,8 +110,15 @@ impl log::Log for Logger { /// #[macro_use] /// extern crate log; /// extern crate slog_stdlog; +/// extern crate slog_scope; +/// extern crate slog_term; /// /// fn main() { +/// let decorator = slog_term::TermDecorator::new(); +/// let drain = slog_term::FullFormat::new(decorator).build().fuse(); +/// let logger = slog::Logger::root(drain, o!("version" => env!("CARGO_PKG_VERSION"))); +/// +/// let _guard = slog_scope::set_global_logger(logger).unwrap(); /// let _guard = slog_stdlog::init().unwrap(); /// // Note: this `info!(...)` macro comes from `log` crate /// info!("standard logging redirected to slog"); From f11ef725fa5b64f73f68d8f8de5656f3ff136dfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Mon, 29 May 2017 19:39:20 -0700 Subject: [PATCH 22/61] Fix documentation --- Cargo.toml | 1 + lib.rs | 14 ++++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 67cc2df..f870537 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,3 +21,4 @@ crossbeam = "0.2.9" [dev-dependencies] slog-term = "2" +slog-async = "2" diff --git a/lib.rs b/lib.rs index 5285b2a..f773f65 100644 --- a/lib.rs +++ b/lib.rs @@ -109,17 +109,23 @@ impl log::Log for Logger { /// ``` /// #[macro_use] /// extern crate log; +/// #[macro_use(slog_o, slog_kv)] +/// extern crate slog; /// extern crate slog_stdlog; /// extern crate slog_scope; /// extern crate slog_term; +/// extern crate slog_async; +/// +/// use slog::Drain; /// /// fn main() { -/// let decorator = slog_term::TermDecorator::new(); +/// let decorator = slog_term::TermDecorator::new().build(); /// let drain = slog_term::FullFormat::new(decorator).build().fuse(); -/// let logger = slog::Logger::root(drain, o!("version" => env!("CARGO_PKG_VERSION"))); +/// let drain = slog_async::Async::new(drain).build().fuse(); +/// let logger = slog::Logger::root(drain, slog_o!("version" => env!("CARGO_PKG_VERSION"))); /// -/// let _guard = slog_scope::set_global_logger(logger).unwrap(); -/// let _guard = slog_stdlog::init().unwrap(); +/// let _scope_guard = slog_scope::set_global_logger(logger); +/// let _log_guard = slog_stdlog::init().unwrap(); /// // Note: this `info!(...)` macro comes from `log` crate /// info!("standard logging redirected to slog"); /// } From 0f966b6f0a360a2043274505b346f40546930fe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Mon, 29 May 2017 23:11:40 -0700 Subject: [PATCH 23/61] Bump version --- CHANGELOG.md | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 561c78d..2ee3584 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## 3.0.1 - 2017-05-29 +## 3.0.2 - 2017-05-29 ### Fixed * Documentation example for `init` diff --git a/Cargo.toml b/Cargo.toml index f870537..db75a58 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "3.0.1" +version = "3.0.2" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] From 415426e7c6738c4c713f5cc9b20fa6a5e3619aed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Mon, 29 May 2017 23:11:57 -0700 Subject: [PATCH 24/61] (cargo-release) start next development iteration 3.0.3-pre --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index db75a58..a6582ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "3.0.2" +version = "3.0.3-pre" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] From 77d1e0a699aac5c6a00b90c1cccf3f023a80bc24 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Thu, 29 Mar 2018 09:41:58 -0700 Subject: [PATCH 25/61] Fix typo in README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 44d7043..0813ff1 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ ## slog-stdlog - `log` crate adapter for [slog-rs] -See [slog-stdlog documentaiton](https://docs.rs/slog-stdlog) for details. +See [slog-stdlog documentation](https://docs.rs/slog-stdlog) for details. For more information, help, to report issues etc. see [slog-rs][slog-rs]. From 0551e6ad6761abbc5ccbddc0981ca164a8be4b77 Mon Sep 17 00:00:00 2001 From: Christopher Durham Date: Fri, 27 Apr 2018 20:05:10 -0400 Subject: [PATCH 26/61] KSV serialize key: slog::Key instead of &str --- lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib.rs b/lib.rs index f773f65..cb8595c 100644 --- a/lib.rs +++ b/lib.rs @@ -238,7 +238,7 @@ impl KSV { } impl slog::Serializer for KSV { - fn emit_arguments(&mut self, key: &str, val: &fmt::Arguments) -> slog::Result { + fn emit_arguments(&mut self, key: slog::Key, val: &fmt::Arguments) -> slog::Result { try!(write!(self.io, ", {}: {}", key, val)); Ok(()) } From f2bccad18d6132c29a0ffa012e3f9960e04fe814 Mon Sep 17 00:00:00 2001 From: siddontang Date: Thu, 30 Aug 2018 14:57:54 +0800 Subject: [PATCH 27/61] add init_with_level function to pass log level explicitly Signed-off-by: siddontang --- Cargo.toml | 2 +- lib.rs | 66 ++++++++++++++++++++++++++++++++++++++---------------- 2 files changed, 48 insertions(+), 20 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a6582ad..a850dc6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "3.0.3-pre" +version = "3.0.4-pre" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] diff --git a/lib.rs b/lib.rs index cb8595c..500fe87 100644 --- a/lib.rs +++ b/lib.rs @@ -50,11 +50,11 @@ #[macro_use] extern crate slog; -extern crate slog_scope; extern crate log; +extern crate slog_scope; use log::LogMetadata; -use std::{io, fmt}; +use std::{fmt, io}; use slog::Level; use slog::KV; @@ -87,17 +87,16 @@ impl log::Log for Logger { let s = slog::RecordStatic { location: &slog::RecordLocation { - file: file, - line: line, - column: 0, - function: "", - module: module, - }, + file: file, + line: line, + column: 0, + function: "", + module: module, + }, level: level, tag: target, }; slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!()))) - } } @@ -131,10 +130,45 @@ impl log::Log for Logger { /// } /// ``` pub fn init() -> Result<(), log::SetLoggerError> { + init_with_level(log::LogLevel::max()) +} + +/// Register `slog-stdlog` as `log` backend. +/// Pass a log::LogLevel to do the log filter explicitly. +/// +/// This will pass all logging statements crated with `log` +/// crate to current `slog-scope::logger()`. +/// +/// ``` +/// #[macro_use] +/// extern crate log; +/// #[macro_use(slog_o, slog_kv)] +/// extern crate slog; +/// extern crate slog_stdlog; +/// extern crate slog_scope; +/// extern crate slog_term; +/// extern crate slog_async; +/// +/// use slog::Drain; +/// +/// fn main() { +/// let decorator = slog_term::TermDecorator::new().build(); +/// let drain = slog_term::FullFormat::new(decorator).build().fuse(); +/// let drain = slog_async::Async::new(drain).build().fuse(); +/// let logger = slog::Logger::root(drain, slog_o!("version" => env!("CARGO_PKG_VERSION"))); +/// +/// let _scope_guard = slog_scope::set_global_logger(logger); +/// let _log_guard = slog_stdlog::init_with_level(log::LogLevel::Error).unwrap(); +/// // Note: this `info!(...)` macro comes from `log` crate +/// info!("standard logging redirected to slog"); +/// error!("standard logging redirected to slog"); +/// } +/// ``` +pub fn init_with_level(level: log::LogLevel) -> Result<(), log::SetLoggerError> { log::set_logger(|max_log_level| { - max_log_level.set(log::LogLevelFilter::max()); - Box::new(Logger) - }) + max_log_level.set(level.to_log_level_filter()); + Box::new(Logger) + }) } /// Drain logging `Record`s into `log` crate @@ -157,7 +191,6 @@ struct LazyLogString<'a> { impl<'a> LazyLogString<'a> { fn new(info: &'a slog::Record, logger_values: &'a slog::OwnedKVList) -> Self { - LazyLogString { info: info, logger_values: logger_values, @@ -167,7 +200,6 @@ impl<'a> LazyLogString<'a> { impl<'a> fmt::Display for LazyLogString<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}", self.info.msg())); let io = io::Cursor::new(Vec::new()); @@ -179,16 +211,13 @@ impl<'a> fmt::Display for LazyLogString<'a> { try!(self.info.kv().serialize(self.info, &mut ser)); Ok(()) } - }() - .map_err(|_| fmt::Error); + }().map_err(|_| fmt::Error); try!(res); let values = ser.into_inner().into_inner(); - write!(f, "{}", String::from_utf8_lossy(&values)) - } } @@ -196,7 +225,6 @@ impl slog::Drain for StdLog { type Err = io::Error; type Ok = (); fn log(&self, info: &slog::Record, logger_values: &slog::OwnedKVList) -> io::Result<()> { - let level = match info.level() { slog::Level::Critical | slog::Level::Error => log::LogLevel::Error, slog::Level::Warning => log::LogLevel::Warn, From abeb776a0f934aebd55730e3404e3ca60e75181c Mon Sep 17 00:00:00 2001 From: Greg Weber Date: Thu, 6 Sep 2018 15:14:01 -0700 Subject: [PATCH 28/61] add missing license files --- LICENSE-APACHE | 201 +++++++++++++++++++++++++++++++++++++++++++++++++ LICENSE-MIT | 25 ++++++ 2 files changed, 226 insertions(+) create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + 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/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,25 @@ +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. From 059224d4808c44423a56f1957b33d0e3ea656cbf Mon Sep 17 00:00:00 2001 From: Aaron Gallagher <_@habnab.it> Date: Fri, 21 Dec 2018 19:36:07 -0800 Subject: [PATCH 29/61] Set a default target on StdLog. For cases where slog records don't have a tag set, use the same default target as the log crate's default target: the module path. --- lib.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib.rs b/lib.rs index 500fe87..f85c71e 100644 --- a/lib.rs +++ b/lib.rs @@ -233,7 +233,10 @@ impl slog::Drain for StdLog { slog::Level::Trace => log::LogLevel::Trace, }; - let target = info.tag(); + let mut target = info.tag(); + if target.is_empty() { + target = info.module(); + } let location = log::LogLocation { __module_path: info.module(), From d49eb1c5a5db86004b93c04337fc53a73f0b36c1 Mon Sep 17 00:00:00 2001 From: XX Date: Thu, 11 Jul 2019 01:07:39 +0300 Subject: [PATCH 30/61] Update log dependency --- .gitignore | 3 ++ Cargo.toml | 5 ++- lib.rs | 116 +++++++++++++++++++++++++---------------------------- 3 files changed, 61 insertions(+), 63 deletions(-) diff --git a/.gitignore b/.gitignore index 6e8e3dc..95139b1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ /tags /.cargo /rusty-tags.vi + +/.idea +*.iml \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index a850dc6..c2358f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ documentation = "https://docs.rs/slog-stdlog" homepage = "https://github.com/slog-rs/stdlog" repository = "https://github.com/slog-rs/stdlog" readme = "README.md" +edition = "2018" [lib] path = "lib.rs" @@ -16,8 +17,8 @@ path = "lib.rs" [dependencies] slog = "2" slog-scope = "4" -log = "0.3.6" -crossbeam = "0.2.9" +log = { version = "0.4.6", features = ["std"] } +crossbeam = "0.7.1" [dev-dependencies] slog-term = "2" diff --git a/lib.rs b/lib.rs index f85c71e..9e3dfe6 100644 --- a/lib.rs +++ b/lib.rs @@ -48,56 +48,57 @@ //! ``` #![warn(missing_docs)] -#[macro_use] -extern crate slog; extern crate log; -extern crate slog_scope; -use log::LogMetadata; use std::{fmt, io}; - -use slog::Level; -use slog::KV; +use slog::{Level, KV, b}; struct Logger; -fn log_to_slog_level(level: log::LogLevel) -> Level { +fn log_to_slog_level(level: log::Level) -> Level { match level { - log::LogLevel::Trace => Level::Trace, - log::LogLevel::Debug => Level::Debug, - log::LogLevel::Info => Level::Info, - log::LogLevel::Warn => Level::Warning, - log::LogLevel::Error => Level::Error, + log::Level::Trace => Level::Trace, + log::Level::Debug => Level::Debug, + log::Level::Info => Level::Info, + log::Level::Warn => Level::Warning, + log::Level::Error => Level::Error, + } +} + +fn record_as_location(r: &log::Record) -> slog::RecordLocation { + let module = r.module_path().unwrap_or(""); + let file = r.file().unwrap_or(""); + let line = r.line().unwrap_or_default(); + + slog::RecordLocation { + file: unsafe { &*(file as *const _) }, // Lifetime extending for initially static ref + line, + column: 0, + function: "", + module: unsafe { &*(module as *const _) }, // Lifetime extending for initially static ref } } impl log::Log for Logger { - fn enabled(&self, _: &LogMetadata) -> bool { + fn enabled(&self, _: &log::Metadata) -> bool { true } - fn log(&self, r: &log::LogRecord) { + fn log(&self, r: &log::Record) { let level = log_to_slog_level(r.metadata().level()); let args = r.args(); let target = r.target(); - let module = r.location().__module_path; - let file = r.location().__file; - let line = r.location().line(); - + let location = &record_as_location(r); let s = slog::RecordStatic { - location: &slog::RecordLocation { - file: file, - line: line, - column: 0, - function: "", - module: module, - }, - level: level, + location, + level, tag: target, }; slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!()))) } + + fn flush(&self) {} } /// Register `slog-stdlog` as `log` backend. @@ -130,11 +131,11 @@ impl log::Log for Logger { /// } /// ``` pub fn init() -> Result<(), log::SetLoggerError> { - init_with_level(log::LogLevel::max()) + init_with_level(log::Level::max()) } /// Register `slog-stdlog` as `log` backend. -/// Pass a log::LogLevel to do the log filter explicitly. +/// Pass a log::Level to do the log filter explicitly. /// /// This will pass all logging statements crated with `log` /// crate to current `slog-scope::logger()`. @@ -158,17 +159,17 @@ pub fn init() -> Result<(), log::SetLoggerError> { /// let logger = slog::Logger::root(drain, slog_o!("version" => env!("CARGO_PKG_VERSION"))); /// /// let _scope_guard = slog_scope::set_global_logger(logger); -/// let _log_guard = slog_stdlog::init_with_level(log::LogLevel::Error).unwrap(); +/// let _log_guard = slog_stdlog::init_with_level(log::Level::Error).unwrap(); /// // Note: this `info!(...)` macro comes from `log` crate /// info!("standard logging redirected to slog"); /// error!("standard logging redirected to slog"); /// } /// ``` -pub fn init_with_level(level: log::LogLevel) -> Result<(), log::SetLoggerError> { - log::set_logger(|max_log_level| { - max_log_level.set(level.to_log_level_filter()); - Box::new(Logger) - }) +pub fn init_with_level(level: log::Level) -> Result<(), log::SetLoggerError> { + log::set_boxed_logger(Box::new(Logger))?; + log::set_max_level(level.to_level_filter()); + + Ok(()) } /// Drain logging `Record`s into `log` crate @@ -192,28 +193,26 @@ struct LazyLogString<'a> { impl<'a> LazyLogString<'a> { fn new(info: &'a slog::Record, logger_values: &'a slog::OwnedKVList) -> Self { LazyLogString { - info: info, - logger_values: logger_values, + info, + logger_values, } } } impl<'a> fmt::Display for LazyLogString<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}", self.info.msg())); + write!(f, "{}", self.info.msg())?; let io = io::Cursor::new(Vec::new()); let mut ser = KSV::new(io); - let res = { - || -> io::Result<()> { - try!(self.logger_values.serialize(self.info, &mut ser)); - try!(self.info.kv().serialize(self.info, &mut ser)); - Ok(()) - } - }().map_err(|_| fmt::Error); - - try!(res); + self.logger_values + .serialize(self.info, &mut ser) + .map_err(|_| fmt::Error)?; + self.info + .kv() + .serialize(self.info, &mut ser) + .map_err(|_| fmt::Error)?; let values = ser.into_inner().into_inner(); @@ -222,15 +221,16 @@ impl<'a> fmt::Display for LazyLogString<'a> { } impl slog::Drain for StdLog { - type Err = io::Error; type Ok = (); + type Err = io::Error; + fn log(&self, info: &slog::Record, logger_values: &slog::OwnedKVList) -> io::Result<()> { let level = match info.level() { - slog::Level::Critical | slog::Level::Error => log::LogLevel::Error, - slog::Level::Warning => log::LogLevel::Warn, - slog::Level::Info => log::LogLevel::Info, - slog::Level::Debug => log::LogLevel::Debug, - slog::Level::Trace => log::LogLevel::Trace, + slog::Level::Critical | slog::Level::Error => log::Level::Error, + slog::Level::Warning => log::Level::Warn, + slog::Level::Info => log::Level::Info, + slog::Level::Debug => log::Level::Debug, + slog::Level::Trace => log::Level::Trace, }; let mut target = info.tag(); @@ -238,16 +238,10 @@ impl slog::Drain for StdLog { target = info.module(); } - let location = log::LogLocation { - __module_path: info.module(), - __file: info.file(), - __line: info.line(), - }; - let lazy = LazyLogString::new(info, logger_values); // Please don't yell at me for this! :D // https://github.com/rust-lang-nursery/log/issues/95 - log::__log(level, target, &location, format_args!("{}", lazy)); + log::__private_api_log(format_args!("{}", lazy), level, &(target, info.module(), info.file(), info.line())); Ok(()) } @@ -270,7 +264,7 @@ impl KSV { impl slog::Serializer for KSV { fn emit_arguments(&mut self, key: slog::Key, val: &fmt::Arguments) -> slog::Result { - try!(write!(self.io, ", {}: {}", key, val)); + write!(self.io, ", {}: {}", key, val)?; Ok(()) } } From 330f331f56f5cf9ae7f809ee5e748319caaefba0 Mon Sep 17 00:00:00 2001 From: Eran Rundstein Date: Wed, 24 Jul 2019 13:51:33 -0700 Subject: [PATCH 31/61] bump version to 3.0.5 since -pre suffix seems to break on crates.io --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index a850dc6..0fc8a49 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "3.0.4-pre" +version = "3.0.5" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] From e599a2464db5372acbe1f6e75bdb806423d3b172 Mon Sep 17 00:00:00 2001 From: Alexander XX Date: Thu, 1 Aug 2019 22:48:00 +0300 Subject: [PATCH 32/61] Update log version and remove unsafe cast --- Cargo.toml | 2 +- lib.rs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c2358f2..cbd35d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ path = "lib.rs" [dependencies] slog = "2" slog-scope = "4" -log = { version = "0.4.6", features = ["std"] } +log = { version = "0.4.8", features = ["std"] } crossbeam = "0.7.1" [dev-dependencies] diff --git a/lib.rs b/lib.rs index 9e3dfe6..532dd89 100644 --- a/lib.rs +++ b/lib.rs @@ -66,16 +66,16 @@ fn log_to_slog_level(level: log::Level) -> Level { } fn record_as_location(r: &log::Record) -> slog::RecordLocation { - let module = r.module_path().unwrap_or(""); - let file = r.file().unwrap_or(""); + let module = r.module_path_static().unwrap_or(""); + let file = r.file_static().unwrap_or(""); let line = r.line().unwrap_or_default(); slog::RecordLocation { - file: unsafe { &*(file as *const _) }, // Lifetime extending for initially static ref + file, line, column: 0, function: "", - module: unsafe { &*(module as *const _) }, // Lifetime extending for initially static ref + module, } } From 757cd6c4d0667db1987b239eef14d4be0a5903b3 Mon Sep 17 00:00:00 2001 From: Eran Rundstein Date: Tue, 13 Aug 2019 12:42:31 -0700 Subject: [PATCH 33/61] update changelog, bump version. --- CHANGELOG.md | 5 +++++ Cargo.toml | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ee3584..f4563a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 4.0.0 - 2018-08-13 +### Changed + +* Update to `log` 0.4 + ## 3.0.2 - 2017-05-29 ### Fixed diff --git a/Cargo.toml b/Cargo.toml index 9e7f066..ba303e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "3.0.5" +version = "4.0.0" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] From 0651ae08d2b42a52940fd18172a231a627a06f55 Mon Sep 17 00:00:00 2001 From: Thomas Whiteway Date: Thu, 10 Oct 2019 16:56:14 +0100 Subject: [PATCH 34/61] Require slog 2.4 or greater lib.rs uses Rust 2018 style macro imports to import b!, which depends on kv!, however slog only defined kv! using local_inner_macros from 2.4.0 so slog-stdlog will fail to compile against versions of slog prior to 2.4.0. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index ba303e7..2b15703 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ edition = "2018" path = "lib.rs" [dependencies] -slog = "2" +slog = "2.4" slog-scope = "4" log = { version = "0.4.8", features = ["std"] } crossbeam = "0.7.1" From 801513b50ab0c83fefb939939055ca606436d204 Mon Sep 17 00:00:00 2001 From: Belousow Makc Date: Mon, 16 Dec 2019 18:31:54 +0300 Subject: [PATCH 35/61] Add support to log == 0.4.10. This commit update signature of private log api, changed in version 0.4.10. --- lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib.rs b/lib.rs index 532dd89..17b404a 100644 --- a/lib.rs +++ b/lib.rs @@ -241,7 +241,7 @@ impl slog::Drain for StdLog { let lazy = LazyLogString::new(info, logger_values); // Please don't yell at me for this! :D // https://github.com/rust-lang-nursery/log/issues/95 - log::__private_api_log(format_args!("{}", lazy), level, &(target, info.module(), info.file(), info.line())); + log::__private_api_log(format_args!("{}", lazy), level, &(target, info.module(), info.file(), info.line()), None); Ok(()) } From 959260635e3b55f16bb8e2aeb0dca955d5ba27ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Thu, 19 Dec 2019 22:37:43 -0800 Subject: [PATCH 36/61] Require `log = 0.4.10` for the new macro --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 2b15703..410dd89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ path = "lib.rs" [dependencies] slog = "2.4" slog-scope = "4" -log = { version = "0.4.8", features = ["std"] } +log = { version = "0.4.10", features = ["std"] } crossbeam = "0.7.1" [dev-dependencies] From da35189c22982c6f761deb7ce0e0aa53bccea689 Mon Sep 17 00:00:00 2001 From: Philip Hayes Date: Tue, 18 Feb 2020 11:03:08 -0800 Subject: [PATCH 37/61] Remove unused dependency `crossbeam = 0.7.1` --- Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 410dd89..b62884f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,6 @@ path = "lib.rs" slog = "2.4" slog-scope = "4" log = { version = "0.4.10", features = ["std"] } -crossbeam = "0.7.1" [dev-dependencies] slog-term = "2" From 508156e22798857644299fc65712650e1cee5929 Mon Sep 17 00:00:00 2001 From: Zhang Jingqiang Date: Wed, 21 Oct 2020 09:18:37 +0800 Subject: [PATCH 38/61] fix compilation --- lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib.rs b/lib.rs index 17b404a..532dd89 100644 --- a/lib.rs +++ b/lib.rs @@ -241,7 +241,7 @@ impl slog::Drain for StdLog { let lazy = LazyLogString::new(info, logger_values); // Please don't yell at me for this! :D // https://github.com/rust-lang-nursery/log/issues/95 - log::__private_api_log(format_args!("{}", lazy), level, &(target, info.module(), info.file(), info.line()), None); + log::__private_api_log(format_args!("{}", lazy), level, &(target, info.module(), info.file(), info.line())); Ok(()) } From 0649588d137e4e75a8ba5fe1afd2bd8f5d69e652 Mon Sep 17 00:00:00 2001 From: Zhang Jingqiang Date: Thu, 22 Oct 2020 08:24:46 +0800 Subject: [PATCH 39/61] require log >= 0.4.11 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index b62884f..d0ef81c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ path = "lib.rs" [dependencies] slog = "2.4" slog-scope = "4" -log = { version = "0.4.10", features = ["std"] } +log = { version = "0.4.11", features = ["std"] } [dev-dependencies] slog-term = "2" From 58443b297d3cc9c59830571e6d71d21ea7b973a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Wed, 21 Oct 2020 17:53:54 -0700 Subject: [PATCH 40/61] Bump version --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index d0ef81c..650af44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "4.0.0" +version = "4.1.0" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] From fb1f0d56a1031b331bf6ac961dcb09c460cbfffd Mon Sep 17 00:00:00 2001 From: John Batty Date: Thu, 3 Jun 2021 08:57:45 +0100 Subject: [PATCH 41/61] Fix license field to be a valid SPDX expression --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 650af44..5fd9b9c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ version = "4.1.0" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] -license = "MPL-2.0/MIT/Apache-2.0" +license = "MPL-2.0 OR MIT OR Apache-2.0" documentation = "https://docs.rs/slog-stdlog" homepage = "https://github.com/slog-rs/stdlog" repository = "https://github.com/slog-rs/stdlog" From 5615f0417752e5f4c126468569b287ca93c86aae Mon Sep 17 00:00:00 2001 From: fiag Date: Thu, 24 Jun 2021 19:57:04 +0800 Subject: [PATCH 42/61] Update: support log kv_unstable --- Cargo.toml | 2 +- lib.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5fd9b9c..3bf24ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ path = "lib.rs" [dependencies] slog = "2.4" slog-scope = "4" -log = { version = "0.4.11", features = ["std"] } +log = { version = "0.4.11", features = ["std", "kv_unstable"] } [dev-dependencies] slog-term = "2" diff --git a/lib.rs b/lib.rs index 532dd89..82834cd 100644 --- a/lib.rs +++ b/lib.rs @@ -51,7 +51,7 @@ extern crate log; use std::{fmt, io}; -use slog::{Level, KV, b}; +use slog::{Level, KV, b, Record, Serializer}; struct Logger; @@ -89,18 +89,60 @@ impl log::Log for Logger { let args = r.args(); let target = r.target(); + let key_values = r.key_values(); let location = &record_as_location(r); let s = slog::RecordStatic { location, level, tag: target, }; - slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!()))) + let mut visitor = Visitor::new(); + key_values.visit(&mut visitor).unwrap(); + slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!(visitor)))) } fn flush(&self) {} } +struct Visitor { + kvs: Vec<(String, String)>, +} + +impl Visitor { + pub fn new() -> Self { + Self { kvs: vec![] } + } +} + +impl<'kvs, 'a> log::kv::Visitor<'kvs> for Visitor { + fn visit_pair( + &mut self, + key: log::kv::Key<'kvs>, + val: log::kv::Value<'kvs>, + ) -> Result<(), log::kv::Error> { + let key = key.to_string(); + if let Some(val) = val.to_borrowed_str() { + let val = val.to_string(); + self.kvs.push((key, val)); + } + Ok(()) + } +} + +fn string_to_static_str(s: String) -> &'static str { + Box::leak(s.into_boxed_str()) +} + +impl slog::KV for Visitor { + fn serialize(&self, _record: &Record, serializer: &mut dyn Serializer) -> slog::Result { + for (key, val) in &self.kvs { + let key = string_to_static_str(key.to_owned()); + serializer.emit_str(key, val.as_str())?; + } + Ok(()) + } +} + /// Register `slog-stdlog` as `log` backend. /// /// This will pass all logging statements crated with `log` From 94e4e7eeefad1d34af5d5b0edb3c09639e1e3da8 Mon Sep 17 00:00:00 2001 From: fiag Date: Mon, 28 Jun 2021 15:30:33 +0800 Subject: [PATCH 43/61] Update: add feature kv_unstable. --- Cargo.toml | 6 ++++- kv.rs | 40 ++++++++++++++++++++++++++++++++ lib.rs | 67 +++++++++++++++++++++--------------------------------- 3 files changed, 71 insertions(+), 42 deletions(-) create mode 100644 kv.rs diff --git a/Cargo.toml b/Cargo.toml index 3bf24ca..4987845 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,10 +14,14 @@ edition = "2018" [lib] path = "lib.rs" +[features] +default = [] +kv_unstable = ["log/kv_unstable_std"] + [dependencies] slog = "2.4" slog-scope = "4" -log = { version = "0.4.11", features = ["std", "kv_unstable"] } +log = { version = "0.4.11", features = ["std"] } [dev-dependencies] slog-term = "2" diff --git a/kv.rs b/kv.rs new file mode 100644 index 0000000..72ef6be --- /dev/null +++ b/kv.rs @@ -0,0 +1,40 @@ +use slog::{Level, Record, Serializer, KV}; + +pub(crate) struct Visitor { + kvs: Vec<(String, String)>, +} + +impl Visitor { + pub fn new() -> Self { + Self { kvs: vec![] } + } +} + +impl<'kvs, 'a> log::kv::Visitor<'kvs> for Visitor { + fn visit_pair( + &mut self, + key: log::kv::Key<'kvs>, + val: log::kv::Value<'kvs>, + ) -> Result<(), log::kv::Error> { + let key = key.to_string(); + if let Some(val) = val.to_borrowed_str() { + let val = val.to_string(); + self.kvs.push((key, val)); + } + Ok(()) + } +} + +fn string_to_static_str(s: String) -> &'static str { + Box::leak(s.into_boxed_str()) +} + +impl slog::KV for Visitor { + fn serialize(&self, _record: &Record, serializer: &mut dyn Serializer) -> slog::Result { + for (key, val) in &self.kvs { + let key = string_to_static_str(key.to_owned()); + serializer.emit_str(key, val.as_str())?; + } + Ok(()) + } +} \ No newline at end of file diff --git a/lib.rs b/lib.rs index 82834cd..f5cef45 100644 --- a/lib.rs +++ b/lib.rs @@ -50,8 +50,16 @@ extern crate log; +#[cfg(feature = "kv_unstable")] +mod kv; + use std::{fmt, io}; -use slog::{Level, KV, b, Record, Serializer}; + +#[cfg(not(feature = "kv_unstable"))] +use slog::{b, Level, KV}; + +#[cfg(feature = "kv_unstable")] +use slog::{b, Level, Record, Serializer, KV}; struct Logger; @@ -84,6 +92,22 @@ impl log::Log for Logger { true } + #[cfg(not(feature = "kv_unstable"))] + fn log(&self, r: &log::Record) { + let level = log_to_slog_level(r.metadata().level()); + + let args = r.args(); + let target = r.target(); + let location = &record_as_location(r); + let s = slog::RecordStatic { + location, + level, + tag: target, + }; + slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!()))) + } + + #[cfg(feature = "kv_unstable")] fn log(&self, r: &log::Record) { let level = log_to_slog_level(r.metadata().level()); @@ -96,7 +120,7 @@ impl log::Log for Logger { level, tag: target, }; - let mut visitor = Visitor::new(); + let mut visitor = kv::Visitor::new(); key_values.visit(&mut visitor).unwrap(); slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!(visitor)))) } @@ -104,45 +128,6 @@ impl log::Log for Logger { fn flush(&self) {} } -struct Visitor { - kvs: Vec<(String, String)>, -} - -impl Visitor { - pub fn new() -> Self { - Self { kvs: vec![] } - } -} - -impl<'kvs, 'a> log::kv::Visitor<'kvs> for Visitor { - fn visit_pair( - &mut self, - key: log::kv::Key<'kvs>, - val: log::kv::Value<'kvs>, - ) -> Result<(), log::kv::Error> { - let key = key.to_string(); - if let Some(val) = val.to_borrowed_str() { - let val = val.to_string(); - self.kvs.push((key, val)); - } - Ok(()) - } -} - -fn string_to_static_str(s: String) -> &'static str { - Box::leak(s.into_boxed_str()) -} - -impl slog::KV for Visitor { - fn serialize(&self, _record: &Record, serializer: &mut dyn Serializer) -> slog::Result { - for (key, val) in &self.kvs { - let key = string_to_static_str(key.to_owned()); - serializer.emit_str(key, val.as_str())?; - } - Ok(()) - } -} - /// Register `slog-stdlog` as `log` backend. /// /// This will pass all logging statements crated with `log` From ea5e5b68e5dc69a3fdcada7f6133f8cdd84e75d2 Mon Sep 17 00:00:00 2001 From: fiag Date: Mon, 28 Jun 2021 15:31:52 +0800 Subject: [PATCH 44/61] Update: add newline at end of file. --- kv.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kv.rs b/kv.rs index 72ef6be..9bbab20 100644 --- a/kv.rs +++ b/kv.rs @@ -37,4 +37,4 @@ impl slog::KV for Visitor { } Ok(()) } -} \ No newline at end of file +} From 766e13bd8b9e3e77e5faec4e3a3c19e57982fe53 Mon Sep 17 00:00:00 2001 From: fiag Date: Mon, 5 Jul 2021 18:43:26 +0800 Subject: [PATCH 45/61] Update: add feature kv_unstable to code block. --- lib.rs | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/lib.rs b/lib.rs index f5cef45..b57eaed 100644 --- a/lib.rs +++ b/lib.rs @@ -92,7 +92,6 @@ impl log::Log for Logger { true } - #[cfg(not(feature = "kv_unstable"))] fn log(&self, r: &log::Record) { let level = log_to_slog_level(r.metadata().level()); @@ -104,27 +103,17 @@ impl log::Log for Logger { level, tag: target, }; + #[cfg(feature = "kv_unstable")] + { + let key_values = r.key_values(); + let mut visitor = kv::Visitor::new(); + key_values.visit(&mut visitor).unwrap(); + slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!(visitor)))) + } + #[cfg(not(feature = "kv_unstable"))] slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!()))) } - #[cfg(feature = "kv_unstable")] - fn log(&self, r: &log::Record) { - let level = log_to_slog_level(r.metadata().level()); - - let args = r.args(); - let target = r.target(); - let key_values = r.key_values(); - let location = &record_as_location(r); - let s = slog::RecordStatic { - location, - level, - tag: target, - }; - let mut visitor = kv::Visitor::new(); - key_values.visit(&mut visitor).unwrap(); - slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!(visitor)))) - } - fn flush(&self) {} } From 6df32956a9e364d313e3071a6c7b2c7f67931aad Mon Sep 17 00:00:00 2001 From: fiag Date: Tue, 6 Jul 2021 17:09:03 +0800 Subject: [PATCH 46/61] Update: use dynamic keys --- Cargo.toml | 2 +- kv.rs | 9 ++------- lib.rs | 4 ---- 3 files changed, 3 insertions(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4987845..4070f0c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ path = "lib.rs" [features] default = [] -kv_unstable = ["log/kv_unstable_std"] +kv_unstable = ["log/kv_unstable_std", "slog/dynamic-keys"] [dependencies] slog = "2.4" diff --git a/kv.rs b/kv.rs index 9bbab20..2172843 100644 --- a/kv.rs +++ b/kv.rs @@ -1,4 +1,4 @@ -use slog::{Level, Record, Serializer, KV}; +use slog::{Record, Serializer}; pub(crate) struct Visitor { kvs: Vec<(String, String)>, @@ -25,15 +25,10 @@ impl<'kvs, 'a> log::kv::Visitor<'kvs> for Visitor { } } -fn string_to_static_str(s: String) -> &'static str { - Box::leak(s.into_boxed_str()) -} - impl slog::KV for Visitor { fn serialize(&self, _record: &Record, serializer: &mut dyn Serializer) -> slog::Result { for (key, val) in &self.kvs { - let key = string_to_static_str(key.to_owned()); - serializer.emit_str(key, val.as_str())?; + serializer.emit_str(key.to_owned().into(), val.as_str())?; } Ok(()) } diff --git a/lib.rs b/lib.rs index b57eaed..789cc55 100644 --- a/lib.rs +++ b/lib.rs @@ -55,12 +55,8 @@ mod kv; use std::{fmt, io}; -#[cfg(not(feature = "kv_unstable"))] use slog::{b, Level, KV}; -#[cfg(feature = "kv_unstable")] -use slog::{b, Level, Record, Serializer, KV}; - struct Logger; fn log_to_slog_level(level: log::Level) -> Level { From 71fe9d3d69b81fc9d232910a8866f5d3b885db43 Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 16:59:28 -0700 Subject: [PATCH 47/61] Avoid using log's private API to construct records Previously this API was required to work around rust-lang/log#95 Thanks to the inclusion of a `RecordBuilder` (PR rust-lang/log#211) it is no longer required. This fixes slog-rs/slog#309 This supersedes PR #20 I have added a comment about supporting the log/kv_unstable feature in the future. Not supporting this feature doesn't break backwards compat, because the old usage of the private API didn't support it either. Therefore, this new code doesn't break or remove anything that was already existing. However,from a feature-completeness standpoint it would be nice to have this in the future. (see comment in code) --- lib.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/lib.rs b/lib.rs index 842b7ce..1ad026d 100644 --- a/lib.rs +++ b/lib.rs @@ -250,9 +250,32 @@ impl slog::Drain for StdLog { } let lazy = LazyLogString::new(info, logger_values); - // Please don't yell at me for this! :D - // https://github.com/rust-lang-nursery/log/issues/95 - log::__private_api_log(format_args!("{}", lazy), level, &(target, info.module(), info.file(), info.line())); + /* + * TODO: Support `log` crate key_values here. + * + * This requires the log/kv_unstable feature here. + * + * Not supporting this feature is backwards compatible + * and it shouldn't break anything (because we've never had), + * but is undesirable from a feature-completeness point of view. + * + * However, this is most likely not as powerful as slog's own + * notion of key/value pairs, so I would humbly suggest using `slog` + * directly if this feature is important to you ;) + * + * This avoids using the private log::__private_api_log api function, + * which is just a thin wrapper around a `RecordBuilder`. + */ + log::logger().log( + &log::Record::builder() + .args(format_args!("{}", lazy)) + .level(level) + .target(target) + .module_path_static(Some(info.module())) + .file_static(Some(info.file())) + .line(Some(info.line())) + .build(), + ); Ok(()) } From e3f25500ba7dbfa6fab1086913965abe409b21f1 Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 17:09:49 -0700 Subject: [PATCH 48/61] Run `cargo fmt` on the code --- lib.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib.rs b/lib.rs index 1ad026d..6ad2a3b 100644 --- a/lib.rs +++ b/lib.rs @@ -53,8 +53,8 @@ extern crate log; #[cfg(feature = "kv_unstable")] mod kv; +use slog::{b, Level, KV}; use std::{fmt, io}; -use slog::{Level, KV, b}; struct Logger; @@ -100,10 +100,10 @@ impl log::Log for Logger { }; #[cfg(feature = "kv_unstable")] { - let key_values = r.key_values(); - let mut visitor = kv::Visitor::new(); - key_values.visit(&mut visitor).unwrap(); - slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!(visitor)))) + let key_values = r.key_values(); + let mut visitor = kv::Visitor::new(); + key_values.visit(&mut visitor).unwrap(); + slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!(visitor)))) } #[cfg(not(feature = "kv_unstable"))] slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!()))) From 31221cba09ef98cf51d0e9786237a4db1d61a00d Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 17:10:51 -0700 Subject: [PATCH 49/61] Fix clippy lints --- lib.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib.rs b/lib.rs index 6ad2a3b..4b9f8e9 100644 --- a/lib.rs +++ b/lib.rs @@ -215,7 +215,7 @@ impl<'a> fmt::Display for LazyLogString<'a> { write!(f, "{}", self.info.msg())?; let io = io::Cursor::new(Vec::new()); - let mut ser = KSV::new(io); + let mut ser = Ksv::new(io); self.logger_values .serialize(self.info, &mut ser) @@ -282,13 +282,13 @@ impl slog::Drain for StdLog { } /// Key-Separator-Value serializer -struct KSV { +struct Ksv { io: W, } -impl KSV { +impl Ksv { fn new(io: W) -> Self { - KSV { io: io } + Ksv { io } } fn into_inner(self) -> W { @@ -296,7 +296,7 @@ impl KSV { } } -impl slog::Serializer for KSV { +impl slog::Serializer for Ksv { fn emit_arguments(&mut self, key: slog::Key, val: &fmt::Arguments) -> slog::Result { write!(self.io, ", {}: {}", key, val)?; Ok(()) From 814587f2e7c0249e16b9b7045e3c1c2624a4b5c6 Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 17:20:50 -0700 Subject: [PATCH 50/61] Document Minimum Supported Rust Version (1.38) Add badge to README :) This was automatically detected by `cargo msrv`. This commit does not change anything, it simply documents what already exists. --- Cargo.toml | 12 ++++++++++++ README.md | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 4070f0c..645f3d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,18 @@ homepage = "https://github.com/slog-rs/stdlog" repository = "https://github.com/slog-rs/stdlog" readme = "README.md" edition = "2018" +# This is our Minimum Supported Rust Version (MSRV) +# +# To change this, you must also: +# 1. Update the README file +# 2. Update the github actions file +# 3. Have an appropriate change to the minor version +# +# See the Cargo.toml in the primary slog repo for more details +# +# The first version of Cargo that supports this field was in Rust 1.56.0. +# In older releases, the field will be ignored, and Cargo will display a warning. +rust-version = "1.38" [lib] path = "lib.rs" diff --git a/README.md b/README.md index 0813ff1..78d825b 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,10 @@ slog-rs Gitter Chat + + + Minimum Rust Version 1.38 +

## slog-stdlog - `log` crate adapter for [slog-rs] From 17d94eb42ab663be7cf0f56267ef9b258f165b4f Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 17:32:33 -0700 Subject: [PATCH 51/61] Bump claimed MSRV to 1.39 This is required for the log/kv_unstable feature. This doesn't break 1.38 compatibility in any way shape or form. It mearly changes the documentation and the official guarentees. If you want, you can still use Rust 1.38. However, you will need to disable the log/kv_unstable feature. The advantage of this change is that it makes Github Actions testing easier. e only need to test a single MSRV, instead of a different one for each feature combination :) --- Cargo.toml | 2 +- README.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 645f3d4..f85c146 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ edition = "2018" # # The first version of Cargo that supports this field was in Rust 1.56.0. # In older releases, the field will be ignored, and Cargo will display a warning. -rust-version = "1.38" +rust-version = "1.39" [lib] path = "lib.rs" diff --git a/README.md b/README.md index 78d825b..4a650f1 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ slog-rs Gitter Chat - - Minimum Rust Version 1.38 + + Minimum Rust Version 1.38

From 5d67e390ee5c9ac4a2ee08791f6aabc080c81db5 Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 17:35:50 -0700 Subject: [PATCH 52/61] Migrate from Travis CI to Github Actions This commit is based on the Github Actions config in slog-term :) --- .github/workflows/clippy.yml | 39 +++++++++++++++++++++++++++ .github/workflows/rustfmt.yml | 31 +++++++++++++++++++++ .github/workflows/test.yml | 51 +++++++++++++++++++++++++++++++++++ .travis.yml | 26 ------------------ 4 files changed, 121 insertions(+), 26 deletions(-) create mode 100644 .github/workflows/clippy.yml create mode 100644 .github/workflows/rustfmt.yml create mode 100644 .github/workflows/test.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/clippy.yml b/.github/workflows/clippy.yml new file mode 100644 index 0000000..b1aa0ec --- /dev/null +++ b/.github/workflows/clippy.yml @@ -0,0 +1,39 @@ +# This is the clippy workflow, seperate from the main 'Rust' workflow +# +# This will fail if clippy fails (if we encounter any of its "correctness" lints) +# +# Clippy warnings won't fail the build. They may or may not turn into Github warnings. +# +# TODO: Test clippy with different feature combos? +# TODO: Should we fail on clippy warnings? +on: [push, pull_request] +name: Clippy + +env: + CARGO_TERM_COLOR: always + # has a history of occasional bugs (especially on old versions) + # + # the ci is free so we might as well use it ;) + CARGO_INCREMENTAL: 0 + + +jobs: + clippy: + # Only run on PRs if the source branch is on someone else's repo + if: ${{ github.event_name != 'pull_request' || github.repository != github.event.pull_request.head.repo.full_name }} + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - stable + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: ${{ matrix.rust }} + override: true + components: clippy + - shell: bash + run: | + cargo clippy diff --git a/.github/workflows/rustfmt.yml b/.github/workflows/rustfmt.yml new file mode 100644 index 0000000..72659f5 --- /dev/null +++ b/.github/workflows/rustfmt.yml @@ -0,0 +1,31 @@ +# The file is the workflow for rustfmt +# +# It runs `cargo fmt --check` +# +# It will fail if there are formatting problems. +on: [push, pull_request] +name: rustfmt + +env: + CARGO_TERM_COLOR: always + +jobs: + rustfmt: + # Only run on PRs if the source branch is on someone else's repo + if: ${{ github.event_name != 'pull_request' || github.repository != github.event.pull_request.head.repo.full_name }} + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - stable + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: ${{ matrix.rust }} + override: true + components: rustfmt + - shell: bash + run: | + cargo fmt -- --check diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..2d7bca6 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,51 @@ +# We use `actions-rs` for most of our actions +# +# This file is for the main tests. clippy & rustfmt are seperate workflows +# +# It is mostly copied from slog-rs/term +on: [push, pull_request] +name: Cargo Test + +env: + CARGO_TERM_COLOR: always + # has a history of occasional bugs (especially on old versions) + # + # the ci is free so we might as well use it ;) + CARGO_INCREMENTAL: 0 + + +# Tested versions: +# 1. stable +# 2. nightly +# 3. Minimum Supported Rust Version (MSRV) + +jobs: + test: + # Only run on PRs if the source branch is on someone else's repo + if: ${{ github.event_name != 'pull_request' || github.repository != github.event.pull_request.head.repo.full_name }} + + runs-on: ubuntu-latest + strategy: + fail-fast: false # Even if one job fails we still want to see the other ones + matrix: + # 1.39 is MSRV. Keep in sync with Cargo.toml + rust: [1.39, stable, nightly] + # NOTE: Features to test must be specified manually. They are applied to all versions seperately. + # + # This has the advantage of being more flexibile and thorough + # This has the disadvantage of being more vebrose + # + # Specific feature combos can be overriden per-version with 'include' and 'exclude' + features: ["", "kv_unstable"] + + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ matrix.rust }} + override: true + # NOTE: We only run `cargo test`. No need for a seperate `cargo check` + - name: Test + run: | + cargo test --verbose --features "${{ matrix.features }}" + diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 9be8a47..0000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: rust -rust: - - stable - - beta - - nightly - -script: - - make all - - make travistest - - if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then make bench ; fi - - if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then cargo build --no-default-features; fi - -env: - global: - - RUST_BACKTRACE=1 - matrix: - - - - RELEASE=true - -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/87a331e1a21456b6e2ad - on_success: change # options: [always|never|change] default: always - on_failure: change # options: [always|never|change] default: always - on_start: false # default: false From 4c37abac54b6fe5c09647042bf13d3daeb8f162e Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 22:41:33 -0700 Subject: [PATCH 53/61] Fix incorrect space in clippy.yml workflow YAML is a harsh mistress --- .github/workflows/clippy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clippy.yml b/.github/workflows/clippy.yml index b1aa0ec..0875727 100644 --- a/.github/workflows/clippy.yml +++ b/.github/workflows/clippy.yml @@ -32,7 +32,7 @@ jobs: with: profile: minimal toolchain: ${{ matrix.rust }} - override: true + override: true components: clippy - shell: bash run: | From 7a93747adb611af2fff5d68aeaf74b467e40a859 Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 22:45:07 -0700 Subject: [PATCH 54/61] Revert "Bump claimed MSRV to 1.39" Apparently the version actually required by the time/unstable_kv feature is much higher than 1.39. In fact, by my tests it appears to start working around 1.53 This makes it worthwhile to test it seperately and restore the old MSRV. This reverts commit 17d94eb42ab663be7cf0f56267ef9b258f165b4f. --- Cargo.toml | 2 +- README.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f85c146..645f3d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ edition = "2018" # # The first version of Cargo that supports this field was in Rust 1.56.0. # In older releases, the field will be ignored, and Cargo will display a warning. -rust-version = "1.39" +rust-version = "1.38" [lib] path = "lib.rs" diff --git a/README.md b/README.md index 4a650f1..78d825b 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ slog-rs Gitter Chat - - Minimum Rust Version 1.38 + + Minimum Rust Version 1.38

From a1886c94dbebb0ab34f1e9f44d489862f4f72093 Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 22:52:30 -0700 Subject: [PATCH 55/61] Don't test log/unstable_kv feature on the MSRV Due to its unstable feature, it requires a recent compiler and we cannot reasonably make MSRV guarentees for their project. Add disclaimer about this to the Cargo.toml file --- .github/workflows/test.yml | 6 ++++++ Cargo.toml | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2d7bca6..03d86e1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,6 +29,9 @@ jobs: fail-fast: false # Even if one job fails we still want to see the other ones matrix: # 1.39 is MSRV. Keep in sync with Cargo.toml + # + # There are no MSRV guarentees for the kv_unstable feature. + # See `Cargo.toml` for more details. rust: [1.39, stable, nightly] # NOTE: Features to test must be specified manually. They are applied to all versions seperately. # @@ -37,6 +40,9 @@ jobs: # # Specific feature combos can be overriden per-version with 'include' and 'exclude' features: ["", "kv_unstable"] + exclude: + - rust: 1.39 # MSRV (see above) + features: "kv_unstable" steps: - uses: actions/checkout@v2 diff --git a/Cargo.toml b/Cargo.toml index 645f3d4..9b5b576 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,10 @@ edition = "2018" # # The first version of Cargo that supports this field was in Rust 1.56.0. # In older releases, the field will be ignored, and Cargo will display a warning. +# +# DISCLAIMER: +# The log/kv_unstable feature requires a recent (stable) compiler. +# It will not compile with this claimed MSRV and requires a recent (stable) compiler. rust-version = "1.38" [lib] From 4306a1ca3c643ece35e0e2da8eca621e4512c082 Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 22:59:52 -0700 Subject: [PATCH 56/61] Don't run tests on MSRV (only cargo check) The tests break because of the `time` crate (a dev-dependency). To workaround this we only run `cargo check` on the MSRV --- .github/workflows/test.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 03d86e1..40e3474 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -50,8 +50,14 @@ jobs: with: toolchain: ${{ matrix.rust }} override: true - # NOTE: We only run `cargo test`. No need for a seperate `cargo check` + - name: Check + run: | + cargo check --verbose --features "${{ matrix.features }}" + # A failing `cargo check` always fails the build + continue-on-error: false + # NOTE: We only run `cargo test` if version > MSRV. Tests break on old MSRV due to + # a dev-dependency. - name: Test run: | cargo test --verbose --features "${{ matrix.features }}" - + if: "${{ matrix.rust == 'stable' || matrix.rust == 'nightly' }}" From fd09e78b1bf434b87b3d5ad2f1a2ecf0b5b85027 Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 23:08:51 -0700 Subject: [PATCH 57/61] Add CHANGELOG.md for 4.1.0 (last release) This was missing and sometimes people complain about this ;) --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f4563a4..f41da62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 4.1.0 - 2020-10-21 +### Changed + +* Require `slog>=2.4` +* Require `log>=0.4.11 + +## Fixed + +* Remove unused dependency `crossbeam = 0.7.1` + ## 4.0.0 - 2018-08-13 ### Changed From c6eba10a72443d7bf0f4024fa2a2db75cd63fbdd Mon Sep 17 00:00:00 2001 From: Techcable Date: Tue, 22 Mar 2022 23:15:44 -0700 Subject: [PATCH 58/61] Bump version to 4.1.1 Most important changes are fixing `log>=0.4.15`. Adding the new feature (support for `log/unstable_kv`) could arguably require bumping the minor version (-> 4.2.0) However, since it's an unstable feature so I don't consider that necessary. --- CHANGELOG.md | 18 ++++++++++++++++++ Cargo.toml | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f41da62..2976911 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 4.1.1 - 2022-03-22 +### Added + +* Support `feature="log/kv-unstable"` (PR #18) + * Requires `slog/dynamic-keys` + * This is unstable (obviously), so I don't consider it + a change that warants a minor-version bump + +### Changed + +* Switch to github actions (PR #20) + +### Fixed + +* Avoid using log's private API to construct records (PR #21) + * Fixes recent versions of `log` crate (`>=0.4.15`), resolving slog-rs/slog#309 +* Fix formatting & clippy lints (part of switch to GH actions) + ## 4.1.0 - 2020-10-21 ### Changed diff --git a/Cargo.toml b/Cargo.toml index 9b5b576..4fa8a58 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "slog-stdlog" -version = "4.1.0" +version = "4.1.1" authors = ["Dawid Ciężarkiewicz "] description = "`log` crate adapter for slog-rs" keywords = ["slog", "logging", "json", "log"] From 07aa6dcfef120537b46313e077cc65749b8c593f Mon Sep 17 00:00:00 2001 From: Thayne McCombs Date: Thu, 5 Jan 2023 09:40:19 -0700 Subject: [PATCH 59/61] Reduce allocations for kv from log to slog (#25) See: https://github.com/rust-lang/log/issues/328 --- kv.rs | 79 ++++++++++++++++++++++++++++++++++++++++++++++------------ lib.rs | 8 +++--- 2 files changed, 67 insertions(+), 20 deletions(-) diff --git a/kv.rs b/kv.rs index 2172843..9854a9e 100644 --- a/kv.rs +++ b/kv.rs @@ -1,35 +1,82 @@ +use log::kv::value::Error as ValueError; use slog::{Record, Serializer}; -pub(crate) struct Visitor { - kvs: Vec<(String, String)>, +struct Visitor<'s> { + serializer: &'s mut dyn Serializer, } -impl Visitor { - pub fn new() -> Self { - Self { kvs: vec![] } +impl<'s> Visitor<'s> { + pub fn new(serializer: &'s mut dyn Serializer) -> Self { + Self { serializer } } } -impl<'kvs, 'a> log::kv::Visitor<'kvs> for Visitor { +pub(crate) struct SourceKV<'kvs>(pub &'kvs dyn log::kv::source::Source); + +struct KeyVisit<'s> { + serializer: &'s mut dyn Serializer, + key: &'s str, +} + +impl<'kvs> log::kv::Visitor<'kvs> for Visitor<'kvs> { fn visit_pair( &mut self, key: log::kv::Key<'kvs>, val: log::kv::Value<'kvs>, ) -> Result<(), log::kv::Error> { - let key = key.to_string(); - if let Some(val) = val.to_borrowed_str() { - let val = val.to_string(); - self.kvs.push((key, val)); + val.visit(KeyVisit { + serializer: self.serializer, + key: key.as_str(), + }) + } +} + +macro_rules! visit_to_emit { + ($t:ty : $vname:ident -> $ename:ident) => { + fn $vname(&mut self, value: $t) -> Result<(), ValueError> { + self.serializer + .$ename(self.key.to_string().into(), value) + .map_err(to_value_err) } - Ok(()) + }; +} + +impl<'s> log::kv::value::Visit<'s> for KeyVisit<'s> { + fn visit_any(&mut self, value: log::kv::Value<'_>) -> Result<(), ValueError> { + let key = self.key.to_string().into(); + self.serializer + .emit_arguments(key, &format_args!("{}", value)) + .map_err(to_value_err) } + + visit_to_emit!(u64: visit_u64 -> emit_u64); + visit_to_emit!(i64: visit_i64 -> emit_i64); + visit_to_emit!(u128: visit_u128 -> emit_u128); + visit_to_emit!(i128: visit_i128 -> emit_i128); + visit_to_emit!(f64: visit_f64 -> emit_f64); + visit_to_emit!(bool: visit_bool -> emit_bool); + visit_to_emit!(&str: visit_str -> emit_str); + visit_to_emit!(char: visit_char -> emit_char); + visit_to_emit!(&(dyn std::error::Error + 'static): visit_error -> emit_error); } -impl slog::KV for Visitor { +impl slog::KV for SourceKV<'_> { fn serialize(&self, _record: &Record, serializer: &mut dyn Serializer) -> slog::Result { - for (key, val) in &self.kvs { - serializer.emit_str(key.to_owned().into(), val.as_str())?; - } - Ok(()) + // Unfortunately, there isn't a way for use to pass the original error through. + self.0 + .visit(&mut Visitor::new(serializer)) + .map_err(|_| slog::Error::Other) } } + +fn to_value_err(err: slog::Error) -> ValueError { + use slog::Error::*; + + match err { + Io(e) => e.into(), + Fmt(e) => e.into(), + Other => ValueError::boxed(err), + } +} + +// TODO: support going the other way diff --git a/lib.rs b/lib.rs index 4b9f8e9..0404371 100644 --- a/lib.rs +++ b/lib.rs @@ -100,10 +100,10 @@ impl log::Log for Logger { }; #[cfg(feature = "kv_unstable")] { - let key_values = r.key_values(); - let mut visitor = kv::Visitor::new(); - key_values.visit(&mut visitor).unwrap(); - slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!(visitor)))) + let key_values = kv::SourceKV(r.key_values()); + slog_scope::with_logger(|logger| { + logger.log(&slog::Record::new(&s, args, b!(key_values))) + }) } #[cfg(not(feature = "kv_unstable"))] slog_scope::with_logger(|logger| logger.log(&slog::Record::new(&s, args, b!()))) From 4a2f3be250ce3ad40757db1063449a7f4b8db53c Mon Sep 17 00:00:00 2001 From: Techcable Date: Thu, 5 Jan 2023 12:12:40 -0700 Subject: [PATCH 60/61] Add integration test for wrapping slog -> log TODO: Add log -> slog test --- Cargo.toml | 3 ++ tests/log2slog.rs.disabled | 61 +++++++++++++++++++++++++ tests/slog2log.rs | 91 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 155 insertions(+) create mode 100644 tests/log2slog.rs.disabled create mode 100644 tests/slog2log.rs diff --git a/Cargo.toml b/Cargo.toml index 4fa8a58..783438b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,3 +42,6 @@ log = { version = "0.4.11", features = ["std"] } [dev-dependencies] slog-term = "2" slog-async = "2" +# Used for tests +fragile = "2" + diff --git a/tests/log2slog.rs.disabled b/tests/log2slog.rs.disabled new file mode 100644 index 0000000..8cf5044 --- /dev/null +++ b/tests/log2slog.rs.disabled @@ -0,0 +1,61 @@ +use std::sync::atomic::{AtomicBool, Ordering}; +use std::fmt; +use std::collections::HashMap; + +struct ExpectedValue { + value: String, + seen: AtomicBool, +} +struct SlogExpectSerialize { + expected: HashMap, +} +impl slog::Serializer for SlogExpectSerialize { + fn emit_arguments(&mut self, key: slog::Key, val: &fmt::Arguments) -> slog::Result { + if let Some(expected_value) = self.expected.get(&key) { + let was_seen = expected_value.seen.compare_exchange( + false, true, + Ordering::SeqCst, Ordering::SeqCst + ).unwrap_or_else(std::convert::identity); + assert!(!was_seen, "Already saw {key:?}"); + assert_eq!(expected_value.value, fmt::format(*val)); + Ok(()) + } else { + panic!("Got unexpected key {key:?} = {val}"); + } + } +} +impl SlogExpectSerialize { + fn check_finished(&self) { + for (key, value) in self.expected { + if !value.seen.load(Ordering::SeqCst) { + panic!("Did not see value for key = {key:?}") + } + } + } +} +impl fmt::Debug for SlogExpectSerialize { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_map().entries(self.expected.iter().map(|(ref key, ref value)| { + let key: &str = key.as_ref(); + (key, &*value.value) + })).finish() + } +} + +struct SlogAssertExpected { + _fo: std::convert::Infallible, +} +impl slog::Drain for SlogAssertExpected { + type Ok = (); + type Err = slog::Error; + fn log(&self, record: &slog::Record<'_>, values: &slog::OwnedKVList) -> Result<(), slog::Error> { + todo!() + } +} +impl SlogAssertExpected { + fn assert_finished(&self) { + todo!() + } +} + +compile_error!("Not Yet Implemented"); diff --git a/tests/slog2log.rs b/tests/slog2log.rs new file mode 100644 index 0000000..5d16a5e --- /dev/null +++ b/tests/slog2log.rs @@ -0,0 +1,91 @@ +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use slog::Drain; +use log::RecordBuilder; +use fragile::Fragile; + +struct StdLogAssertExpected<'a> { + expected: Mutex>>>, + current_index: AtomicUsize, +} +impl log::Log for StdLogAssertExpected<'_> { + fn enabled(&self, _: &log::Metadata) -> bool { + true + } + fn log(&self, actual: &log::Record<'_>) { + let expected = { + let expected = self.expected.lock().unwrap(); + // NOTE: I think load fence is implied by the lock + let old_index = self.current_index.load(Ordering::Relaxed); + match expected.get(old_index) { + Some(e) => { + assert_eq!( + old_index, + // Do we need a store fence, or is that implied as well? + self.current_index.fetch_add(1, Ordering::Acquire) + ); + e.get().clone() + }, + None => panic!("Expected no more log records. but got {:?}", actual) + } + }; + assert_eq!(expected.metadata(), actual.metadata()); + assert_eq!(expected.args().to_string(), actual.args().to_string()); + assert_eq!(expected.level(), actual.level()); + assert_eq!(expected.target(), actual.target()); + assert_eq!(expected.module_path(), actual.module_path()); + assert_eq!(expected.file(), actual.file()); + // NOTE: Intentionally ignored `line` + if cfg!(feature = "kv_unstable") { + todo!("Structure not currently used. See PR #26"); + } + } + fn flush(&self) {} +} +impl StdLogAssertExpected<'_> { + fn assert_finished(&self) { + let expected = self.expected.lock().unwrap(); + // load fence implied (I think) + let remaining = expected.len() - self.current_index.load(Ordering::Relaxed); + assert!( + remaining == 0, + "Expected {remaining} more values (first={first:?}) {maybeLast}", + first = expected.first().unwrap(), + maybeLast = if remaining >= 2 { + format!("(last={:?})", expected.last().unwrap()) + } else { + String::new() + } + ); + } +} + +macro_rules! record { + ($level:ident, $fmt:expr) => { + RecordBuilder::new() + .args(format_args!($fmt)) + .level(log::Level::$level) + .file(Some(file!())) + .module_path(Some(module_path!())) + .target(module_path!()) + .build() + } +} + +#[test] +fn test_slog2log() { + let expected = vec![ + record!(Info, "Hello World!"), + record!(Debug, "Hello World, I am 100 years old") + ].into_iter().map(Fragile::new).collect::>>(); + let std_logger = Box::leak(Box::new(StdLogAssertExpected { + expected: Mutex::new(expected), + current_index: 0.into(), + })); + log::set_logger(std_logger).unwrap(); + let sl = slog::Logger::root(slog_stdlog::StdLog.fuse(), slog::o!()); + slog::info!(sl, "Hello {}", "World!"); + slog::debug!(sl, "Hello {}, I am {} years old", "World", 100); + std_logger.assert_finished(); +} From 252b6bb6435a8a3ba44748b2e1626aa676508097 Mon Sep 17 00:00:00 2001 From: Techcable Date: Thu, 5 Jan 2023 12:23:16 -0700 Subject: [PATCH 61/61] Disable slog2log test when kv-unstable is enabled This is why you don't commit directly to master... Also: rustfmt code. --- tests/slog2log.rs | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/tests/slog2log.rs b/tests/slog2log.rs index 5d16a5e..722a977 100644 --- a/tests/slog2log.rs +++ b/tests/slog2log.rs @@ -1,9 +1,9 @@ -use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; -use slog::Drain; -use log::RecordBuilder; use fragile::Fragile; +use log::RecordBuilder; +use slog::Drain; struct StdLogAssertExpected<'a> { expected: Mutex>>>, @@ -26,8 +26,8 @@ impl log::Log for StdLogAssertExpected<'_> { self.current_index.fetch_add(1, Ordering::Acquire) ); e.get().clone() - }, - None => panic!("Expected no more log records. but got {:?}", actual) + } + None => panic!("Expected no more log records. but got {:?}", actual), } }; assert_eq!(expected.metadata(), actual.metadata()); @@ -70,15 +70,22 @@ macro_rules! record { .module_path(Some(module_path!())) .target(module_path!()) .build() - } + }; } #[test] +#[cfg_attr( + feature = "kv_unstable", + ignore = "TODO: Support kv-unstable feature (See PR #26)" +)] fn test_slog2log() { let expected = vec![ record!(Info, "Hello World!"), - record!(Debug, "Hello World, I am 100 years old") - ].into_iter().map(Fragile::new).collect::>>(); + record!(Debug, "Hello World, I am 100 years old"), + ] + .into_iter() + .map(Fragile::new) + .collect::>>(); let std_logger = Box::leak(Box::new(StdLogAssertExpected { expected: Mutex::new(expected), current_index: 0.into(),