log_writer.rs
1 // Copyright (c) 2025 ADnet Contributors 2 // This file is part of the AlphaOS library. 3 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at: 7 8 // http://www.apache.org/licenses/LICENSE-2.0 9 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 use std::io; 17 use tokio::sync::mpsc; 18 19 pub enum LogWriter { 20 /// Writes to stdout. 21 Stdout(io::Stdout), 22 /// Writes to a channel. 23 Sender(mpsc::Sender<Vec<u8>>), 24 } 25 26 impl LogWriter { 27 /// Initialize a new log writer. 28 pub fn new(log_sender: &Option<mpsc::Sender<Vec<u8>>>) -> Self { 29 if let Some(sender) = log_sender { Self::Sender(sender.clone()) } else { Self::Stdout(io::stdout()) } 30 } 31 } 32 33 impl io::Write for LogWriter { 34 /// Writes the given buffer into the log writer. 35 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { 36 match self { 37 Self::Stdout(stdout) => stdout.write(buf), 38 Self::Sender(sender) => { 39 let log = buf.to_vec(); 40 let _ = sender.try_send(log); 41 Ok(buf.len()) 42 } 43 } 44 } 45 46 /// Flushes the log writer (no-op). 47 fn flush(&mut self) -> io::Result<()> { 48 Ok(()) 49 } 50 }