Browse Source

Just straight-up roll our own logger

This gets rid of a few dependencies (including another terminal colour crate). It also simplifies the main run function a little bit.
Benjamin Sago 4 years ago
parent
commit
54ed1bede0
4 changed files with 102 additions and 117 deletions
  1. 0 46
      Cargo.lock
  2. 0 5
      Cargo.toml
  3. 66 0
      src/logger.rs
  4. 36 66
      src/main.rs

+ 0 - 46
Cargo.lock

@@ -146,7 +146,6 @@ dependencies = [
  "datetime 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "dns 0.1.0",
  "dns-transport 0.1.0",
- "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "getopts 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)",
  "log 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)",
  "pretty_assertions 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -156,17 +155,6 @@ dependencies = [
  "serde_json 1.0.58 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
-[[package]]
-name = "env_logger"
-version = "0.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-dependencies = [
- "atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)",
- "humantime 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "log 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)",
- "termcolor 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
-]
-
 [[package]]
 name = "fnv"
 version = "1.0.7"
@@ -311,14 +299,6 @@ name = "httpdate"
 version = "0.3.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
-[[package]]
-name = "humantime"
-version = "1.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-dependencies = [
- "quick-error 1.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
-]
-
 [[package]]
 name = "hyper"
 version = "0.13.8"
