From a8d4a7cef46bed5b74929ca87ff83f3279b8a987 Mon Sep 17 00:00:00 2001 From: Will Crichton Date: Thu, 22 Aug 2024 17:35:54 -0700 Subject: [PATCH] Add Logger data structure --- .gitignore | 3 ++- crates/chatbot/src/lib.rs | 23 ++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index c41cc9e..3d91d49 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -/target \ No newline at end of file +/target +log.txt \ No newline at end of file diff --git a/crates/chatbot/src/lib.rs b/crates/chatbot/src/lib.rs index 13c321f..c9bd6c1 100644 --- a/crates/chatbot/src/lib.rs +++ b/crates/chatbot/src/lib.rs @@ -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 = RefCell::new(SmallRng::from_entropy()); @@ -58,3 +58,24 @@ impl Chatbot { ] } } + +/// Holds chat messages and writes them to disk infrequently. +#[derive(Default)] +pub struct Logger { + logs: Vec, +} + +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(()) + } +}