Mercurial > hg
changeset 40288:87c76e5f3427
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
author | Yuya Nishihara <yuya@tcha.org> |
---|---|
date | Sun, 07 Oct 2018 11:32:42 +0900 |
parents | 7623199def92 |
children | 7d3285f799cc |
files | rust/chg/src/main.rs |
diffstat | 1 files changed, 39 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- 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