use std::env;
use std::fmt;
use std::io::IsTerminal;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Level {
Trace = 0,
Debug = 1,
Info = 2,
Success = 3,
Warn = 4,
Error = 5,
Fatal = 6,
}
impl Level {
pub const ALL: [Level; 7] = [
Level::Trace,
Level::Debug,
Level::Info,
Level::Success,
Level::Warn,
Level::Error,
Level::Fatal,
];
pub fn badge(self) -> &'static str {
match self {
Level::Trace => "TRC",
Level::Debug => "DBG",
Level::Info => "INF",
Level::Success => "SUC",
Level::Warn => "WAR",
Level::Error => "ERR",
Level::Fatal => "FTL",
}
}
pub fn as_str(self) -> &'static str {
match self {
Level::Trace => "trace",
Level::Debug => "debug",
Level::Info => "info",
Level::Success => "success",
Level::Warn => "warn",
Level::Error => "error",
Level::Fatal => "fatal",
}
}
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseLevelError(String);
impl fmt::Display for ParseLevelError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid log level: {:?}", self.0)
}
}
impl std::error::Error for ParseLevelError {}
impl FromStr for Level {
type Err = ParseLevelError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"trace" => Ok(Level::Trace),
"debug" => Ok(Level::Debug),
"info" => Ok(Level::Info),
"success" => Ok(Level::Success),
"warn" | "warning" => Ok(Level::Warn),
"error" => Ok(Level::Error),
"fatal" | "critical" => Ok(Level::Fatal),
_ => Err(ParseLevelError(s.to_string())),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Format {
#[default]
Auto,
Pretty,
Json,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseFormatError(String);
impl fmt::Display for ParseFormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid log format: {:?}", self.0)
}
}
impl std::error::Error for ParseFormatError {}
impl FromStr for Format {
type Err = ParseFormatError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"auto" => Ok(Format::Auto),
"pretty" | "text" | "console" => Ok(Format::Pretty),
"json" => Ok(Format::Json),
_ => Err(ParseFormatError(s.to_string())),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WriterKind {
#[default]
Stderr,
Stdout,
Other,
}
#[derive(Debug, Clone)]
pub struct Config {
pub level: Level,
pub format: Format,
pub caller: bool,
pub no_color: bool,
}
impl Default for Config {
fn default() -> Self {
Config {
level: Level::Info,
format: Format::Auto,
caller: false,
no_color: false,
}
}
}
impl Config {
pub fn from_env() -> Self {
let mut config = Config::default();
if let Some(parsed) = env::var("LOG_LEVEL").ok().and_then(|l| l.parse().ok()) {
config.level = parsed;
}
if let Some(parsed) = env::var("LOG_FORMAT").ok().and_then(|l| l.parse().ok()) {
config.format = parsed;
}
if let Ok(caller) = env::var("LOG_CALLER") {
config.caller = matches!(caller.as_str(), "1" | "true");
}
if env::var_os("NO_COLOR").is_some() || env::var("TERM").as_deref() == Ok("dumb") {
config.no_color = true;
}
config
}
#[must_use]
pub fn with_level(mut self, level: Level) -> Self {
self.level = level;
self
}
#[must_use]
pub fn with_format(mut self, format: Format) -> Self {
self.format = format;
self
}
#[must_use]
pub fn with_caller(mut self, caller: bool) -> Self {
self.caller = caller;
self
}
#[must_use]
pub fn with_no_color(mut self, no_color: bool) -> Self {
self.no_color = no_color;
self
}
pub fn resolved_format(&self, writer_kind: WriterKind) -> Format {
match self.format {
Format::Auto => match writer_kind {
WriterKind::Stderr => {
if std::io::stderr().is_terminal() {
Format::Pretty
} else {
Format::Json
}
}
WriterKind::Stdout => {
if std::io::stdout().is_terminal() {
Format::Pretty
} else {
Format::Json
}
}
WriterKind::Other => Format::Json,
},
explicit => explicit,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn level_ordering_enables_filtering() {
assert!(Level::Trace < Level::Info);
assert!(Level::Info < Level::Success);
assert!(Level::Success < Level::Warn);
assert!(Level::Error < Level::Fatal);
assert!(Level::Info >= Level::Info);
}
#[test]
fn level_parsing_and_aliases() {
assert_eq!("info".parse(), Ok(Level::Info));
assert_eq!("success".parse(), Ok(Level::Success));
assert_eq!("WARNING".parse(), Ok(Level::Warn));
assert_eq!("Critical".parse(), Ok(Level::Fatal));
assert!("nonsense".parse::<Level>().is_err());
}
#[test]
fn success_badge_and_str() {
assert_eq!(Level::Success.badge(), "SUC");
assert_eq!(Level::Success.as_str(), "success");
}
#[test]
fn format_parsing() {
assert_eq!("json".parse(), Ok(Format::Json));
assert_eq!("pretty".parse(), Ok(Format::Pretty));
assert_eq!("auto".parse(), Ok(Format::Auto));
assert!("xml".parse::<Format>().is_err());
}
#[test]
fn builder_methods_compose() {
let config = Config::default()
.with_level(Level::Trace)
.with_format(Format::Json)
.with_caller(true)
.with_no_color(true);
assert_eq!(config.level, Level::Trace);
assert_eq!(config.format, Format::Json);
assert!(config.caller);
assert!(config.no_color);
}
#[test]
fn explicit_formats_resolve_to_themselves() {
for kind in [WriterKind::Stderr, WriterKind::Stdout, WriterKind::Other] {
assert_eq!(
Config::default()
.with_format(Format::Json)
.resolved_format(kind),
Format::Json
);
assert_eq!(
Config::default()
.with_format(Format::Pretty)
.resolved_format(kind),
Format::Pretty
);
}
}
#[test]
fn auto_resolves_to_json_for_non_terminal_sinks() {
assert_eq!(
Config::default().resolved_format(WriterKind::Other),
Format::Json
);
}
}