summaryrefslogtreecommitdiffstats
path: root/src/log
diff options
context:
space:
mode:
authorMatthias Beyer <mail@beyermatthias.de>2020-11-04 14:59:31 +0100
committerMatthias Beyer <mail@beyermatthias.de>2020-11-04 16:43:27 +0100
commit3ff4fee49963d461fd5dcc896a0ea10ed63759eb (patch)
treeefd063a59b136c1011e1b0f9e6719d877834d4f2 /src/log
parent7188fc9ee1d3b2eaf0ee6f5f2a152a7237329ced (diff)
Add FileSink as LogSink implementation that writes to a file
Signed-off-by: Matthias Beyer <mail@beyermatthias.de>
Diffstat (limited to 'src/log')
-rw-r--r--src/log/filesink.rs63
-rw-r--r--src/log/mod.rs3
2 files changed, 66 insertions, 0 deletions
diff --git a/src/log/filesink.rs b/src/log/filesink.rs
new file mode 100644
index 0000000..6052254
--- /dev/null
+++ b/src/log/filesink.rs
@@ -0,0 +1,63 @@
+use std::path::Path;
+use std::path::PathBuf;
+use std::fs::File;
+use std::fs::OpenOptions;
+use std::convert::TryInto;
+use std::io::Write;
+
+use anyhow::Result;
+use anyhow::Error;
+use anyhow::anyhow;
+
+use crate::log::LogSink;
+use crate::log::LogItem;
+use crate::job::Job;
+
+pub struct FileSink {
+ file: File,
+}
+
+impl FileSink {
+ fn new(path: &Path) -> Result<Self> {
+ OpenOptions::new()
+ .create(true)
+ .append(true)
+ .write(false)
+ .open(path)
+ .map(|file| FileSink { file })
+ .map_err(Error::from)
+ }
+}
+
+impl LogSink for FileSink {
+ fn log_item(&mut self, item: LogItem) -> Result<()> {
+ let s: String = item.try_into()?;
+ writeln!(self.file, "{}", s)?;
+ Ok(())
+ }
+}
+
+pub struct FileLogSinkFactory {
+ root: PathBuf
+}
+
+impl FileLogSinkFactory {
+ pub fn new(root: PathBuf) -> Self {
+ FileLogSinkFactory { root }
+ }
+
+ pub fn new_file_sink(&self, job: &Job) -> Result<FileSink> {
+ let now = chrono::offset::Local::now()
+ .naive_local()
+ .format("%Y-%m-%dT%H:%M:%S");
+
+ trace!("Got current time: {}", now);
+ let filename = format!("{}-{}", now, job.package().name());
+
+ trace!("Building path from {} and {}", self.root.display(), filename);
+ let p = self.root.join(filename);
+
+ FileSink::new(&p)
+ }
+}
+
diff --git a/src/log/mod.rs b/src/log/mod.rs
index e3d8325..bf24ad9 100644
--- a/src/log/mod.rs
+++ b/src/log/mod.rs
@@ -7,5 +7,8 @@ pub use item::*;
mod sink;
pub use sink::*;
+mod filesink;
+pub use filesink::*;
+
mod util;