Skip to content

Commit

Permalink
Added logger to both stdout and a file, replaced of prints with info/…
Browse files Browse the repository at this point in the history
…debug log calls
  • Loading branch information
cnsr committed May 30, 2021
1 parent 3ceb05b commit 75412ad
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 29 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/target
.env
commands.yml
commands.yml
*.log
55 changes: 50 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,6 @@ http = "0.2.4"
yaml-rust = "0.4.5"
linked-hash-map = "0.5.4"
regex = "1.5.4"
rand = "0.8.3"
rand = "0.8.3"
log = "0.4.14"
chrono = "0.4.19"
20 changes: 9 additions & 11 deletions src/commands/commandset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::fs;
use std::path::Path;
use regex::Regex;
use rand::seq::SliceRandom;
use log::{info, warn, error, debug};

#[derive(Debug, Clone)]
pub struct Command {
Expand Down Expand Up @@ -102,7 +103,7 @@ impl CommandSet {
raw_command.extract_vec("replies"),
raw_command.extract_string("execute"),
);
println!("entry: {:?}", parsed_command);
info!("Command entry: {:?}", parsed_command);
match parsed_command {
Ok(command) => {
initial_commands.push(command);
Expand All @@ -122,8 +123,6 @@ impl CommandSet {
}
}
pub fn check_against_commands(&self, text: String) -> Option<String> {
println!("checking {:#?}", text);

if self.help.is_match(&text.clone()) {
let mut result = String::from("");
for command in self.commands.clone().into_iter() {
Expand All @@ -132,14 +131,15 @@ impl CommandSet {
command.clone().name.unwrap(),
command.clone().regex,
command.get_description());
}
return Some(result);
}
return Some(result);
}

for command in self.commands.clone().into_iter() {
match command.check_against(text.clone()) {

for command in self.commands.clone().into_iter() {
info!("checking regex {:?} against '{:#?}'", command.regex, text);
match command.check_against(text.clone()) {
Some(result) => {
println!("COMMAND MATCH ON TEXT: {:#?} FOR COMMAND: {:#?}", text, command);
debug!("COMMAND MATCH ON TEXT: {:#?} FOR COMMAND: {:#?}", text, command);
return Some(result);
},
_ => {}
Expand All @@ -156,15 +156,13 @@ trait ExtractString {

impl ExtractString for LinkedHashMap<Yaml, Yaml> {
fn extract_string(&mut self, value: &str) -> Option<String> {
// println!("Extracting {:?} from {:?}", value, self);
match self.get(&Yaml::from_str(value)) {
Some (value) => {
value.to_owned().into_string()
} _ => None
}
}
fn extract_vec(&mut self, value: &str) -> Option<Vec<String>> {
// println!("Extracting {:?} from {:?}", value, self);
match self.get(&Yaml::from_str(value)) {
Some (value) => {
let mut result = Vec::new();
Expand Down
14 changes: 7 additions & 7 deletions src/connection/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ extern crate serde_json;

// external
use http::{HeaderMap, HeaderValue, header::{COOKIE}};
use log::{info, warn, error, debug};

// local
use crate::message::{InboundMessage, MessageQueue, OutboundMessage, PostResult};
Expand Down Expand Up @@ -77,8 +78,8 @@ impl ChanConnection {
if self.lastpost != 0u32 {
result = format!("{}&count={}", result, self.lastpost);
}
println!("Retrieving get_url: {:#?} {:#?} {:#?}", self.raw_get_url, self.limit, self.lastpost);
println!("Result url: {}", result);
debug!("Retrieving get_url: {:#?} {:#?} {:#?}", self.raw_get_url, self.limit, self.lastpost);
info!("Result url: {}", result);
return result;
}

Expand All @@ -95,8 +96,8 @@ impl ChanConnection {
self.lastpost = message.count;
let added_to_queue = self.queue.add_to_queue(message.clone(), is_bot).await?;
if added_to_queue {
println!("Added a message to the queue: {:#?}", message.count);
println!("count: {:#?}\t is_bot: {:#?}\t is_replied_to {:#?}", message.count, is_bot, message.replied_to);
debug!("Added a message to the queue: {:#?}", message.count);
debug!("count: {:#?}\t is_bot: {:#?}\t is_replied_to {:#?}", message.count, is_bot, message.replied_to);
if !is_bot && message.replied_to != Some(true) {
match self.commands.check_against_commands(message.clone().body) {
Some (reply_text) => {
Expand Down Expand Up @@ -175,9 +176,9 @@ impl ChanConnection {
pub async fn attempt_sending_outbound(&mut self) -> Result<(), anyhow::Error> {
match self.queue.first_to_send() {
Some(message) => {
println!("Sending out: {:?}", message);
debug!("Sending out: {:?}", message);
let result: bool = self.send_message(message.clone()).await?;
println!("Sending out status: {:?}", result);
debug!("Sending out status: {:?}", result);
match result {
true => {
self.queue.append_as_first(message);
Expand Down Expand Up @@ -208,7 +209,6 @@ impl ChanConnection {
.await?;

let messages: Vec<InboundMessage> = serde_json::from_str(&response).unwrap();
// println!("Messages: \n{:#?}", messages.clone());

self.process_messages(messages).await?;
Ok(())
Expand Down
37 changes: 37 additions & 0 deletions src/logger/logger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use log::{Record, Level, Metadata};
use std::{fs::OpenOptions, io::Write, path::Path};
// TODO: look into tokio::time usage
use chrono::prelude::*;

pub struct AnnaLogger;

impl log::Log for AnnaLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= Level::Info
}

// TODO: rewrite it so the file is held in memory instead of opened for each instance
fn log(&self, record: &Record) {
let logfile = "anna.log";
if self.enabled(record.metadata()) {
println!("{} - {}", record.level(), record.args());
}
let create = Path::new(logfile).exists();
let mut file = OpenOptions::new()
.create(create)
.write(true)
.append(true)
.open(logfile)
.unwrap();
writeln!(
file,
"{}:{} - {} in {}",
Utc::now(),
record.level(),
record.args(),
record.file().unwrap(),
).unwrap();
}

fn flush(&self) {}
}
2 changes: 2 additions & 0 deletions src/logger/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
mod logger;
pub use logger::*;
6 changes: 6 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::env;
// use std::path::Path;
use tokio::time::{sleep, Duration};
use log::LevelFilter;

extern crate dotenv;
extern crate reqwest;
Expand All @@ -11,13 +12,18 @@ extern crate anyhow;
mod connection;
mod message;
mod commands;
mod logger;

// external crates
use dotenv::dotenv;

static LOGGER: logger::AnnaLogger = logger::AnnaLogger;

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
dotenv().ok();

log::set_logger(&LOGGER).map(|()| log::set_max_level(LevelFilter::Info)).unwrap();

// anna_nolimit_cookie1
let anna_cookie = env::var("ANNA_COOKIE")
Expand Down
6 changes: 2 additions & 4 deletions src/message/model.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// #![feature(in_band_lifetimes)]

use futures::future::Either;
use serde::{Deserialize, Serialize};
use anyhow::Result;
use log::{info, warn, error, debug};

#[derive(Serialize, Debug, Clone)]
pub struct OutboundMessage {
Expand All @@ -28,7 +26,7 @@ impl PostResult {
return self.success != None;
}
pub fn failed_to_send(&self) -> bool {
// println!("Checking PostResult: {:#?}", self);
debug!("Checking PostResult: {:#?}", self);
match &self.failure {
Some(reason) => reason == "countdown_violation",
None => false
Expand Down

0 comments on commit 75412ad

Please sign in to comment.