@@ -559,11 +539,6 @@ dependencies = [
  "unicode-xid 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
-[[package]]
-name = "quick-error"
-version = "1.2.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-
 [[package]]
 name = "quote"
 version = "1.0.7"
@@ -724,14 +699,6 @@ dependencies = [
  "winapi 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
-[[package]]
-name = "termcolor"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-dependencies = [
- "winapi-util 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
-]
-
 [[package]]
 name = "tokio"
 version = "0.2.22"
@@ -852,14 +819,6 @@ name = "winapi-i686-pc-windows-gnu"
 version = "0.4.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
-[[package]]
-name = "winapi-util"
-version = "0.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-dependencies = [
- "winapi 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
-]
-
 [[package]]
 name = "winapi-x86_64-pc-windows-gnu"
 version = "0.4.0"
@@ -891,7 +850,6 @@ dependencies = [
 "checksum datetime 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d0fcb4df22ae812fa2f6d5e3b577247584cc67fce06ad0779168d1dd41cbcce3"
 "checksum derive_more 0.99.11 (registry+https://github.com/rust-lang/crates.io-index)" = "41cb0e6161ad61ed084a36ba71fbba9e3ac5aee3606fb607fe08da6acbcf3d8c"
 "checksum difference 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198"
-"checksum env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36"
 "checksum fnv 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
 "checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
 "checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
@@ -911,7 +869,6 @@ dependencies = [
 "checksum http-body 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "13d5ff830006f7646652e057693569bfe0d51760c0085a071769d142a205111b"
 "checksum httparse 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9"
 "checksum httpdate 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "494b4d60369511e7dea41cf646832512a94e542f68bb9c49e54518e0f468eb47"
-"checksum humantime 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f"
 "checksum hyper 0.13.8 (registry+https://github.com/rust-lang/crates.io-index)" = "2f3afcfae8af5ad0576a31e768415edb627824129e8e5a29b8bfccb2f234e835"
 "checksum hyper-tls 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d979acc56dcb5b8dddba3917601745e877576475aa046df3226eabdecef78eed"
 "checksum indexmap 1.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "55e2e4c765aa53a0424761bf9f41aa7a6ac1efa87238f59560640e27fca028f2"
@@ -938,7 +895,6 @@ dependencies = [
 "checksum ppv-lite86 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "c36fa947111f5c62a733b652544dd0016a43ce89619538a8ef92724a6f501a20"
 "checksum pretty_assertions 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3f81e1644e1b54f5a68959a29aa86cde704219254669da328ecfdf6a1f09d427"
 "checksum proc-macro2 1.0.24 (registry+https://github.com/rust-lang/crates.io-index)" = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
-"checksum quick-error 1.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
 "checksum quote 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
 "checksum rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"
 "checksum rand_chacha 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"
@@ -958,7 +914,6 @@ dependencies = [
 "checksum socket2 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)" = "b1fa70dc5c8104ec096f4fe7ede7a221d35ae13dcd19ba1ad9a81d2cab9a1c44"
 "checksum syn 1.0.42 (registry+https://github.com/rust-lang/crates.io-index)" = "9c51d92969d209b54a98397e1b91c8ae82d8c87a7bb87df0b29aa2ad81454228"
 "checksum tempfile 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9"
-"checksum termcolor 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f"
 "checksum tokio 0.2.22 (registry+https://github.com/rust-lang/crates.io-index)" = "5d34ca54d84bf2b5b4d7d31e901a8464f7b60ac145a284fba25ceb801f2ddccd"
 "checksum tokio-tls 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9a70f4fcd7b3b24fb194f837560168208f669ca8cb70d0c4b862944452396343"
 "checksum tokio-util 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "be8242891f2b6cbef26a2d7e8605133c2c554cd35b3e4948ea892d6d68436499"
@@ -975,6 +930,5 @@ dependencies = [
 "checksum winapi 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
 "checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"
 "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
-"checksum winapi-util 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
 "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
 "checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e"

+ 0 - 5
Cargo.toml

@@ -44,11 +44,6 @@ serde_json = "1.0"
 # logging
 log = "0.4"
 
-[dependencies.env_logger]
-version = "0.7"
-default_features = false
-features = [ "termcolor", "atty", "humantime" ]
-
 [build-dependencies]
 datetime = { version = "0.5.1", default_features = false }
 regex = { version = "1.3", default_features = false, features = ["std"] }

+ 66 - 0
src/logger.rs

@@ -0,0 +1,66 @@
+//! Debug error logging.
+
+use std::ffi::OsStr;
+
+use ansi_term::{Colour, ANSIString};
+
+
+/// Sets the internal logger, changing the log level based on the value of an
+/// environment variable.
+pub fn configure<T: AsRef<OsStr>>(ev: Option<T>) {
+    let ev = match ev {
+        Some(v)  => v,
+        None     => return,
+    };
+
+    let env_var = ev.as_ref();
+    if env_var.is_empty() {
+        return;
+    }
+
+    if env_var == "trace" {
+        log::set_max_level(log::LevelFilter::Trace);
+    }
+    else {
+        log::set_max_level(log::LevelFilter::Debug);
+    }
+
+    let result = log::set_logger(GLOBAL_LOGGER);
+    if let Err(e) = result {
+        eprintln!("Failed to initialise logger: {}", e);
+    }
+}
+
+
+#[derive(Debug)]
+struct Logger;
+
+const GLOBAL_LOGGER: &Logger = &Logger;
+
+impl log::Log for Logger {
+    fn enabled(&self, _: &log::Metadata<'_>) -> bool {
+        true  // no need to filter after using ‘set_max_level’.
+    }
+
+    fn log(&self, record: &log::Record<'_>) {
+        let open = Colour::Fixed(243).paint("[");
+        let level = level(record.level());
+        let close = Colour::Fixed(243).paint("]");
+
+        eprintln!("{}{} {}{} {}", open, level, record.target(), close, record.args());
+    }
+
+    fn flush(&self) {
+        // no need to flush with ‘eprintln!’.
+    }
+}
+
+fn level(level: log::Level) -> ANSIString<'static> {
+    match level {
+        log::Level::Error => Colour::Red.paint("ERROR"),
+        log::Level::Warn  => Colour::Yellow.paint("WARN"),
+        log::Level::Info  => Colour::Cyan.paint("INFO"),
+        log::Level::Debug => Colour::Blue.paint("DEBUG"),
+        log::Level::Trace => Colour::Fixed(245).paint("TRACE"),
+    }
+}

+ 36 - 66
src/main.rs

@@ -20,15 +20,11 @@
 
 #![deny(unsafe_code)]
 
-
-use std::env;
-use std::process::exit;
-use std::time::Instant;
-
 use log::*;
 
 mod colours;
 mod connect;
+mod logger;
 mod output;
 mod requests;
 mod resolve;
@@ -42,13 +38,15 @@ use self::options::*;
 /// Configures logging, parses the command-line options, and handles any
 /// errors before passing control over to the Dog type.
 fn main() {
-    configure_logger();
+    use std::env;
+    use std::process::exit;
+
+    logger::configure(env::var_os("DOG_DEBUG"));
 
     match Options::getopts(env::args_os().skip(1)) {
         OptionsResult::Ok(options) => {
             info!("Running with options -> {:#?}", options);
-            let dog = Dog::init(options);
-            exit(dog.run());
+            exit(run(options));
         }
 
         OptionsResult::Help(help_reason, use_colours) => {
@@ -91,76 +89,48 @@ fn main() {
 }
 
 
-/// Checks the `DOG_DEBUG` environment variable, enabling debug logging if
-/// it’s non-empty.
-fn configure_logger() {
-    let present = match env::var_os("DOG_DEBUG") {
-        Some(debug)  => debug.len() > 0,
-        None         => false,
-    };
-
-    let mut logs = env_logger::Builder::new();
-    if present {
-        let _ = logs.filter(None, log::LevelFilter::Debug);
-    }
-    else {
-        let _ = logs.filter(None, log::LevelFilter::Off);
-    }
-
-    logs.init()
-}
-
-struct Dog {
-    options: Options,
-}
+fn run(Options { requests, format, measure_time }: Options) -> i32 {
+    use std::time::Instant;
 
-impl Dog {
-    fn init(options: Options) -> Self {
-        Self { options }
-    }
+    let mut runtime = dns_transport::Runtime::new().expect("Failed to create runtime");
+    let should_show_opt = requests.edns.should_show();
 
-    fn run(self) -> i32 {
-        let Options { requests, format, measure_time } = self.options;
-        let mut runtime = dns_transport::Runtime::new().expect("Failed to create runtime");
-        let should_show_opt = requests.edns.should_show();
+    let mut responses = Vec::new();
+    let timer = if measure_time { Some(Instant::now()) } else { None };
 
-        let mut responses = Vec::new();
-        let timer = if measure_time { Some(Instant::now()) } else { None };
+    let mut errored = false;
+    for (request, transport) in requests.generate() {
+        let result = runtime.block_on(async { transport.send(&request).await });
 
-        let mut errored = false;
-        for (request, transport) in requests.generate() {
-            let result = runtime.block_on(async { transport.send(&request).await });
-
-            match result {
-                Ok(mut response) => {
-                    if ! should_show_opt {
-                        response.answers.retain(dns::Answer::is_standard);
-                        response.authorities.retain(dns::Answer::is_standard);
-                        response.additionals.retain(dns::Answer::is_standard);
-                    }
-
-                    responses.push(response);
-                }
-                Err(e) => {
-                    format.print_error(e);
-                    errored = true;
+        match result {
+            Ok(mut response) => {
+                if ! should_show_opt {
+                    response.answers.retain(dns::Answer::is_standard);
+                    response.authorities.retain(dns::Answer::is_standard);
+                    response.additionals.retain(dns::Answer::is_standard);
                 }
-            }
-        }
 
-        let duration = timer.map(|t| t.elapsed());
-        if format.print(responses, duration) {
-            if errored {
-                exits::NETWORK_ERROR
+                responses.push(response);
             }
-            else {
-                exits::SUCCESS
+            Err(e) => {
+                format.print_error(e);
+                errored = true;
             }
         }
+    }
+
+    let duration = timer.map(|t| t.elapsed());
+    if format.print(responses, duration) {
+        if errored {
+            exits::NETWORK_ERROR
+        }
         else {
-            exits::NO_SHORT_RESULTS
+            exits::SUCCESS
         }
     }
+    else {
+        exits::NO_SHORT_RESULTS
+    }
 }