# HG changeset patch # User Yuya Nishihara # Date 1538879562 -32400 # Node ID 87c76e5f3427e9c4e00d8e04803f110b6e584d41 # Parent 7623199def92d0ac7d5174ab93a62d5eb039587f rust-chg: install logger if $CHGDEBUG is set This is modeled after the example logger and debugmsg() of chg/util.c. https://docs.rs/log/0.4.5/log/#implementing-a-logger diff -r 7623199def92 -r 87c76e5f3427 rust/chg/src/main.rs --- a/rust/chg/src/main.rs Sat Oct 06 20:07:11 2018 +0900 +++ b/rust/chg/src/main.rs Sun Oct 07 11:32:42 2018 +0900 @@ -5,6 +5,7 @@ extern crate chg; extern crate futures; +extern crate log; extern crate tokio; extern crate tokio_hglib; @@ -15,10 +16,48 @@ use std::env; use std::io; use std::process; +use std::time::Instant; use tokio::prelude::*; use tokio_hglib::UnixClient; +struct DebugLogger { + start: Instant, +} + +impl DebugLogger { + pub fn new() -> DebugLogger { + DebugLogger { + start: Instant::now(), + } + } +} + +impl log::Log for DebugLogger { + fn enabled(&self, metadata: &log::Metadata) -> bool { + metadata.target().starts_with("chg::") + } + + fn log(&self, record: &log::Record) { + if self.enabled(record.metadata()) { + // just make the output looks similar to chg of C + let l = format!("{}", record.level()).to_lowercase(); + let t = self.start.elapsed(); + writeln!(io::stderr(), "chg: {}: {}.{:06} {}", + l, t.as_secs(), t.subsec_micros(), record.args()).unwrap_or(()); + } + } + + fn flush(&self) { + } +} + fn main() { + if env::var_os("CHGDEBUG").is_some() { + log::set_boxed_logger(Box::new(DebugLogger::new())) + .expect("any logger should not be installed yet"); + log::set_max_level(log::LevelFilter::Debug); + } + let code = run().unwrap_or_else(|err| { writeln!(io::stderr(), "chg: abort: {}", err).unwrap_or(()); 255