Skip to content

Commit 84a9a4e

Browse files
authored
Merge pull request #13 from windoze/log2file
Log file settings
2 parents f80404a + cb5aea1 commit 84a9a4e

File tree

3 files changed

+53
-5
lines changed

3 files changed

+53
-5
lines changed

Cargo.lock

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

clip-sync-config/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ clap-verbosity-flag = { workspace = true }
1717
platform-dirs = { workspace = true }
1818
serde = { workspace = true, features = ["derive"] }
1919
toml = { workspace = true }
20+
chrono = { workspace = true }
2021
url = { workspace = true, optional = true }
2122

2223
mqtt-client = { workspace = true, optional = true }

clip-sync-config/src/lib.rs

+51-5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::io::Write;
12
use std::path::{Path, PathBuf};
23

34
use clap::Parser;
@@ -17,6 +18,9 @@ pub struct Args {
1718
#[cfg(feature = "websocket")]
1819
#[serde(default)]
1920
pub websocket_client: websocket_client::ClientConfig,
21+
22+
pub log_file: Option<String>,
23+
pub log_level: Option<String>,
2024
}
2125

2226
impl Args {
@@ -75,9 +79,51 @@ pub fn parse() -> anyhow::Result<Args> {
7579
}
7680

7781
let cli = Config::parse();
78-
env_logger::Builder::new()
79-
.filter_level(cli.verbose.log_level_filter())
80-
.filter_module("tantivy", log::LevelFilter::Warn) // Tantivy is too talky at the INFO level
81-
.init();
82-
parse_config(cli.config_path)
82+
let args = parse_config(cli.config_path)?;
83+
84+
let log_level = if let Some(log_level) = args.log_level.as_ref() {
85+
log_level.parse()?
86+
} else {
87+
cli.verbose.log_level_filter()
88+
};
89+
90+
let debug = log_level == log::LevelFilter::Debug
91+
|| cli.verbose.log_level_filter() == log::LevelFilter::Trace;
92+
93+
if let Some(log_file) = args.log_file.as_ref() {
94+
let target = Box::new(std::fs::File::create(log_file).expect("Can't create file"));
95+
96+
env_logger::Builder::new()
97+
.format(move |buf, record| {
98+
if debug {
99+
writeln!(
100+
buf,
101+
"{}:{} {} [{}] - {}",
102+
record.file().unwrap_or("unknown"),
103+
record.line().unwrap_or(0),
104+
chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.3f"),
105+
record.level(),
106+
record.args()
107+
)
108+
} else {
109+
writeln!(
110+
buf,
111+
"{} [{}] - {}",
112+
chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.3f"),
113+
record.level(),
114+
record.args()
115+
)
116+
}
117+
})
118+
.target(env_logger::Target::Pipe(target))
119+
.filter_level(log_level)
120+
.filter_module("tantivy", log::LevelFilter::Warn) // Tantivy is too talky at the INFO level
121+
.init();
122+
} else {
123+
env_logger::Builder::new()
124+
.filter_level(log_level)
125+
.filter_module("tantivy", log::LevelFilter::Warn) // Tantivy is too talky at the INFO level
126+
.init();
127+
}
128+
Ok(args)
83129
}

0 commit comments

Comments
 (0)