Skip to content

Commit

Permalink
Fix --debug flag
Browse files Browse the repository at this point in the history
Currently the `--debug` flag does not actually enable debug logging as
intended. We initialize `env_logger` immediately in `main`, then attempt
to change the log filtering level in `NewCli::run` if the `--debug` flag
is passed. This does not work, as `env_logger::builder` needs its `init`
method to be called to change the global logger. This is not an option,
as we've already called `env_logger::init`. The internet suggests[0]
that using `log::set_max_level` lets us change the level independently
of logger initialization, but this did not work when I tried it out.

Move logger initialization into `NewCli::run` so that we know the
desired log level ahead of calling `init`. This means that items logged
before we initialize the logger will be lost, but in practice we're not
missing anything.

[0] rust-cli/env_logger#228 (comment)
  • Loading branch information
wfchandler committed Oct 14, 2024
1 parent ceafb75 commit 00719e5
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
4 changes: 3 additions & 1 deletion cli/src/cli_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,9 +229,11 @@ impl<'a> NewCli<'a> {
timeout,
} = OxideCli::from_arg_matches(&matches).unwrap();

let mut log_builder = env_logger::builder();
if debug {
env_logger::builder().filter_level(LevelFilter::Debug);
log_builder.filter_level(LevelFilter::Debug);
}
log_builder.init();

let mut client_config = ClientConfig::default();

Expand Down
2 changes: 0 additions & 2 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,6 @@ pub fn make_cli() -> NewCli<'static> {

#[tokio::main]
async fn main() {
env_logger::init();

let new_cli = make_cli();

// Spawn a task so we get this potentially chunky Future off the
Expand Down
20 changes: 20 additions & 0 deletions cli/tests/test_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,3 +568,23 @@ fn test_cmd_auth_status_env() {
));
oxide_mock.assert();
}

#[test]
fn test_cmd_auth_debug_logging() {
let server = MockServer::start();
let bad_url = "sys.oxide.invalid";

// Validate debug logs are printed
Command::cargo_bin("oxide")
.unwrap()
.env("OXIDE_HOST", server.url(""))
.env("OXIDE_TOKEN", "oxide-token-bad")
.arg("--debug")
.arg("auth")
.arg("login")
.arg("--host")
.arg(bad_url)
.assert()
.failure()
.stderr(str::contains("DEBUG"));
}

0 comments on commit 00719e5

Please sign in to comment.