From cf7d07a7f036bd6a82fe816c904e051cd7d6f438 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Teo=20Klestrup=20R=C3=B6ijezon?= Date: Thu, 12 Mar 2020 18:10:54 +0100 Subject: [PATCH 1/2] Expose a way to serialize a KV to any Serde Serializer This is useful if you need to serialize to a more structured form, such as sending full JSON blobs to a HTTP endpoint. --- lib.rs | 45 +++++++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/lib.rs b/lib.rs index 233b4b7..a22eff6 100644 --- a/lib.rs +++ b/lib.rs @@ -47,7 +47,7 @@ thread_local! { /// /// Newtype to wrap serde Serializer, so that `Serialize` can be implemented /// for it -struct SerdeSerializer { +pub struct SerdeSerializer { /// Current state of map serializing: `serde::Serializer::MapState` ser_map: S::SerializeMap, } @@ -67,6 +67,25 @@ impl SerdeSerializer { fn end(self) -> result::Result { self.ser_map.end() } + + /// Serialize a map of values using a Serde `Serializer` + pub fn serialize<'a, VIter>( + serializer: S, + rinfo: &Record, + logger_values: VIter, + ) -> result::Result + where + S::Error: Send + Sync + 'static, + VIter: IntoIterator, + { + let mut serializer = try!(Self::start(serializer, None)); + for kv in logger_values { + try!(kv.serialize(rinfo, &mut serializer)); + } + serializer.end().map_err(|e| { + slog::Error::Io(io::Error::new(io::ErrorKind::Other, e)) + }) + } } macro_rules! impl_m( @@ -197,21 +216,15 @@ impl Json where F: serde_json::ser::Formatter, { - let mut serializer = - try!(SerdeSerializer::start(&mut *serializer, None)); - - for kv in &self.values { - try!(kv.serialize(rinfo, &mut serializer)); - } - - try!(logger_values.serialize(rinfo, &mut serializer)); - - try!(rinfo.kv().serialize(rinfo, &mut serializer)); - - let res = serializer.end(); - - try!(res.map_err(|e| io::Error::new(io::ErrorKind::Other, e))); - + try!(SerdeSerializer::serialize( + &mut *serializer, + rinfo, + self.values + .iter() + .map(|kv| kv as &dyn KV) + .chain(std::iter::once(logger_values as &dyn KV)) + .chain(std::iter::once(&rinfo.kv() as &dyn KV)) + )); Ok(()) } } From e0a0f69206027e6493f77056bf2ea517dfb43b15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Teo=20Klestrup=20R=C3=B6ijezon?= Date: Thu, 12 Mar 2020 18:23:09 +0100 Subject: [PATCH 2/2] Upgrade to Rust 2018 and cargofmt --- Cargo.toml | 1 + examples/pretty.rs | 1 - lib.rs | 111 ++++++++++++++++++++++++--------------------- 3 files changed, 61 insertions(+), 52 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1a5f977..84e352c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ documentation = "https://docs.rs/slog-json" homepage = "https://github.com/slog-rs/slog" repository = "https://github.com/slog-rs/json" readme = "README.md" +edition = "2018" [lib] path = "lib.rs" diff --git a/examples/pretty.rs b/examples/pretty.rs index 9e18288..cb88474 100644 --- a/examples/pretty.rs +++ b/examples/pretty.rs @@ -5,7 +5,6 @@ extern crate slog_json; use slog::Drain; - fn main() { let drain = slog_json::Json::new(std::io::stdout()) .set_pretty(true) diff --git a/lib.rs b/lib.rs index a22eff6..76ebf2a 100644 --- a/lib.rs +++ b/lib.rs @@ -20,6 +20,7 @@ // {{{ Imports & meta #![warn(missing_docs)] +#![allow(clippy::needless_doctest_main)] #[macro_use] extern crate slog; extern crate chrono; @@ -27,11 +28,11 @@ extern crate serde; extern crate serde_json; use serde::ser::SerializeMap; -use slog::{FnValue, PushFnValue}; -use slog::{OwnedKVList, KV, SendSyncRefUnwindSafeKV}; -use slog::Record; -use std::{io, result, fmt}; use slog::Key; +use slog::Record; +use slog::{FnValue, PushFnValue}; +use slog::{OwnedKVList, SendSyncRefUnwindSafeKV, KV}; +use std::{fmt, io, result}; use std::cell::RefCell; use std::fmt::Write; @@ -55,12 +56,13 @@ pub struct SerdeSerializer { impl SerdeSerializer { /// Start serializing map of values fn start(ser: S, len: Option) -> result::Result { - let ser_map = try!(ser.serialize_map(len) - .map_err(|e| { - io::Error::new(io::ErrorKind::Other, - format!("serde serialization error: {}", e)) - })); - Ok(SerdeSerializer { ser_map: ser_map }) + let ser_map = ser.serialize_map(len).map_err(|e| { + io::Error::new( + io::ErrorKind::Other, + format!("serde serialization error: {}", e), + ) + })?; + Ok(SerdeSerializer { ser_map }) } /// Finish serialization, and return the serializer @@ -78,9 +80,9 @@ impl SerdeSerializer { S::Error: Send + Sync + 'static, VIter: IntoIterator, { - let mut serializer = try!(Self::start(serializer, None)); + let mut serializer = Self::start(serializer, None)?; for kv in logger_values { - try!(kv.serialize(rinfo, &mut serializer)); + kv.serialize(rinfo, &mut serializer)?; } serializer.end().map_err(|e| { slog::Error::Io(io::Error::new(io::ErrorKind::Other, e)) @@ -91,14 +93,15 @@ impl SerdeSerializer { macro_rules! impl_m( ($s:expr, $key:expr, $val:expr) => ({ let k_s: &str = $key.as_ref(); - try!($s.ser_map.serialize_entry(k_s, $val) - .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("serde serialization error: {}", e)))); + $s.ser_map.serialize_entry(k_s, $val) + .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("serde serialization error: {}", e)))?; Ok(()) }); ); impl slog::Serializer for SerdeSerializer - where S: serde::Serializer +where + S: serde::Serializer, { fn emit_bool(&mut self, key: Key, val: bool) -> slog::Result { impl_m!(self, key, &val) @@ -155,26 +158,28 @@ impl slog::Serializer for SerdeSerializer fn emit_str(&mut self, key: Key, val: &str) -> slog::Result { impl_m!(self, key, &val) } - fn emit_arguments(&mut self, - key: Key, - val: &fmt::Arguments) - -> slog::Result { - + fn emit_arguments( + &mut self, + key: Key, + val: &fmt::Arguments, + ) -> slog::Result { TL_BUF.with(|buf| { let mut buf = buf.borrow_mut(); buf.write_fmt(*val).unwrap(); - let res = { - || impl_m!(self, key, &*buf) - }(); + let res = { || impl_m!(self, key, &*buf) }(); buf.clear(); res }) } #[cfg(feature = "nested-values")] - fn emit_serde(&mut self, key: Key, value: &slog::SerdeValue) -> slog::Result { + fn emit_serde( + &mut self, + key: Key, + value: &slog::SerdeValue, + ) -> slog::Result { impl_m!(self, key, value.as_serde()) } } @@ -194,7 +199,8 @@ pub struct Json { } impl Json - where W: io::Write +where + W: io::Write, { /// New `Json` `Drain` with default key-value pairs added pub fn default(io: W) -> Json { @@ -202,7 +208,7 @@ impl Json } /// Build custom `Json` `Drain` - #[cfg_attr(feature = "cargo-clippy", allow(new_ret_no_self))] + #[allow(clippy::new_ret_no_self)] pub fn new(io: W) -> JsonBuilder { JsonBuilder::new(io) } @@ -216,41 +222,42 @@ impl Json where F: serde_json::ser::Formatter, { - try!(SerdeSerializer::serialize( + SerdeSerializer::serialize( &mut *serializer, rinfo, self.values .iter() .map(|kv| kv as &dyn KV) .chain(std::iter::once(logger_values as &dyn KV)) - .chain(std::iter::once(&rinfo.kv() as &dyn KV)) - )); + .chain(std::iter::once(&rinfo.kv() as &dyn KV)), + )?; Ok(()) } } impl slog::Drain for Json - where W: io::Write +where + W: io::Write, { type Ok = (); type Err = io::Error; - fn log(&self, - rinfo: &Record, - logger_values: &OwnedKVList) - -> io::Result<()> { - + fn log( + &self, + rinfo: &Record, + logger_values: &OwnedKVList, + ) -> io::Result<()> { let mut io = self.io.borrow_mut(); let io = if self.pretty { let mut serializer = serde_json::Serializer::pretty(&mut *io); - try!(self.log_impl(&mut serializer, &rinfo, &logger_values)); + self.log_impl(&mut serializer, &rinfo, &logger_values)?; serializer.into_inner() } else { let mut serializer = serde_json::Serializer::new(&mut *io); - try!(self.log_impl(&mut serializer, &rinfo, &logger_values)); + self.log_impl(&mut serializer, &rinfo, &logger_values)?; serializer.into_inner() }; if self.newlines { - try!(io.write_all("\n".as_bytes())); + io.write_all(b"\n")?; } if self.flush { io.flush()?; @@ -274,14 +281,15 @@ pub struct JsonBuilder { } impl JsonBuilder - where W: io::Write +where + W: io::Write, { fn new(io: W) -> Self { JsonBuilder { newlines: true, flush: false, values: vec![], - io: io, + io, pretty: false, } } @@ -319,7 +327,8 @@ impl JsonBuilder /// Add custom values to be printed with this formatter pub fn add_key_value(mut self, value: slog::OwnedKV) -> Self - where T: SendSyncRefUnwindSafeKV + 'static + where + T: SendSyncRefUnwindSafeKV + 'static, { self.values.push(value.into()); self @@ -332,16 +341,16 @@ impl JsonBuilder /// * `msg` - msg - formatted logging message pub fn add_default_keys(self) -> Self { self.add_key_value(o!( - "ts" => PushFnValue(move |_ : &Record, ser| { - ser.emit(chrono::Local::now().to_rfc3339()) - }), - "level" => FnValue(move |rinfo : &Record| { - rinfo.level().as_short_str() - }), - "msg" => PushFnValue(move |record : &Record, ser| { - ser.emit(record.msg()) - }), - )) + "ts" => PushFnValue(move |_ : &Record, ser| { + ser.emit(chrono::Local::now().to_rfc3339()) + }), + "level" => FnValue(move |rinfo : &Record| { + rinfo.level().as_short_str() + }), + "msg" => PushFnValue(move |record : &Record, ser| { + ser.emit(record.msg()) + }), + )) } } // }}}