~gbmor/clinte

c5ea65393d9b8000d68cf8c2f887f22bdae81222 — Ben Morrison 1 year, 2 months ago a24e259
logging changes:

Rather than using a new logfile for each invocation, a single logfile
called `/tmp/clinte_$USER.log` will be used, with later invocations
appending to the previous messages.

Also removed some unnecessary `use` statements relating to the `log`
crate and its macros. Leaving the macro calls namespaced to `log::`
makes it clearer what the behavior is.
5 files changed, 25 insertions(+), 44 deletions(-)

M src/db.rs
M src/ed.rs
M src/logging.rs
M src/main.rs
M src/user.rs
M src/db.rs => src/db.rs +2 -5
@@ 1,8 1,5 @@
use std::time;

use log::info;
use rusqlite;

const DB_PATH: &str = "/usr/local/clinte/clinte.db";

#[derive(Debug)]


@@ 21,7 18,7 @@ pub struct Conn {
impl Conn {
    pub fn init(path: &str) -> rusqlite::Connection {
        let start = time::Instant::now();
        info!("Connecting to database");
        log::info!("Connecting to database");
        let conn = rusqlite::Connection::open_with_flags(
            path,
            rusqlite::OpenFlags::SQLITE_OPEN_FULL_MUTEX


@@ 41,7 38,7 @@ impl Conn {
        )
        .expect("Could not initialize DB");

        info!(
        log::info!(
            "Database connection established in {}ms",
            start.elapsed().as_millis()
        );

M src/ed.rs => src/ed.rs +0 -1
@@ 3,7 3,6 @@ use std::fs;
use std::process;

use chrono::prelude::*;
use log;

use crate::error;
use crate::user;

M src/logging.rs => src/logging.rs +16 -30
@@ 1,38 1,23 @@
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;

use chrono::offset::Utc;
use simplelog::*;

use crate::error;
use crate::user;

lazy_static! {
    static ref FILE: String = format!("/tmp/clinte_{}.log", *user::NAME);
}

pub fn init() -> error::Result<()> {
    // If the log file exists on startup,
    // move and timestamp it so we get a
    // fresh log file.
    if fs::metadata(FILE.clone()).is_ok() {
        let mut new_file = FILE.clone();
        let time = Utc::now().to_rfc3339();
        new_file.push_str(".");
        new_file.push_str(&time);
        fs::rename(FILE.clone(), new_file)?;
    let file = format!("/tmp/clinte_{}.log", *user::NAME);
    let logfile = match OpenOptions::new().append(true).create(true).open(file) {
        Err(e) => {
            panic!("Could not open log file: {}", e);
        }
        Ok(f) => f,
    };

    if let Err(e) = WriteLogger::init(LevelFilter::Info, Config::default(), logfile) {
        panic!("Could not initiate logging: {}", e);
    }

    CombinedLogger::init(vec![
        TermLogger::new(LevelFilter::Warn, Config::default(), TerminalMode::Stderr).unwrap(),
        WriteLogger::new(
            LevelFilter::Info,
            Config::default(),
            File::create(FILE.clone())?,
        ),
    ])
    .expect("Unable to initialize logging");

    Ok(())
}



@@ 40,16 25,17 @@ pub fn init() -> error::Result<()> {
mod tests {
    use super::*;

    use log::info;
    use std::fs;

    #[test]
    fn init_logs() {
        let file = format!("/tmp/clinte_{}.log", *user::NAME);
        let blank = " ".bytes().collect::<Vec<u8>>();
        fs::write(&*FILE, &blank).unwrap();
        fs::write(&file, &blank).unwrap();
        init().unwrap();

        info!("TEST LOG MESSAGE");
        let logfile = fs::read_to_string(&*FILE).unwrap();
        log::info!("TEST LOG MESSAGE");
        let logfile = fs::read_to_string(&file).unwrap();
        assert!(logfile.contains("TEST LOG MESSAGE"));
    }
}

M src/main.rs => src/main.rs +5 -6
@@ 4,7 4,6 @@ use std::time;
extern crate lazy_static;

use clap;
use log::info;

mod db;
mod ed;


@@ 25,17 24,17 @@ fn main() -> error::Result<()> {

    let start = time::Instant::now();
    logging::init()?;
    info!("clinte starting up!");
    log::info!("clinte starting up!");
    println!("clinte v{}", clap::crate_version!());
    println!("a community notices system");
    println!();

    let db = db::Conn::new();

    info!("Startup completed in {:?}ms", start.elapsed().as_millis());
    log::info!("Startup completed in {:?}ms", start.elapsed().as_millis());

    if arg_matches.subcommand_matches("post").is_some() {
        info!("New post...");
        log::info!("New post...");
        posts::create(&db)?;
    } else if arg_matches.subcommand_matches("update").is_some() {
        let id: u32 = if let Some(val) = arg_matches.subcommand_matches("update_handler") {


@@ 43,7 42,7 @@ fn main() -> error::Result<()> {
        } else {
            0
        };
        info!("Updating post ...");
        log::info!("Updating post ...");
        posts::update_handler(&db, id)?;
    } else if arg_matches.subcommand_matches("delete").is_some() {
        let id: u32 = if let Some(val) = arg_matches.subcommand_matches("update_handler") {


@@ 51,7 50,7 @@ fn main() -> error::Result<()> {
        } else {
            0
        };
        info!("Deleting post");
        log::info!("Deleting post");
        posts::delete_handler(&db, id)?;
    }


M src/user.rs => src/user.rs +2 -2
@@ 2,7 2,7 @@ use users;

lazy_static! {
    pub static ref NAME: String = users::get_current_username()
        .unwrap()
        .expect("Could not get username")
        .into_string()
        .unwrap();
        .expect("Could not get username");
}