use alloc::format;
use alloc::string::String;
use core::fmt::{self, Display};
use eko::env;
use tracing::dispatcher::SetGlobalDefaultError;
pub use {::tracing, ::tracing_core};
pub struct LoggerConfig {
pub filter: Option<String>,
pub color_logs: Option<String>,
pub verbose_entry_exit: Option<String>,
pub verbose_thread_ids: Option<String>,
pub backtrace: Option<String>,
pub json: Option<String>,
pub output_target: Option<String>,
pub wraptree: Option<String>,
pub lines: Option<String>,
}
impl LoggerConfig {
pub fn from_env(env: &str) -> Self {
LoggerConfig {
filter: env::var(env),
color_logs: env::var(&format!("{env}_COLOR")),
verbose_entry_exit: env::var(&format!("{env}_ENTRY_EXIT")),
verbose_thread_ids: env::var(&format!("{env}_THREAD_IDS")),
backtrace: env::var(&format!("{env}_BACKTRACE")),
wraptree: env::var(&format!("{env}_WRAPTREE")),
lines: env::var(&format!("{env}_LINES")),
json: env::var(&format!("{env}_FORMAT_JSON")),
output_target: env::var(&format!("{env}_OUTPUT_TARGET")),
}
}
fn requested(&self) -> bool {
self.filter.is_some()
|| self.color_logs.is_some()
|| self.verbose_entry_exit.is_some()
|| self.verbose_thread_ids.is_some()
|| self.backtrace.is_some()
|| self.json.is_some()
|| self.output_target.is_some()
|| self.wraptree.is_some()
|| self.lines.is_some()
}
}
pub fn init_logger(cfg: LoggerConfig) -> Result<(), Error> {
match &cfg.color_logs {
Some(value) => match value.as_ref() {
"always" | "never" | "auto" => {}
_ => return Err(Error::InvalidColorValue(value.clone())),
},
None => {}
}
if let Some(v) = &cfg.wraptree
&& v.parse::<usize>().is_err()
{
return Err(Error::InvalidWraptree(v.clone()));
}
if cfg.requested() {
eko::eprintln!(
"warning: `-Zlog` is unsupported in this build: the tracing_subscriber sink was \
removed because every feature of it that this compiler used (fmt, env-filter, \
registry) forces a dependency on std, which is banned in this tree"
);
}
Ok(())
}
pub fn stdout_isatty() -> bool {
eko::file::stdout().is_terminal()
}
pub fn stderr_isatty() -> bool {
eko::file::stderr().is_terminal()
}
#[derive(Debug)]
pub enum Error {
InvalidColorValue(String),
NonUnicodeColorValue,
InvalidWraptree(String),
AlreadyInit(SetGlobalDefaultError),
}
impl core::error::Error for Error {}
impl Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InvalidColorValue(value) => write!(
formatter,
"invalid log color value '{value}': expected one of always, never, or auto",
),
Error::NonUnicodeColorValue => write!(
formatter,
"non-Unicode log color value: expected one of always, never, or auto",
),
Error::InvalidWraptree(value) => write!(
formatter,
"invalid log WRAPTREE value '{value}': expected a non-negative integer",
),
Error::AlreadyInit(tracing_error) => Display::fmt(tracing_error, formatter),
}
}
}
impl From<SetGlobalDefaultError> for Error {
fn from(tracing_error: SetGlobalDefaultError) -> Self {
Error::AlreadyInit(tracing_error)
}
}