Skip to content

Commit

Permalink
Add Logger data structure
Browse files Browse the repository at this point in the history
  • Loading branch information
willcrichton committed Aug 26, 2024
1 parent b25502e commit 7e0c591
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/target
/target
log.txt
23 changes: 22 additions & 1 deletion crates/chatbot/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use rand::{rngs::SmallRng, Rng, SeedableRng};
use std::{cell::RefCell, path::PathBuf, time::Duration};
use std::{cell::RefCell, io, path::PathBuf, time::Duration};

thread_local! {
static RNG: RefCell<SmallRng> = RefCell::new(SmallRng::from_entropy());
Expand Down Expand Up @@ -58,3 +58,24 @@ impl Chatbot {
]
}
}

/// Holds chat messages and writes them to disk infrequently.
#[derive(Default)]
pub struct Logger {
logs: Vec<String>,
}

impl Logger {
/// Saves the message to the logger.
pub fn append(&mut self, message: &str) {
self.logs.push(message.to_string());
}

/// Potentially writes the logs to disk, if needed.
pub async fn save(&self) -> io::Result<()> {
if self.logs.len() % 3 == 0 {
tokio::fs::write("log.txt", self.logs.join("\n")).await?;
}
Ok(())
}
}

0 comments on commit 7e0c591

Please sign in to comment.