Skip to main content

xet_runtime/logging/
config.rs

1#[cfg(not(target_family = "wasm"))]
2use std::path::Path;
3use std::path::PathBuf;
4use std::time::Duration;
5
6use crate::config::XetConfig;
7#[cfg(not(target_family = "wasm"))]
8use crate::utils::TemplatedPathBuf;
9
10#[derive(Clone, Debug, PartialEq)]
11pub enum LoggingMode {
12    Directory(PathBuf),
13    File(PathBuf),
14    Console,
15}
16
17/// The log directory cleanup configuration.
18#[derive(Clone, Debug, PartialEq)]
19pub struct LogDirConfig {
20    pub min_deletion_age: Duration,
21    pub max_retention_age: Duration,
22    pub size_limit: u64,
23    pub filename_prefix: String,
24}
25
26impl LogDirConfig {
27    pub fn from_config(config: &XetConfig) -> Self {
28        Self {
29            min_deletion_age: config.log.dir_min_deletion_age,
30            max_retention_age: config.log.dir_max_retention_age,
31            size_limit: config.log.dir_max_size.as_u64(),
32            filename_prefix: config.log.prefix.to_string(),
33        }
34    }
35}
36
37#[derive(Clone, Debug, PartialEq)]
38pub struct LoggingConfig {
39    pub logging_mode: LoggingMode,
40    pub use_json: bool,
41    pub enable_log_dir_cleanup: bool,
42    pub version: String,
43    pub log_dir_config: LogDirConfig,
44}
45
46impl LoggingConfig {
47    /// Set up logging to a directory using the given config.
48    #[cfg(not(target_family = "wasm"))]
49    pub fn from_directory(config: &XetConfig, version: String, log_directory: impl AsRef<Path>) -> LoggingConfig {
50        let logging_mode = {
51            if let Some(log_dest) = &config.log.dest {
52                if log_dest.as_str().is_empty() {
53                    LoggingMode::Console
54                } else {
55                    let path = TemplatedPathBuf::evaluate(log_dest);
56
57                    if log_dest.ends_with('/')
58                        || (cfg!(windows) && log_dest.ends_with('\\'))
59                        || (path.exists() && path.is_dir())
60                    {
61                        LoggingMode::Directory(path)
62                    } else {
63                        LoggingMode::File(path)
64                    }
65                }
66            } else {
67                LoggingMode::Directory(log_directory.as_ref().to_path_buf())
68            }
69        };
70
71        let use_json = {
72            if let Some(format) = &config.log.format {
73                format.as_str().to_ascii_lowercase().trim() == "json"
74            } else {
75                logging_mode != LoggingMode::Console
76            }
77        };
78
79        let enable_log_dir_cleanup =
80            matches!(logging_mode, LoggingMode::Directory(_)) && !config.log.dir_disable_cleanup;
81
82        Self {
83            logging_mode,
84            use_json,
85            enable_log_dir_cleanup,
86            version,
87            log_dir_config: LogDirConfig::from_config(config),
88        }
89    }
90}