Skip to content

Commit 5461e99

Browse files
committed
Better logging for lintcheck
Use `simplelog` to handle logs, as `env_logger` does not handle writing to file for the moment, see rust-cli/env_logger#208 Do not push most verbose logs on stdout, only push them in the log file
1 parent f5d225d commit 5461e99

File tree

3 files changed

+49
-18
lines changed

3 files changed

+49
-18
lines changed

lintcheck/Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ publish = false
1313
cargo_metadata = "0.14"
1414
clap = "3.2"
1515
crossbeam-channel = "0.5.6"
16+
simplelog = "0.12.0"
1617
flate2 = "1.0"
18+
log = "0.4"
1719
rayon = "1.5.1"
1820
serde = { version = "1.0", features = ["derive"] }
1921
serde_json = "1.0.85"

lintcheck/src/config.rs

+30-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
use clap::{Arg, ArgAction, ArgMatches, Command};
2+
use log::LevelFilter;
3+
use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger};
24
use std::env;
5+
use std::fs::{self, File};
36
use std::path::PathBuf;
47

58
fn get_clap_config() -> ArgMatches {
@@ -39,6 +42,11 @@ fn get_clap_config() -> ArgMatches {
3942
.help("Run clippy on the dependencies of crates specified in crates-toml")
4043
.conflicts_with("threads")
4144
.conflicts_with("fix"),
45+
Arg::new("verbose")
46+
.short('v')
47+
.long("--verbose")
48+
.action(ArgAction::Count)
49+
.help("Verbosity to use, default to WARN"),
4250
])
4351
.get_matches()
4452
}
@@ -66,6 +74,27 @@ pub(crate) struct LintcheckConfig {
6674
impl LintcheckConfig {
6775
pub fn new() -> Self {
6876
let clap_config = get_clap_config();
77+
let level_filter = match clap_config.get_count("verbose") {
78+
0 => LevelFilter::Warn,
79+
1 => LevelFilter::Info,
80+
2 => LevelFilter::Debug,
81+
_ => LevelFilter::Trace,
82+
};
83+
// using `create_dir_all` as it does not error when the dir already exists
84+
fs::create_dir_all("lintcheck-logs").expect("Creating the log dir failed");
85+
let _ = CombinedLogger::init(vec![
86+
TermLogger::new(
87+
std::cmp::min(level_filter, LevelFilter::Info), // do not print more verbose log than `INFO` to stdout,
88+
Config::default(),
89+
TerminalMode::Mixed,
90+
ColorChoice::Auto,
91+
),
92+
WriteLogger::new(
93+
level_filter,
94+
Config::default(),
95+
File::create("lintcheck-logs/lintcheck.log").unwrap(),
96+
),
97+
]);
6998

7099
// first, check if we got anything passed via the LINTCHECK_TOML env var,
71100
// if not, ask clap if we got any value for --crates-toml <foo>
@@ -84,7 +113,7 @@ impl LintcheckConfig {
84113
// wasd.toml, use "wasd"...)
85114
let filename: PathBuf = sources_toml_path.file_stem().unwrap().into();
86115
let lintcheck_results_path = PathBuf::from(format!(
87-
"lintcheck-logs/{}_logs.{}",
116+
"lintcheck-logs/{}_results.{}",
88117
filename.display(),
89118
if markdown { "md" } else { "txt" }
90119
));

lintcheck/src/main.rs

+17-17
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ use std::time::Duration;
2828

2929
use cargo_metadata::diagnostic::{Diagnostic, DiagnosticLevel};
3030
use cargo_metadata::Message;
31+
use log::{debug, error, trace, warn};
3132
use rayon::prelude::*;
3233
use serde::{Deserialize, Serialize};
3334
use walkdir::{DirEntry, WalkDir};
@@ -163,10 +164,10 @@ fn get(path: &str) -> Result<ureq::Response, ureq::Error> {
163164
match ureq::get(path).call() {
164165
Ok(res) => return Ok(res),
165166
Err(e) if retries >= MAX_RETRIES => return Err(e),
166-
Err(ureq::Error::Transport(e)) => eprintln!("Error: {e}"),
167+
Err(ureq::Error::Transport(e)) => error!("{}", e),
167168
Err(e) => return Err(e),
168169
}
169-
eprintln!("retrying in {retries} seconds...");
170+
warn!("retrying in {retries} seconds...");
170171
thread::sleep(Duration::from_secs(u64::from(retries)));
171172
retries += 1;
172173
}
@@ -234,7 +235,7 @@ impl CrateSource {
234235
.expect("Failed to clone git repo!")
235236
.success()
236237
{
237-
eprintln!("Failed to clone {url} into {}", repo_path.display());
238+
warn!("Failed to clone {url} into {}", repo_path.display());
238239
}
239240
}
240241
// check out the commit/branch/whatever
@@ -247,7 +248,7 @@ impl CrateSource {
247248
.expect("Failed to check out commit")
248249
.success()
249250
{
250-
eprintln!("Failed to checkout {commit} of repo at {}", repo_path.display());
251+
warn!("Failed to checkout {commit} of repo at {}", repo_path.display());
251252
}
252253

253254
Crate {
@@ -390,6 +391,8 @@ impl Crate {
390391

391392
cargo_clippy_args.extend(clippy_args);
392393

394+
debug!("Arguments passed to cargo clippy driver: {:?}", cargo_clippy_args);
395+
393396
let all_output = Command::new(&cargo_clippy_path)
394397
// use the looping index to create individual target dirs
395398
.env("CARGO_TARGET_DIR", shared_target_dir.join(format!("_{thread_index:?}")))
@@ -409,21 +412,19 @@ impl Crate {
409412
let status = &all_output.status;
410413

411414
if !status.success() {
412-
eprintln!(
413-
"\nWARNING: bad exit status after checking {} {} \n",
414-
self.name, self.version
415-
);
415+
warn!("bad exit status after checking {} {} \n", self.name, self.version);
416416
}
417417

418418
if config.fix {
419+
trace!("{}", stderr);
419420
if let Some(stderr) = stderr
420421
.lines()
421422
.find(|line| line.contains("failed to automatically apply fixes suggested by rustc to crate"))
422423
{
423424
let subcrate = &stderr[63..];
424-
println!(
425-
"ERROR: failed to apply some suggetion to {} / to (sub)crate {subcrate}",
426-
self.name
425+
error!(
426+
"failed to apply some suggetion to {} / to (sub)crate {}",
427+
self.name, subcrate
427428
);
428429
}
429430
// fast path, we don't need the warnings anyway
@@ -449,7 +450,7 @@ fn build_clippy() {
449450
.status()
450451
.expect("Failed to build clippy!");
451452
if !status.success() {
452-
eprintln!("Error: Failed to compile Clippy!");
453+
error!("Failed to compile Clippy!");
453454
std::process::exit(1);
454455
}
455456
}
@@ -553,7 +554,7 @@ fn main() {
553554

554555
// assert that we launch lintcheck from the repo root (via cargo lintcheck)
555556
if std::fs::metadata("lintcheck/Cargo.toml").is_err() {
556-
eprintln!("lintcheck needs to be run from clippy's repo root!\nUse `cargo lintcheck` alternatively.");
557+
error!("lintcheck needs to be run from clippy's repo root!\nUse `cargo lintcheck` alternatively.");
557558
std::process::exit(3);
558559
}
559560

@@ -615,8 +616,8 @@ fn main() {
615616
.collect();
616617

617618
if crates.is_empty() {
618-
eprintln!(
619-
"ERROR: could not find crate '{}' in lintcheck/lintcheck_crates.toml",
619+
error!(
620+
"could not find crate '{}' in lintcheck/lintcheck_crates.toml",
620621
config.only.unwrap(),
621622
);
622623
std::process::exit(1);
@@ -693,8 +694,7 @@ fn main() {
693694
let _ = write!(text, "{cratename}: '{msg}'");
694695
}
695696

696-
println!("Writing logs to {}", config.lintcheck_results_path.display());
697-
fs::create_dir_all(config.lintcheck_results_path.parent().unwrap()).unwrap();
697+
println!("Writing results to {}", config.lintcheck_results_path.display());
698698
fs::write(&config.lintcheck_results_path, text).unwrap();
699699

700700
print_stats(old_stats, new_stats, &config.lint_filter);

0 commit comments

Comments
 (0)