From 63ea22f4434b8ce4dc480d37172bb90718a7d5d9 Mon Sep 17 00:00:00 2001 From: Thomas Jarosch Date: Sat, 4 May 2024 23:31:20 +0200 Subject: [PATCH] Fix logging messages after `flush()` (#7) Resets the "flushed" flag on each `write()` invocation. Otherwise we would buffer data and never flush it out as demonstrated in https://github.com/max-heller/tracing-syslog/pull/4#issue-1897443390 Adds unit test for this corner case. --- src/syslog.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/syslog.rs b/src/syslog.rs index 4f902b3..c7eb2ce 100644 --- a/src/syslog.rs +++ b/src/syslog.rs @@ -339,6 +339,7 @@ thread_local! { static BUF: RefCell> = RefCell::new(Vec::with_capacity(2 impl io::Write for SyslogWriter { fn write(&mut self, bytes: &[u8]) -> io::Result { BUF.with(|buf| buf.borrow_mut().extend(bytes)); + self.flushed = false; Ok(bytes.len()) } @@ -477,6 +478,29 @@ mod tests { } } + #[test] + fn write_after_flush() { + let _lock = INITIALIZED.lock(); + + let process = "example-program"; + let text = "test message"; + + let msg = capture_stderr(|| { + use std::io::Write; + + let syslog = Syslog::new(IDENTITY, OPTIONS | Options::LOG_PERROR, FACILITY).unwrap(); + let mut writer = syslog.make_writer(); + + writer.write_all(text.as_bytes()).unwrap(); + writer.flush().unwrap(); + + writer.write_all(text.as_bytes()).unwrap(); + // writer dropped here -> flush() + }); + + assert_eq!(msg, format!("{process}: {text}\n{process}: {text}\n")) + } + #[test] #[should_panic = "interior nul byte"] fn invalid_chars_panic() {