use serde::Serialize;
use crate::error::{Result, Error};
pub trait Formatter {
fn format<T: Serialize>(&self, entry: &T) -> Result<String>;
fn format_with_options<T: Serialize>(&self, entry: &T, options: &FormatterOptions) -> Result<String>;
}
#[derive(Debug, Clone)]
pub struct FormatterOptions {
pub include_timestamps: bool,
pub include_levels: bool,
pub include_metadata: bool,
pub include_context: bool,
pub pretty_print: bool,
}
impl Default for FormatterOptions {
fn default() -> Self {
Self {
include_timestamps: true,
include_levels: true,
include_metadata: true,
include_context: true,
pretty_print: false,
}
}
}
pub struct SimpleFormatter;
impl SimpleFormatter {
pub fn new() -> Self {
Self
}
}
impl Default for SimpleFormatter {
fn default() -> Self {
Self::new()
}
}
impl Formatter for SimpleFormatter {
fn format<T: Serialize>(&self, entry: &T) -> Result<String> {
serde_json::to_string(entry).map_err(Error::SerializationError)
}
fn format_with_options<T: Serialize>(&self, entry: &T, options: &FormatterOptions) -> Result<String> {
if options.pretty_print {
serde_json::to_string_pretty(entry).map_err(Error::SerializationError)
} else {
serde_json::to_string(entry).map_err(Error::SerializationError)
}
}
}
#[allow(dead_code)]
pub struct PrettyFormatter {
options: FormatterOptions,
}
impl PrettyFormatter {
pub fn new() -> Self {
Self {
options: FormatterOptions {
pretty_print: true,
..Default::default()
},
}
}
pub fn with_options(options: FormatterOptions) -> Self {
Self { options }
}
}
impl Default for PrettyFormatter {
fn default() -> Self {
Self::new()
}
}
impl Formatter for PrettyFormatter {
fn format<T: Serialize>(&self, entry: &T) -> Result<String> {
serde_json::to_string_pretty(entry).map_err(Error::SerializationError)
}
fn format_with_options<T: Serialize>(&self, entry: &T, options: &FormatterOptions) -> Result<String> {
if options.pretty_print {
serde_json::to_string_pretty(entry).map_err(Error::SerializationError)
} else {
serde_json::to_string(entry).map_err(Error::SerializationError)
}
}
}