Skip to content

Commit 1679a4f

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 600816f commit 1679a4f

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
}
@@ -246,7 +247,7 @@ impl CrateSource {
246247
.expect("Failed to clone git repo!")
247248
.success()
248249
{
249-
eprintln!("Failed to clone {url} into {}", repo_path.display());
250+
warn!("Failed to clone {url} into {}", repo_path.display());
250251
}
251252
}
252253
// check out the commit/branch/whatever
@@ -259,7 +260,7 @@ impl CrateSource {
259260
.expect("Failed to check out commit")
260261
.success()
261262
{
262-
eprintln!("Failed to checkout {commit} of repo at {}", repo_path.display());
263+
warn!("Failed to checkout {commit} of repo at {}", repo_path.display());
263264
}
264265

265266
Crate {
@@ -407,6 +408,8 @@ impl Crate {
407408

408409
cargo_clippy_args.extend(clippy_args);
409410

411+
debug!("Arguments passed to cargo clippy driver: {:?}", cargo_clippy_args);
412+
410413
let all_output = Command::new(&cargo_clippy_path)
411414
// use the looping index to create individual target dirs
412415
.env("CARGO_TARGET_DIR", shared_target_dir.join(format!("_{thread_index:?}")))
@@ -427,21 +430,19 @@ impl Crate {
427430
let status = &all_output.status;
428431

429432
if !status.success() {
430-
eprintln!(
431-
"\nWARNING: bad exit status after checking {} {} \n",
432-
self.name, self.version
433-
);
433+
warn!("bad exit status after checking {} {} \n", self.name, self.version);
434434
}
435435

436436
if config.fix {
437+
trace!("{}", stderr);
437438
if let Some(stderr) = stderr
438439
.lines()
439440
.find(|line| line.contains("failed to automatically apply fixes suggested by rustc to crate"))
440441
{
441442
let subcrate = &stderr[63..];
442-
println!(
443-
"ERROR: failed to apply some suggetion to {} / to (sub)crate {subcrate}",
444-
self.name
443+
error!(
444+
"failed to apply some suggetion to {} / to (sub)crate {}",
445+
self.name, subcrate
445446
);
446447
}
447448
// fast path, we don't need the warnings anyway
@@ -467,7 +468,7 @@ fn build_clippy() {
467468
.status()
468469
.expect("Failed to build clippy!");
469470
if !status.success() {
470-
eprintln!("Error: Failed to compile Clippy!");
471+
error!("Failed to compile Clippy!");
471472
std::process::exit(1);
472473
}
473474
}
@@ -571,7 +572,7 @@ fn main() {
571572

572573
// assert that we launch lintcheck from the repo root (via cargo lintcheck)
573574
if std::fs::metadata("lintcheck/Cargo.toml").is_err() {
574-
eprintln!("lintcheck needs to be run from clippy's repo root!\nUse `cargo lintcheck` alternatively.");
575+
error!("lintcheck needs to be run from clippy's repo root!\nUse `cargo lintcheck` alternatively.");
575576
std::process::exit(3);
576577
}
577578

@@ -633,8 +634,8 @@ fn main() {
633634
.collect();
634635

635636
if crates.is_empty() {
636-
eprintln!(
637-
"ERROR: could not find crate '{}' in lintcheck/lintcheck_crates.toml",
637+
error!(
638+
"could not find crate '{}' in lintcheck/lintcheck_crates.toml",
638639
config.only.unwrap(),
639640
);
640641
std::process::exit(1);
@@ -711,8 +712,7 @@ fn main() {
711712
let _ = write!(text, "{cratename}: '{msg}'");
712713
}
713714

714-
println!("Writing logs to {}", config.lintcheck_results_path.display());
715-
fs::create_dir_all(config.lintcheck_results_path.parent().unwrap()).unwrap();
715+
println!("Writing results to {}", config.lintcheck_results_path.display());
716716
fs::write(&config.lintcheck_results_path, text).unwrap();
717717

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

0 commit comments

Comments
 (0)