use crate::service::ServiceError;
use crate::service::fallback::Fallback;
use crate::service::write::{StandardMessageFormatter, MessageFormatter};
use crate::{LoggerStatus, Message, Service};
use std::any::Any;
use std::sync::Mutex;
pub struct Cout<F>
where
F: MessageFormatter,
{
formatter: Mutex<F>,
}
impl<F> Cout<F>
where
F: MessageFormatter,
{
pub fn new() -> Box<Self> {
Box::new(Self {
formatter: Mutex::new(Default::default()),
})
}
pub fn with_formatter(formatter: F) -> Box<Self> {
Box::new(Self {
formatter: Mutex::new(formatter),
})
}
}
impl<F> Service for Cout<F>
where
F: MessageFormatter + 'static,
{
fn status(&self) -> LoggerStatus {
LoggerStatus::Running
}
fn work(&self, msg: &Message) -> Result<(), ServiceError> {
let mut formatter_guard = self.formatter.lock()?;
let mut out = std::io::stdout();
formatter_guard.format_io(msg, &mut out)?;
Ok(())
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl<F> Fallback for Cout<F>
where
F: MessageFormatter + 'static,
{
fn fallback(&self, error: &ServiceError, msg: &Message) {
if let Ok(mut guard) = self.formatter.lock() {
let mut out = std::io::stdout();
let _ = guard.format_io(msg, &mut out);
let _ = eprintln!("CoutWriteService Error: {}", error);
}
}
}
pub type StandardCout = Cout<StandardMessageFormatter>;
pub struct Cerr<F>
where
F: MessageFormatter,
{
formatter: Mutex<F>,
}
impl<F> Cerr<F>
where
F: MessageFormatter,
{
pub fn new() -> Box<Self> {
Box::new(Self {
formatter: Mutex::new(Default::default()),
})
}
pub fn with_formatter(formatter: F) -> Box<Self> {
Box::new(Self {
formatter: Mutex::new(formatter),
})
}
}
impl<F> Service for Cerr<F>
where
F: MessageFormatter + 'static,
{
fn status(&self) -> LoggerStatus {
LoggerStatus::Running
}
fn work(&self, msg: &Message) -> Result<(), ServiceError> {
let mut formatter_guard = self.formatter.lock()?;
let mut out = std::io::stderr();
formatter_guard.format_io(msg, &mut out)?;
Ok(())
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl<F> Fallback for Cerr<F>
where
F: MessageFormatter + 'static,
{
fn fallback(&self, error: &ServiceError, msg: &Message) {
if let Ok(mut guard) = self.formatter.lock() {
let mut out = std::io::stdout();
let _ = guard.format_io(msg, &mut out);
let _ = println!("CerrWriteService Error: {}", error);
}
}
}
pub type StandardCerr = Cerr<StandardMessageFormatter>;