Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(timber): prettier logs #263

Merged
merged 1 commit into from
Feb 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/timber/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ authors = ["Apollo Developers <opensource@apollographql.com>"]
edition = "2018"

[dependencies]
atty = "0.2.14"
serde = "1"
tracing-core = "0.1"
# the parking_lot feature uses a more performant mutex than std::sync::Mutex
tracing-subscriber = { version = "0.2", features = [ "ansi", "fmt", "parking_lot" ] }
tracing-subscriber = { version = "0.2", features = ["ansi", "fmt", "parking_lot"] }
26 changes: 0 additions & 26 deletions crates/timber/src/formatter.rs

This file was deleted.

38 changes: 16 additions & 22 deletions crates/timber/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,40 @@
//! Defines the output format of traces, events, and spans produced
//! by `env_logger`, `log`, and/or `tracing`.

mod formatter;
use std::io;
use tracing_subscriber::fmt;

pub use tracing_core::Level;

/// possible log levels
pub const LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"];

#[cfg(debug_assertions)]
/// default log level for debug builds
pub const DEFAULT_LEVEL: &str = "debug";

#[cfg(not(debug_assertions))]
/// default log level for debug builds
pub const DEFAULT_LEVEL: &str = "info";

/// Initializes a global tracing subscriber that formats
/// all logs produced by an application that calls init,
/// and all logs produced by libraries consumed by that application.
pub fn init(level: Level) {
match level {
// default subscriber for released code
Level::ERROR | Level::WARN | Level::INFO => formatter::least_verbose(level),
// default subscriber for debug code
Level::DEBUG => formatter::verbose(level),
// extra verbose subscriber
Level::TRACE => formatter::very_verbose(level),
pub fn init(level: Option<Level>) {
// by default, no logs are printed.
if let Some(level) = level {
let format = fmt::format().without_time().pretty();
fmt()
.with_max_level(level)
.event_format(format)
.with_writer(io::stderr)
.init();
}
}

#[cfg(test)]
mod tests {
use tracing_core::metadata::ParseLevelError;

use super::{Level, LEVELS};
use std::error::Error;
use std::str::FromStr;

#[test]
fn it_parses_all_possible_levels() -> Result<(), Box<dyn Error>> {
fn it_parses_all_possible_levels() -> Result<(), ParseLevelError> {
for level in &LEVELS {
if let Err(e) = Level::from_str(&level) {
return Err(e.into());
}
Level::from_str(&level)?;
}
Ok(())
}
Expand Down
10 changes: 5 additions & 5 deletions installers/binstall/src/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ impl Installer {
return Ok(None);
}

tracing::info!("creating directory for binary");
tracing::debug!("Creating directory for binary");
self.create_bin_dir()?;

tracing::info!("writing binary to {}", &bin_destination.display());
eprintln!("Writing binary to {}", &bin_destination.display());
self.write_bin_to_fs()?;

tracing::info!("adding binary to PATH");
tracing::debug!("Adding binary to PATH");
self.add_binary_to_path()?;

Ok(Some(bin_destination))
Expand Down Expand Up @@ -86,12 +86,12 @@ impl Installer {

// It looks like we're at an interactive prompt, so ask the user if they'd
// like to overwrite the previous installation.
tracing::info!(
eprintln!(
"existing {} installation found at `{}`",
&self.binary_name,
destination.display()
);
tracing::info!("Would you like to overwrite this file? [y/N]: ");
eprintln!("Would you like to overwrite this file? [y/N]: ");
let mut line = String::new();
io::stdin().read_line(&mut line)?;

Expand Down
9 changes: 9 additions & 0 deletions out.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
+--------+-------------+----------------------------+
EverlastingBugstopper marked this conversation as resolved.
Show resolved Hide resolved
| Name | Routing Url | Last Updated |
+--------+-------------+----------------------------+
| films | N/A | 2020-12-18 12:26:10 -06:00 |
+--------+-------------+----------------------------+
| people | N/A | 2020-12-18 12:25:44 -06:00 |
+--------+-------------+----------------------------+

View full details at https://studio.apollographql.com/graph/averys-federated-graph/service-list
6 changes: 3 additions & 3 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::utils::{
use crate::Result;
use config::Config;
use houston as config;
use timber::{Level, DEFAULT_LEVEL, LEVELS};
use timber::{Level, LEVELS};

use std::path::PathBuf;

Expand Down Expand Up @@ -39,9 +39,9 @@ pub struct Rover {
#[structopt(subcommand)]
pub command: Command,

#[structopt(long = "log", short = "l", global = true, default_value = DEFAULT_LEVEL, possible_values = &LEVELS, case_insensitive = true)]
#[structopt(long = "log", short = "l", global = true, possible_values = &LEVELS, case_insensitive = true)]
#[serde(serialize_with = "from_display")]
pub log_level: Level,
pub log_level: Option<Level>,

#[structopt(skip)]
#[serde(skip_serializing)]
Expand Down
10 changes: 6 additions & 4 deletions src/command/config/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,23 @@ impl Auth {
let api_key = api_key_prompt()?;
Profile::set_api_key(&self.profile_name, &config, &api_key)?;
Profile::get_api_key(&self.profile_name, &config).map(|_| {
tracing::info!("Successfully saved API key.");
eprintln!("Successfully saved API key.");
})?;
Ok(RoverStdout::None)
}
}

fn api_key_prompt() -> Result<String> {
let term = console::Term::stdout();
tracing::info!(
let term = console::Term::stderr();
eprintln!(
"Go to {} and create a new Personal API Key.",
Cyan.normal()
.paint("https://studio.apollographql.com/user-settings")
);
tracing::info!("Copy the key and paste it into the prompt below.");

eprintln!("Copy the key and paste it into the prompt below.");
term.write_str("> ")?;

let api_key = term.read_secure_line()?;
if is_valid(&api_key) {
Ok(api_key)
Expand Down
2 changes: 1 addition & 1 deletion src/command/config/clear.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub struct Clear {}
impl Clear {
pub fn run(&self, config: config::Config) -> Result<RoverStdout> {
config.clear()?;
tracing::info!("Successfully cleared all configuration.");
eprintln!("Successfully cleared all configuration.");
Ok(RoverStdout::None)
}
}
2 changes: 1 addition & 1 deletion src/command/config/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub struct Delete {
impl Delete {
pub fn run(&self, config: config::Config) -> Result<RoverStdout> {
config::Profile::delete(&self.name, &config)?;
tracing::info!("Successfully deleted profile \"{}\"", &self.name);
eprintln!("Successfully deleted profile \"{}\"", &self.name);
Ok(RoverStdout::None)
}
}
10 changes: 1 addition & 9 deletions src/command/config/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,6 @@ pub struct List {}
impl List {
pub fn run(&self, config: config::Config) -> Result<RoverStdout> {
let profiles = config::Profile::list(&config)?;
if profiles.is_empty() {
tracing::info!("No profiles found.")
} else {
tracing::info!("Profiles:");
for profile in profiles {
tracing::info!("{}", profile);
}
}
Ok(RoverStdout::None)
Ok(RoverStdout::Profiles(profiles))
}
}
2 changes: 1 addition & 1 deletion src/command/config/show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl Show {

let profile = config::Profile::load(&self.name, &config, opts)?;

tracing::info!("{}: {}", &self.name, profile);
eprintln!("{}: {}", &self.name, profile);
Ok(RoverStdout::None)
}
}
8 changes: 3 additions & 5 deletions src/command/config/whoami.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,13 @@ pub struct WhoAmI {
impl WhoAmI {
pub fn run(&self, client_config: StudioClientConfig) -> Result<RoverStdout> {
let client = client_config.get_client(&self.profile_name)?;
tracing::info!("Checking identity of your API key against the registry...",);
eprintln!("Checking identity of your API key against the registry.");

let identity = whoami::run(whoami::who_am_i_query::Variables {}, &client)?;

tracing::info!(
eprintln!(
"Key Info:\n- Name: {}\n- ID: {}\n- Key Type: {:?}",
identity.name,
identity.id,
identity.key_actor_type
identity.name, identity.id, identity.key_actor_type
);
Ok(RoverStdout::None)
}
Expand Down
7 changes: 3 additions & 4 deletions src/command/graph/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl Check {
&client,
)?;

tracing::info!(
eprintln!(
"Validated the proposed subgraph against metrics from {}",
&self.graph
);
Expand All @@ -89,13 +89,12 @@ impl Check {
_ => format!("Compared {} schema changes against {} operations", res.changes.len(), res.number_of_checked_operations),
};

tracing::info!("{}", &msg);
eprintln!("{}", &msg);

let num_failures = print_changes(&res.changes);

if let Some(url) = res.target_url {
tracing::info!("View full details here");
tracing::info!("{}", url.to_string());
eprintln!("View full details at {}", &url);
}

match num_failures {
Expand Down
2 changes: 1 addition & 1 deletion src/command/graph/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl Fetch {
pub fn run(&self, client_config: StudioClientConfig) -> Result<RoverStdout> {
let client = client_config.get_client(&self.profile_name)?;
let graph_ref = self.graph.to_string();
tracing::info!(
eprintln!(
"Fetching SDL from {} using credentials from the {} profile.",
Cyan.normal().paint(&graph_ref),
Yellow.normal().paint(&self.profile_name)
Expand Down
10 changes: 4 additions & 6 deletions src/command/graph/push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ impl Push {
) -> Result<RoverStdout> {
let client = client_config.get_client(&self.profile_name)?;
let graph_ref = self.graph.to_string();
tracing::info!(
eprintln!(
"Pushing SDL to {} using credentials from the {} profile.",
Cyan.normal().paint(&graph_ref),
Yellow.normal().paint(&self.profile_name)
);

let schema_document = load_schema_from_flag(&self.schema, std::io::stdin())?;

tracing::debug!("Schema Document to push:\n{}", &schema_document);
tracing::debug!(?schema_document);

let push_response = push::run(
push::push_schema_mutation::Variables {
Expand All @@ -66,11 +66,9 @@ impl Push {

/// handle all output logging from operation
fn handle_response(graph: &GraphRef, response: push::PushResponse) -> String {
tracing::info!(
eprintln!(
"{}#{} Pushed successfully {}",
graph,
response.schema_hash,
response.change_summary
graph, response.schema_hash, response.change_summary
);

response.schema_hash
Expand Down
7 changes: 2 additions & 5 deletions src/command/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,9 @@ impl Info {
Err(_) => "Unknown".to_string(),
};

tracing::info!(
eprintln!(
"Rover Info:\nVersion: {}\nInstall Location: {}\nOS: {}\nShell: {}",
version,
location,
os,
shell
version, location, os, shell
);

Ok(RoverStdout::None)
Expand Down
4 changes: 2 additions & 2 deletions src/command/install/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ impl Install {
.with_context(|| format!("could not install {}", &binary_name))?;

if let Some(install_location) = install_location {
tracing::info!("{} was successfully installed to `{}`. You may need to reload your terminal for the binary to be loaded into your PATH.", &binary_name, install_location.display())
eprintln!("{} was successfully installed to `{}`. You may need to reload your terminal for the binary to be loaded into your PATH.", &binary_name, install_location.display())
} else {
tracing::info!("{} was not installed. To override the existing installation, you can pass the `--force` flag to the installer.", &binary_name);
eprintln!("{} was not installed. To override the existing installation, you can pass the `--force` flag to the installer.", &binary_name);
}
Ok(RoverStdout::None)
} else {
Expand Down
Loading