pub mod json;
pub mod template;
pub mod text;
pub mod util;
use crate::record::Record;
use std::fmt::Debug;
use std::sync::Arc;
pub type FormatFn = Arc<dyn Fn(&Record) -> String + Send + Sync>;
pub trait FormatterTrait: Send + Sync + Debug {
fn fmt(&self, record: &Record) -> String;
fn fmt_batch(&self, records: &[Record]) -> String {
records
.iter()
.map(|record| FormatterTrait::fmt(self, record))
.collect::<Vec<_>>()
.join("\n")
}
fn with_colors(&mut self, use_colors: bool);
fn with_timestamp(&mut self, include_timestamp: bool);
fn with_level(&mut self, include_level: bool);
fn with_module(&mut self, include_module: bool);
fn with_location(&mut self, include_location: bool);
fn with_pattern(&mut self, pattern: String);
fn with_format(&mut self, format_fn: FormatFn);
fn box_clone(&self) -> Box<dyn FormatterTrait + Send + Sync>;
}
#[derive(Debug)]
pub struct Formatter {
inner: Box<dyn FormatterTrait + Send + Sync>,
}
impl Clone for Formatter {
fn clone(&self) -> Self {
Self {
inner: self.inner.box_clone(),
}
}
}
impl Default for Formatter {
fn default() -> Self {
Self::text()
}
}
impl Formatter {
pub fn text() -> Self {
Self {
inner: Box::new(crate::formatters::text::TextFormatter::default()),
}
}
pub fn json() -> Self {
Self {
inner: Box::new(crate::formatters::json::JsonFormatter::default()),
}
}
pub fn template(template: impl Into<String>) -> Self {
Self {
inner: Box::new(crate::formatters::template::TemplateFormatter::new(
template,
)),
}
}
pub fn format(&self, record: &Record) -> String {
FormatterTrait::fmt(&*self.inner, record)
}
pub fn format_batch(&self, records: &[Record]) -> String {
self.inner.fmt_batch(records)
}
pub fn with_colors(mut self, use_colors: bool) -> Self {
self.inner.with_colors(use_colors);
self
}
pub fn with_timestamp(mut self, include_timestamp: bool) -> Self {
self.inner.with_timestamp(include_timestamp);
self
}
pub fn with_level(mut self, include_level: bool) -> Self {
self.inner.with_level(include_level);
self
}
pub fn with_module(mut self, include_module: bool) -> Self {
self.inner.with_module(include_module);
self
}
pub fn with_location(mut self, include_location: bool) -> Self {
self.inner.with_location(include_location);
self
}
pub fn with_pattern(mut self, pattern: impl Into<String>) -> Self {
self.inner.with_pattern(pattern.into());
self
}
pub fn with_format<F>(mut self, format_fn: F) -> Self
where
F: Fn(&Record) -> String + Send + Sync + 'static,
{
self.inner.with_format(Arc::new(format_fn));
self
}
}
pub use self::json::JsonFormatter;
pub use self::template::TemplateFormatter;
pub use self::text::TextFormatter;