Skip to main content

schedr_bin/
logging.rs

1//! schedr's own logs (see archive/PROJECT.md, Observability): stdout, JSON in pods and readable
2//! text in a terminal, with `RUST_LOG`-style level filters.
3
4use schedr_config::{LogFormat, LogSection};
5use tracing_subscriber::EnvFilter;
6
7#[cfg(test)]
8mod tests;
9
10/// The format actually used once `auto` is resolved.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ResolvedFormat {
13    /// One JSON object per line.
14    Json,
15    /// Human-readable lines.
16    Text,
17}
18
19/// Resolves `[log] format`: `auto` is text in a terminal and JSON otherwise (pods).
20#[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
28/// The level filter for `[log] level`, e.g. `info` or `info,schedr_master=debug`.
29///
30/// # Errors
31///
32/// Returns the filter's own message if the level isn't a valid filter directive.
33pub fn level_filter(level: &str) -> Result<EnvFilter, String> {
34    EnvFilter::try_new(level).map_err(|e| format!("[log] level `{level}`: {e}"))
35}
36
37/// The target of sqlx's connect-options warnings, which quote a database URL's unknown
38/// parameter with its value, a password among them (`PassWord=`, `sslpassword=`: B203's
39/// review); schedr warns of such a parameter by name instead.
40const SQLX_OPTIONS: &str = "sqlx_postgres::options";
41
42/// A filter dropping sqlx's connect-options events (`sqlx_postgres::options`) whatever
43/// `[log] level` says: a layer of its own, so no directive of the level
44/// (`sqlx_postgres::options::parse=debug`) brings them back.
45#[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
51/// Installs the global logger. Returns `false` if one was already installed (only the first
52/// call in a process takes effect).
53///
54/// # Errors
55///
56/// Returns a message if `[log] level` is invalid.
57pub 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(&section.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}