1use schedr_config::{LogFormat, LogSection};
5use tracing_subscriber::EnvFilter;
6
7#[cfg(test)]
8mod tests;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ResolvedFormat {
13 Json,
15 Text,
17}
18
19#[must_use]
21pub const fn resolve_format(format: LogFormat, stdout_is_terminal: bool) -> ResolvedFormat {
22 match (format, stdout_is_terminal) {
23 (LogFormat::Json, _) | (LogFormat::Auto, false) => ResolvedFormat::Json,
24 (LogFormat::Text, _) | (LogFormat::Auto, true) => ResolvedFormat::Text,
25 }
26}
27
28pub fn level_filter(level: &str) -> Result<EnvFilter, String> {
34 EnvFilter::try_new(level).map_err(|e| format!("[log] level `{level}`: {e}"))
35}
36
37const SQLX_OPTIONS: &str = "sqlx_postgres::options";
41
42#[must_use]
46pub fn quiet_sqlx_options()
47-> tracing_subscriber::filter::FilterFn<impl Fn(&tracing::Metadata<'_>) -> bool> {
48 tracing_subscriber::filter::filter_fn(|metadata| !metadata.target().starts_with(SQLX_OPTIONS))
49}
50
51pub fn init(section: &LogSection, stdout_is_terminal: bool) -> Result<bool, String> {
58 use tracing_subscriber::layer::SubscriberExt;
59 use tracing_subscriber::util::SubscriberInitExt;
60 let filter = level_filter(§ion.level)?;
61 let builder = tracing_subscriber::fmt()
62 .with_env_filter(filter)
63 .with_writer(std::io::stderr);
64 let installed = match resolve_format(section.format, stdout_is_terminal) {
65 ResolvedFormat::Json => builder
66 .json()
67 .finish()
68 .with(quiet_sqlx_options())
69 .try_init(),
70 ResolvedFormat::Text => builder.finish().with(quiet_sqlx_options()).try_init(),
71 }
72 .is_ok();
73 Ok(installed)
74}