summary history branches tags files
commit:bc91fd5deff7791c8a6e3a02970d02a32dfe1cc8
author:Trevor Bentley
committer:Trevor Bentley
date:Sat Apr 22 19:03:39 2017 +0200
parents:23d6c5017a5e193cdf8307dcc0e439cae69a0707
Add logging to file in home directory.
diff --git a/Cargo.toml b/Cargo.toml
line changes: +2/-0
index baa7458..056d364
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -38,6 +38,8 @@ time = "0.1"
 timer = "0.1.6"
 chrono = "0.3.0"
 libc = "0.2"
+log = "0.3.7"
+log4rs = "0.6.3"
 
 [target."cfg(windows)".dependencies]
 

diff --git a/src/lib.rs b/src/lib.rs
line changes: +3/-0
index 865cf41..84262ee
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -5,6 +5,9 @@ pub mod webapi;
 // Re-export webapi interface to connectr root
 pub use webapi::*;
 
+#[macro_use]
+extern crate log;
+
 #[cfg(target_os = "macos")]
 pub mod osx;
 

diff --git a/src/main.rs b/src/main.rs
line changes: +41/-0
index 1fcecde..05274d3
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,6 +1,11 @@
 extern crate connectr;
 use connectr::SpotifyResponse;
 
+#[macro_use]
+extern crate log;
+extern crate log4rs;
+
+use std::env;
 use std::ptr;
 use std::thread::sleep;
 use std::time::Duration;
@@ -199,7 +204,38 @@ fn clear_menu<T: TStatusBar>(app: &mut ConnectrApp, _: &mut connectr::SpotifyCon
     status.clear_items();
 }
 
+fn create_logger() {
+    use log::LogLevelFilter;
+    use log4rs::append::console::ConsoleAppender;
+    use log4rs::append::file::FileAppender;
+    use log4rs::encode::pattern::PatternEncoder;
+    use log4rs::config::{Appender, Config, Logger, Root};
+
+    let log_path = format!("{}/{}", env::home_dir().unwrap().display(), ".connectr.log");
+    let stdout = ConsoleAppender::builder()
+        .encoder(Box::new(PatternEncoder::new("{m}{n}")))
+        .build();
+    let requests = FileAppender::builder()
+        .build(&log_path)
+        .unwrap();
+
+    let config = Config::builder()
+        .appender(Appender::builder().build("stdout", Box::new(stdout)))
+        .appender(Appender::builder().build("requests", Box::new(requests)))
+        .logger(Logger::builder().build("app::backend::db", LogLevelFilter::Info))
+        .logger(Logger::builder()
+            .appender("requests")
+            .additive(false)
+            .build("app::requests", LogLevelFilter::Info))
+        .build(Root::builder().appender("stdout").appender("requests").build(LogLevelFilter::Info))
+        .unwrap();
+    let _ = log4rs::init_config(config).unwrap();
+}
+
 fn main() {
+    create_logger();
+    info!("Started Connectr");
+
     let mut app = ConnectrApp {
         menu: MenuItems {
             device: Vec::<(MenuItem, String)>::new(),
@@ -213,9 +249,12 @@ fn main() {
     let mut refresh_time_utc = 0;
     let (tx,rx) = channel::<String>();
     let mut spotify = connectr::SpotifyConnectr::new();
+    info!("Created Spotify controller.");
     spotify.connect();
+    info!("Created Spotify connection.");
     spotify.set_target_device(None);
     let mut status = osx::OSXStatusBar::new(tx);
+    info!("Created status bar.");
 
     loop {
         let now = time::now_utc().to_timespec().sec as i64;
@@ -225,12 +264,14 @@ fn main() {
             clear_menu(&mut app, &mut spotify, &mut status);
             fill_menu(&mut app, &mut spotify, &mut status);
             refresh_time_utc = now + 30;
+            info!("Refreshed Spotify state.");
         }
 
         spotify.await_once(false);
         if let Ok(s) = rx.try_recv() {
             println!("Received {}", s);
             let cmd: MenuCallbackCommand = json::decode(&s).unwrap();
+            info!("Executed action: {:?}", cmd.action);
             match cmd.action {
                 CallbackAction::SelectDevice => {
                     let device = &app.menu.device;

diff --git a/src/settings/mod.rs b/src/settings/mod.rs
line changes: +5/-0
index a88ae46..88777fa
--- a/src/settings/mod.rs
+++ b/src/settings/mod.rs
@@ -39,6 +39,7 @@ fn inifile() -> String {
     // Try to load INI file from home directory
     let path = format!("{}/{}", env::home_dir().unwrap().display(), INIFILE);
     if path::Path::new(&path).exists() {
+        info!("Found config: {}", path);
         return path
     }
 
@@ -46,18 +47,21 @@ fn inifile() -> String {
     // such a thing exists.
     let bundle_ini = bundled_ini();
     if path::Path::new(&bundle_ini).exists() {
+        info!("Copied config: {}", bundle_ini);
         let _ = fs::copy(bundle_ini, path.clone());
     }
     path
 }
 
 pub fn read_settings() -> Option<Settings> {
+    info!("Attempting to read config file.");
     let conf = match Ini::load_from_file(&inifile()) {
         Ok(c) => c,
         Err(_) => {
             // No connectr.ini found.  Generate a junk one in-memory, which
             // will fail shortly after with the nice error message.
             let mut c = Ini::new();
+            info!("No config file found.");
             c.with_section(Some("connectr".to_owned()))
                 .set("port", 5657.to_string());
             c.with_section(Some("application".to_owned()))
@@ -74,6 +78,7 @@ pub fn read_settings() -> Option<Settings> {
     let secret = section.get("secret").unwrap();
     let client_id = section.get("client_id").unwrap();
     if client_id.starts_with('<') || secret.starts_with('<') {
+        error!("No config file found.  Exiting.");
         println!("");
         println!("ERROR: Spotify Client ID or Secret not set in connectr.ini!");
         println!("");