muse2/
log.rs

1//! The `log` module provides initialisation and configuration of the application's logging system.
2//!
3//! This module sets up logging with various levels (error, warn, info, debug, trace) and optional
4//! colourisation based on terminal support. It also allows configuration of the log level through
5//! environment variables.
6use anyhow::{Result, bail};
7use chrono::Local;
8use fern::colors::{Color, ColoredLevelConfig};
9use fern::{Dispatch, FormatCallback};
10use log::{LevelFilter, Record};
11use std::env;
12use std::fmt::{Arguments, Display};
13use std::fs::OpenOptions;
14use std::io::IsTerminal;
15use std::path::Path;
16use std::sync::OnceLock;
17
18/// A flag indicating whether the logger has been initialised
19static LOGGER_INIT: OnceLock<()> = OnceLock::new();
20
21/// The default log level for the program.
22///
23/// Used as a fallback if the user hasn't specified something else with the `MUSE2_LOG_LEVEL`
24/// environment variable or the settings.toml file.
25pub const DEFAULT_LOG_LEVEL: &str = "info";
26
27/// The file name for the log file containing messages about the ordinary operation of MUSE2
28const LOG_INFO_FILE_NAME: &str = "muse2_info.log";
29
30/// The file name for the log file containing warnings and error messages
31const LOG_ERROR_FILE_NAME: &str = "muse2_error.log";
32
33/// Whether the program logger has been initialised
34pub fn is_logger_initialised() -> bool {
35    LOGGER_INIT.get().is_some()
36}
37
38/// Initialise the program logger using the `fern` logging library with colourised output.
39///
40/// The user can specify their preferred logging level via the `settings.toml` file (defaulting to
41/// `info` if not present) or with the `MUSE2_LOG_LEVEL` environment variable. If both are provided,
42/// the environment variable takes precedence.
43///
44/// Possible log level options are:
45///
46/// * `error`
47/// * `warn`
48/// * `info`
49/// * `debug`
50/// * `trace`
51///
52/// # Arguments
53///
54/// * `log_level_from_settings`: The log level specified in `settings.toml`
55/// * `log_file_path`: The location to save log files (if Some, log files will be created)
56pub fn init(log_level_from_settings: &str, log_file_path: Option<&Path>) -> Result<()> {
57    // Retrieve the log level from the environment variable or settings, or use the default
58    let log_level =
59        env::var("MUSE2_LOG_LEVEL").unwrap_or_else(|_| log_level_from_settings.to_string());
60
61    // Convert the log level string to a log::LevelFilter
62    let log_level = match log_level.to_lowercase().as_str() {
63        "off" => LevelFilter::Off,
64        "error" => LevelFilter::Error,
65        "warn" => LevelFilter::Warn,
66        "info" => LevelFilter::Info,
67        "debug" => LevelFilter::Debug,
68        "trace" => LevelFilter::Trace,
69        unknown => bail!("Unknown log level: {unknown}"),
70    };
71
72    // Set up colours for log levels
73    let colours = ColoredLevelConfig::new()
74        .error(Color::Red)
75        .warn(Color::Yellow)
76        .info(Color::Green)
77        .debug(Color::Blue)
78        .trace(Color::Magenta);
79
80    // Automatically apply colours only if the output is a terminal
81    let use_colour_stdout = std::io::stdout().is_terminal();
82    let use_colour_stderr = std::io::stderr().is_terminal();
83
84    // Create log files if log file path is available
85    let (info_log_file, err_log_file) = if let Some(log_file_path) = log_file_path {
86        let new_log_file = |file_name| {
87            OpenOptions::new()
88                .write(true)
89                .create(true)
90                .truncate(true)
91                .open(log_file_path.join(file_name))
92        };
93        (
94            Some(new_log_file(LOG_INFO_FILE_NAME)?),
95            Some(new_log_file(LOG_ERROR_FILE_NAME)?),
96        )
97    } else {
98        (None, None)
99    };
100
101    // Configure the logger
102    let mut dispatch = Dispatch::new()
103        .chain(
104            // Write non-error messages to stdout
105            Dispatch::new()
106                .filter(|metadata| metadata.level() > LevelFilter::Warn)
107                .format(move |out, message, record| {
108                    write_log_colour(out, message, record, use_colour_stdout, &colours);
109                })
110                .level(log_level)
111                .chain(std::io::stdout()),
112        )
113        .chain(
114            // Write error messages to stderr
115            Dispatch::new()
116                .format(move |out, message, record| {
117                    write_log_colour(out, message, record, use_colour_stderr, &colours);
118                })
119                .level(log_level.min(LevelFilter::Warn))
120                .chain(std::io::stderr()),
121        );
122
123    // Add log file chains if log files were created
124    if let Some(info_log_file) = info_log_file {
125        dispatch = dispatch.chain(
126            // Write non-error messages to log file
127            Dispatch::new()
128                .filter(|metadata| metadata.level() > LevelFilter::Warn)
129                .format(write_log_plain)
130                .level(log_level.max(LevelFilter::Info))
131                .chain(info_log_file),
132        );
133    }
134
135    if let Some(err_log_file) = err_log_file {
136        dispatch = dispatch.chain(
137            // Write error messages to a different log file
138            Dispatch::new()
139                .format(write_log_plain)
140                .level(LevelFilter::Warn)
141                .chain(err_log_file),
142        );
143    }
144
145    // Apply the logger configuration
146    dispatch.apply().expect("Logger already initialised");
147
148    // Set a flag to indicate that the logger has been initialised
149    LOGGER_INIT.set(()).unwrap();
150
151    Ok(())
152}
153
154/// Write to the log in the format we want for MUSE2
155fn write_log<T: Display>(out: FormatCallback, level: T, target: &str, message: &Arguments) {
156    let timestamp = Local::now().format("%H:%M:%S");
157
158    out.finish(format_args!("[{timestamp} {level} {target}] {message}"));
159}
160
161/// Write to the log with no colours
162fn write_log_plain(out: FormatCallback, message: &Arguments, record: &Record) {
163    write_log(out, record.level(), record.target(), message);
164}
165
166/// Write to the log with optional colours
167fn write_log_colour(
168    out: FormatCallback,
169    message: &Arguments,
170    record: &Record,
171    use_colour: bool,
172    colours: &ColoredLevelConfig,
173) {
174    // Format output with or without colour based on `use_colour`
175    if use_colour {
176        write_log(out, colours.color(record.level()), record.target(), message);
177    } else {
178        write_log_plain(out, message, record);
179    }
180}