Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created April 11, 2020 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/059abbf57b2e8af4ae6e4c74d2676c4f to your computer and use it in GitHub Desktop.
Save rust-play/059abbf57b2e8af4ae6e4c74d2676c4f to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
/*
[dependencies]
serde = { version = "1.*", features = ["derive"] }
serde_json = "1.*"
slog-json = "2.*"
slog = { version = "2.*", features = ["nested-values"] }
erased-serde = "0.3.*"
sloggers = "0.3.*"
*/
use std::sync;
use serde_json;
use serde::{Deserialize, Serialize};
use sloggers;
use slog;
use slog_json;
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Test {
x : f64,
y : f64
}
impl slog::KV for Test {
fn serialize(&self,
_record: &slog::Record,
serializer: &mut dyn slog::Serializer
) -> slog::Result {
serializer.emit_serde("test", self)
}
}
impl slog::Value for Test {
fn serialize(&self,
_record: &slog::Record,
key: slog::Key,
serializer: &mut dyn slog::Serializer
) -> slog::Result {
serializer.emit_serde(key, self)
}
}
impl slog::SerdeValue for Test {
fn as_serde(&self) -> &dyn erased_serde::Serialize {
self
}
fn to_sendable(&self) -> Box<dyn slog::SerdeValue + Send + 'static> {
Box::new(self.clone())
}
}
fn main() {
use sloggers::Build;
let t = Test { x: 1.0, y: -1.0 };
println!("{}", serde_json::to_string(&t).unwrap());
let logjson = {
let json = sync::Mutex::new (
slog_json::Json::new (std::io::stdout()).build()
);
slog::Logger::root (slog::Fuse(json), slog::o!())
};
let logterm = {
sloggers::terminal::TerminalLoggerBuilder::new()
.destination(sloggers::terminal::Destination::Stdout)
.build().unwrap()
};
slog::info!(logterm, ""; "hello" => "world");
slog::info!(logterm, ""; t.clone());
slog::info!(logterm, ""; "test" => t.clone());
// --> thread 'main' panicked at '`ToSendSerializer` can't fail: Other'
slog::info!(logjson, ""; "hello" => "world");
slog::info!(logjson, ""; t.clone());
slog::info!(logjson, ""; "test" => t.clone());
// --> thread 'main' panicked at 'slog::Fuse Drain: Custom { kind: Other, error: "other error" }'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment