use rainier_support::setting_enum;
setting_enum! {
pub enum LogFormat: "log format" {
#[default]
Auto = "auto",
Pretty = "pretty",
Compact = "compact",
Json = "json",
}
}
impl LogFormat {
pub fn resolve(self, environment: &str) -> Self {
match self {
Self::Auto if matches!(environment, "production" | "prod" | "staging") => Self::Json,
Self::Auto => Self::Pretty,
explicit => explicit,
}
}
pub fn is_structured(self) -> bool {
matches!(self, Self::Json)
}
}
#[cfg(test)]
mod tests {
use super::*;
use rainier_support::Setting;
#[test]
fn auto_follows_the_environment() {
assert_eq!(LogFormat::Auto.resolve("production"), LogFormat::Json);
assert_eq!(LogFormat::Auto.resolve("prod"), LogFormat::Json);
assert_eq!(LogFormat::Auto.resolve("staging"), LogFormat::Json);
assert_eq!(LogFormat::Auto.resolve("local"), LogFormat::Pretty);
assert_eq!(LogFormat::Auto.resolve("testing"), LogFormat::Pretty);
assert_eq!(LogFormat::Auto.resolve(""), LogFormat::Pretty);
}
#[test]
fn an_explicit_format_is_never_second_guessed() {
for format in [LogFormat::Pretty, LogFormat::Compact, LogFormat::Json] {
assert_eq!(format.resolve("production"), format);
assert_eq!(format.resolve("local"), format);
}
}
#[test]
fn resolving_is_idempotent() {
let once = LogFormat::Auto.resolve("production");
assert_eq!(once.resolve("production"), once);
}
#[test]
fn only_json_is_for_machines() {
assert!(LogFormat::Json.is_structured());
assert!(!LogFormat::Pretty.is_structured());
assert!(!LogFormat::Compact.is_structured());
assert!(!LogFormat::Auto.is_structured());
}
#[test]
fn the_default_is_auto() {
assert_eq!(LogFormat::default(), LogFormat::Auto);
assert_eq!(LogFormat::parse("auto").unwrap(), LogFormat::Auto);
}
}