Skip to content

Commit 8ce91eb

Browse files
authored
Merge pull request #5518 from Turbo87/tracing-calls
Migrate more `println!()` calls to use `tracing` instead
2 parents e640480 + de6edae commit 8ce91eb

File tree

9 files changed

+44
-40
lines changed

9 files changed

+44
-40
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

cargo-registry-index/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,6 @@ dotenv = "=0.15.0"
2020
git2 = "=0.15.0"
2121
serde = { version = "=1.0.147", features = ["derive"] }
2222
tempfile = "=3.3.0"
23+
tracing = "=0.1.37"
2324
url = "=2.3.1"
2425
serde_json = { version = "=1.0.89", optional = true }

cargo-registry-index/lib.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#[macro_use]
22
extern crate serde;
3+
#[macro_use]
4+
extern crate tracing;
35

46
#[cfg(feature = "testing")]
57
pub mod testing;
@@ -177,10 +179,8 @@ impl RepositoryConfig {
177179
match (username, password, http_url, ssh_key, ssh_url) {
178180
(extra_user, extra_pass, extra_http_url, Ok(encoded_key), Ok(ssh_url)) => {
179181
if let (Ok(_), Ok(_), Ok(_)) = (extra_user, extra_pass, extra_http_url) {
180-
println!(
181-
"warning: both http and ssh credentials to authenticate with git are set"
182-
);
183-
println!("note: ssh credentials will take precedence over the http ones");
182+
warn!("both http and ssh credentials to authenticate with git are set");
183+
info!("note: ssh credentials will take precedence over the http ones");
184184
}
185185

186186
let index_location =
@@ -439,13 +439,13 @@ impl Repository {
439439
/// This function also prints the commit message and a success or failure
440440
/// message to the console.
441441
pub fn commit_and_push(&self, message: &str, modified_file: &Path) -> anyhow::Result<()> {
442-
println!("Committing and pushing \"{message}\"");
442+
info!("Committing and pushing \"{message}\"");
443443

444444
let relative_path = modified_file.strip_prefix(self.checkout_path.path())?;
445445
self.perform_commit_and_push(message, relative_path)
446-
.map(|_| println!("Commit and push finished for \"{message}\""))
446+
.map(|_| info!("Commit and push finished for \"{message}\""))
447447
.map_err(|err| {
448-
eprintln!("Commit and push for \"{message}\" errored: {err}");
448+
error!(?err, "Commit and push for \"{message}\" errored");
449449
err
450450
})
451451
}
@@ -467,7 +467,7 @@ impl Repository {
467467
let head = self.head_oid()?;
468468

469469
if head != original_head {
470-
println!("Resetting index from {original_head} to {head}");
470+
info!("Resetting index from {original_head} to {head}");
471471
}
472472

473473
let obj = self.repository.find_object(head, None)?;

src/admin/migrate.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ pub fn run(_opts: Opts) -> Result<(), Error> {
2323
// TODO: Check `any_pending_migrations()` with a read-only connection and error if true.
2424
// It looks like this requires changes upstream to make this pub in `migration_macros`.
2525

26-
println!("==> Skipping migrations and category sync (read-only mode)");
26+
warn!("Skipping migrations and category sync (read-only mode)");
2727

2828
// The service is undergoing maintenance or mitigating an outage.
2929
// Exit with success to ensure configuration changes can be made.
@@ -34,10 +34,10 @@ pub fn run(_opts: Opts) -> Result<(), Error> {
3434
// The primary is online, access directly via `DATABASE_URL`.
3535
let conn = crate::db::oneoff_connection_with_config(&config)?;
3636

37-
println!("==> migrating the database");
37+
info!("Migrating the database");
3838
embedded_migrations::run_with_output(&conn, &mut std::io::stdout())?;
3939

40-
println!("==> synchronizing crate categories");
40+
info!("Synchronizing crate categories");
4141
crate::boot::categories::sync_with_connection(CATEGORIES_TOML, &conn).unwrap();
4242

4343
Ok(())

src/bin/background-worker.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
1313
#![warn(clippy::all, rust_2018_idioms)]
1414

15+
#[macro_use]
16+
extern crate tracing;
17+
1518
use cargo_registry::config;
1619
use cargo_registry::worker::cloudfront::CloudFront;
1720
use cargo_registry::{background_jobs::*, db};
@@ -23,19 +26,19 @@ use std::thread::sleep;
2326
use std::time::Duration;
2427

2528
fn main() {
26-
println!("Booting runner");
27-
2829
let _sentry = cargo_registry::sentry::init();
2930

3031
// Initialize logging
3132
cargo_registry::util::tracing::init();
3233

34+
info!("Booting runner");
35+
3336
let config = config::Server::default();
3437
let uploader = config.base.uploader();
3538

3639
if config.db.are_all_read_only() {
3740
loop {
38-
println!(
41+
warn!(
3942
"Cannot run background jobs with a read-only pool. Please scale background_worker \
4043
to 0 processes until the leader database is available."
4144
);
@@ -50,13 +53,13 @@ fn main() {
5053
.parse()
5154
.expect("Invalid value for `BACKGROUND_JOB_TIMEOUT`");
5255

53-
println!("Cloning index");
56+
info!("Cloning index");
5457

5558
let repository_config = RepositoryConfig::from_environment();
5659
let repository = Arc::new(Mutex::new(
5760
Repository::open(&repository_config).expect("Failed to clone index"),
5861
));
59-
println!("Index cloned");
62+
info!("Index cloned");
6063

6164
let cloudfront = CloudFront::from_environment();
6265

@@ -79,18 +82,15 @@ fn main() {
7982
};
8083
let mut runner = build_runner();
8184

82-
println!("Runner booted, running jobs");
85+
info!("Runner booted, running jobs");
8386

8487
let mut failure_count = 0;
8588

8689
loop {
8790
if let Err(e) = runner.run_all_pending_jobs() {
8891
failure_count += 1;
8992
if failure_count < 5 {
90-
eprintln!(
91-
"Error running jobs (n = {}) -- retrying: {:?}",
92-
failure_count, e,
93-
);
93+
warn!(?failure_count, err = ?e, "Error running jobs -- retrying");
9494
runner = build_runner();
9595
} else {
9696
panic!("Failed to begin running jobs 5 times. Restarting the process");

src/bin/server.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
#![warn(clippy::all, rust_2018_idioms)]
22

3+
#[macro_use]
4+
extern crate tracing;
5+
36
use cargo_registry::{env_optional, metrics::LogEncoder, util::errors::AppResult, App, Env};
47
use std::{fs::File, process::Command, sync::Arc, time::Duration};
58

@@ -8,7 +11,6 @@ use futures_util::future::FutureExt;
811
use prometheus::Encoder;
912
use reqwest::blocking::Client;
1013
use std::io::{self, Write};
11-
use tokio::io::AsyncWriteExt;
1214
use tokio::signal::unix::{signal, SignalKind};
1315

1416
const CORE_THREADS: usize = 4;
@@ -85,18 +87,16 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
8587
_ = sig_int.recv().fuse() => {},
8688
_ = sig_term.recv().fuse() => {},
8789
};
88-
tokio::io::stdout()
89-
.write_all(b"Starting graceful shutdown\n")
90-
.await
91-
.ok();
90+
91+
info!("Starting graceful shutdown");
9292
});
9393

9494
Ok::<_, io::Error>((addr, server))
9595
})?;
9696

9797
// Do not change this line! Removing the line or changing its contents in any way will break
9898
// the test suite :)
99-
println!("Listening at http://{addr}");
99+
info!("Listening at http://{addr}");
100100

101101
// Creating this file tells heroku to tell nginx that the application is ready
102102
// to receive traffic.
@@ -106,7 +106,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
106106
} else {
107107
"/tmp/app-initialized"
108108
};
109-
println!("Writing to {path}");
109+
info!("Writing to {path}");
110110
File::create(path).unwrap();
111111

112112
// Launch nginx via the Heroku nginx buildpack
@@ -120,13 +120,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
120120
// Block the main thread until the server has shutdown
121121
rt.block_on(server)?;
122122

123-
println!("Persisting remaining downloads counters");
123+
info!("Persisting remaining downloads counters");
124124
match app.downloads_counter.persist_all_shards(&app) {
125125
Ok(stats) => stats.log(),
126-
Err(err) => println!("downloads_counter error: {err}"),
126+
Err(err) => error!(?err, "downloads_counter error"),
127127
}
128128

129-
println!("Server has gracefully shutdown!");
129+
info!("Server has gracefully shutdown!");
130130
Ok(())
131131
}
132132

@@ -140,7 +140,7 @@ fn downloads_counter_thread(app: Arc<App>) {
140140

141141
match app.downloads_counter.persist_next_shard(&app) {
142142
Ok(stats) => stats.log(),
143-
Err(err) => println!("downloads_counter error: {err}"),
143+
Err(err) => error!(?err, "downloads_counter error"),
144144
}
145145
});
146146
}
@@ -155,7 +155,7 @@ fn log_instance_metrics_thread(app: Arc<App>) {
155155

156156
std::thread::spawn(move || loop {
157157
if let Err(err) = log_instance_metrics_inner(&app) {
158-
eprintln!("log_instance_metrics error: {err}");
158+
error!(?err, "log_instance_metrics error");
159159
}
160160
std::thread::sleep(interval);
161161
});

src/config/base.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,13 @@ impl Base {
3838
// for the related S3 environment variables and configure the app to upload to
3939
// and read from S3 like production does. All values except for bucket are
4040
// optional, like production read-only mirrors.
41-
println!("Using S3 uploader");
41+
info!("Using S3 uploader");
4242
Self::s3_maybe_read_only()
4343
} else {
4444
// If we don't set the `S3_BUCKET` variable, we'll use a development-only
4545
// uploader that makes it possible to run and publish to a locally-running
4646
// crates.io instance without needing to set up an account and a bucket in S3.
47-
println!(
47+
info!(
4848
"Using local uploader, crate files will be in the local_uploads directory"
4949
);
5050
Uploader::Local

src/middleware.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,10 @@ pub fn build_middleware(app: Arc<App>, endpoints: RouteBuilder) -> MiddlewareBui
9090
if let Ok(capacity) = env::var("DB_PRIMARY_POOL_SIZE") {
9191
if let Ok(capacity) = capacity.parse() {
9292
if capacity >= 10 {
93-
println!("Enabling BalanceCapacity middleware with {capacity} pool capacity");
93+
info!(?capacity, "Enabling BalanceCapacity middleware");
9494
m.around(balance_capacity::BalanceCapacity::new(capacity))
9595
} else {
96-
println!(
97-
"BalanceCapacity middleware not enabled. DB_PRIMARY_POOL_SIZE is too low."
98-
);
96+
info!("BalanceCapacity middleware not enabled. DB_PRIMARY_POOL_SIZE is too low.");
9997
}
10098
}
10199
}

src/tests/server_binary.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ impl ServerBin {
123123
let mut process = Command::new(env!("CARGO_BIN_EXE_server"))
124124
.env_clear()
125125
.envs(self.env.into_iter())
126+
.env("RUST_LOG", "info")
126127
.stdout(Stdio::piped())
127128
.stderr(Stdio::piped())
128129
.spawn()?;
@@ -199,7 +200,10 @@ where
199200
// If we expect the port number to be logged into this stream, look for it and send it
200201
// over the channel as soon as it's found.
201202
if let Some(port_send) = &port_send {
202-
if let Some(url) = line.strip_prefix("Listening at ") {
203+
let pattern = "Listening at ";
204+
if let Some(idx) = line.find(pattern) {
205+
let start = idx + pattern.len();
206+
let url = &line[start..];
203207
let url = Url::parse(url).unwrap();
204208
let port = url.port().unwrap();
205209
port_send

0 commit comments

Comments
 (0)