Skip to main content

tracing_gcloud_layer/
google_writer.rs

1use serde_json::Value;
2use std::io::Write;
3use tokio::sync::mpsc;
4
5/// Synchronous writer handle that can be used to send log entries to a background task.
6///
7/// This implements [`std::io::Write`] so it can be used as a sink for structured logs,
8/// e.g., from `tracing` or other JSON-based logging systems. Log entries are sent
9/// through an unbounded channel to a background batch writer.
10#[derive(Clone, Debug)]
11pub struct GoogleWriterHandle {
12    pub(crate) sender: mpsc::UnboundedSender<Value>,
13}
14
15impl Write for GoogleWriterHandle {
16    /// Sends a JSON log entry to the background batching task.
17    ///
18    /// # Errors
19    ///
20    /// Returns an I/O error if the log entry cannot be deserialized from JSON.
21    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
22        let log_entry: Value = serde_json::from_slice(buf)
23            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
24
25        if let Err(e) = self.sender.send(log_entry) {
26            tracing::error!("Failed to send log: {e}");
27        }
28
29        Ok(buf.len())
30    }
31
32    fn flush(&mut self) -> std::io::Result<()> {
33        Ok(())
34    }
35}