Skip to content

Commit 9536744

Browse files
committed
Merge torrust#1022: Improve Tracing Part One
14e672e tracing: add spans to many functions (Cameron Garnham) 3dc75d5 tracing: init tracing-subscriber in intragration tests (Cameron Garnham) e4aa1db tracing: qualify use of tracing macros (Cameron Garnham) Pull request description: make better use of the modern features in the `tracing` library, first part. ACKs for top commit: da2ce7: ACK 14e672e Tree-SHA512: 3c913a1e7ea6ad5d088bdb08bd17bb30ff93e56fd37744e66fb869bca9870a0a019a2b1a29f56839cb6fe37f14afec27adce7ef5a81d3a58dd1eac13c563fe2b
2 parents 06857d2 + 14e672e commit 9536744

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+807
-186
lines changed

packages/located-error/src/lib.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@ use std::error::Error;
3333
use std::panic::Location;
3434
use std::sync::Arc;
3535

36-
use tracing::debug;
37-
3836
pub type DynError = Arc<dyn std::error::Error + Send + Sync>;
3937

4038
/// A generic wrapper around an error.
@@ -94,7 +92,7 @@ where
9492
source: Arc::new(self.0),
9593
location: Box::new(*std::panic::Location::caller()),
9694
};
97-
debug!("{e}");
95+
tracing::debug!("{e}");
9896
e
9997
}
10098
}

packages/test-helpers/src/configuration.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ pub fn ephemeral() -> Configuration {
2828

2929
let mut config = Configuration::default();
3030

31-
config.logging.threshold = Threshold::Off; // Change to `debug` for tests debugging
31+
config.logging.threshold = Threshold::Off; // It should always be off here, the tests manage their own logging.
3232

3333
// Ephemeral socket address for API
3434
let api_port = 0u16;

src/app.rs

+7-6
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use std::sync::Arc;
2525

2626
use tokio::task::JoinHandle;
2727
use torrust_tracker_configuration::Configuration;
28-
use tracing::{info, warn};
28+
use tracing::instrument;
2929

3030
use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker};
3131
use crate::servers::registar::Registar;
@@ -37,12 +37,13 @@ use crate::{core, servers};
3737
///
3838
/// - Can't retrieve tracker keys from database.
3939
/// - Can't load whitelist from database.
40+
#[instrument(skip(config, tracker))]
4041
pub async fn start(config: &Configuration, tracker: Arc<core::Tracker>) -> Vec<JoinHandle<()>> {
4142
if config.http_api.is_none()
4243
&& (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty))
4344
&& (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty))
4445
{
45-
warn!("No services enabled in configuration");
46+
tracing::warn!("No services enabled in configuration");
4647
}
4748

4849
let mut jobs: Vec<JoinHandle<()>> = Vec::new();
@@ -69,7 +70,7 @@ pub async fn start(config: &Configuration, tracker: Arc<core::Tracker>) -> Vec<J
6970
if let Some(udp_trackers) = &config.udp_trackers {
7071
for udp_tracker_config in udp_trackers {
7172
if tracker.is_private() {
72-
warn!(
73+
tracing::warn!(
7374
"Could not start UDP tracker on: {} while in private mode. UDP is not safe for private trackers!",
7475
udp_tracker_config.bind_address
7576
);
@@ -78,7 +79,7 @@ pub async fn start(config: &Configuration, tracker: Arc<core::Tracker>) -> Vec<J
7879
}
7980
}
8081
} else {
81-
info!("No UDP blocks in configuration");
82+
tracing::info!("No UDP blocks in configuration");
8283
}
8384

8485
// Start the HTTP blocks
@@ -96,7 +97,7 @@ pub async fn start(config: &Configuration, tracker: Arc<core::Tracker>) -> Vec<J
9697
};
9798
}
9899
} else {
99-
info!("No HTTP blocks in configuration");
100+
tracing::info!("No HTTP blocks in configuration");
100101
}
101102

102103
// Start HTTP API
@@ -112,7 +113,7 @@ pub async fn start(config: &Configuration, tracker: Arc<core::Tracker>) -> Vec<J
112113
jobs.push(job);
113114
};
114115
} else {
115-
info!("No API block in configuration");
116+
tracing::info!("No API block in configuration");
116117
}
117118

118119
// Start runners to remove torrents without peers, every interval

src/bootstrap/app.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use std::sync::Arc;
1616
use torrust_tracker_clock::static_time;
1717
use torrust_tracker_configuration::validator::Validator;
1818
use torrust_tracker_configuration::Configuration;
19-
use tracing::info;
19+
use tracing::instrument;
2020

2121
use super::config::initialize_configuration;
2222
use crate::bootstrap;
@@ -30,6 +30,7 @@ use crate::shared::crypto::ephemeral_instance_keys;
3030
///
3131
/// Setup can file if the configuration is invalid.
3232
#[must_use]
33+
#[instrument(skip())]
3334
pub fn setup() -> (Configuration, Arc<Tracker>) {
3435
let configuration = initialize_configuration();
3536

@@ -39,7 +40,7 @@ pub fn setup() -> (Configuration, Arc<Tracker>) {
3940

4041
let tracker = initialize_with_configuration(&configuration);
4142

42-
info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json());
43+
tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json());
4344

4445
(configuration, tracker)
4546
}
@@ -48,6 +49,7 @@ pub fn setup() -> (Configuration, Arc<Tracker>) {
4849
///
4950
/// The configuration may be obtained from the environment (via config file or env vars).
5051
#[must_use]
52+
#[instrument(skip())]
5153
pub fn initialize_with_configuration(configuration: &Configuration) -> Arc<Tracker> {
5254
initialize_static();
5355
initialize_logging(configuration);
@@ -60,6 +62,7 @@ pub fn initialize_with_configuration(configuration: &Configuration) -> Arc<Track
6062
///
6163
/// - The time when the application started.
6264
/// - An ephemeral instance random seed. This seed is used for encryption and it's changed when the main application process is restarted.
65+
#[instrument(skip())]
6366
pub fn initialize_static() {
6467
// Set the time of Torrust app starting
6568
lazy_static::initialize(&static_time::TIME_AT_APP_START);
@@ -73,13 +76,15 @@ pub fn initialize_static() {
7376
/// The tracker is the domain layer service. It's the entrypoint to make requests to the domain layer.
7477
/// It's used by other higher-level components like the UDP and HTTP trackers or the tracker API.
7578
#[must_use]
79+
#[instrument(skip(config))]
7680
pub fn initialize_tracker(config: &Configuration) -> Tracker {
7781
tracker_factory(config)
7882
}
7983

8084
/// It initializes the log threshold, format and channel.
8185
///
8286
/// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging.
87+
#[instrument(skip(config))]
8388
pub fn initialize_logging(config: &Configuration) {
8489
bootstrap::logging::setup(config);
8590
}

src/bootstrap/jobs/health_check_api.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
use tokio::sync::oneshot;
1818
use tokio::task::JoinHandle;
1919
use torrust_tracker_configuration::HealthCheckApi;
20-
use tracing::info;
20+
use tracing::instrument;
2121

2222
use super::Started;
2323
use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET};
@@ -35,6 +35,8 @@ use crate::servers::signals::Halted;
3535
/// # Panics
3636
///
3737
/// It would panic if unable to send the `ApiServerJobStarted` notice.
38+
#[allow(clippy::async_yields_async)]
39+
#[instrument(skip(config, register))]
3840
pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> JoinHandle<()> {
3941
let bind_addr = config.bind_address;
4042

@@ -45,18 +47,18 @@ pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> Jo
4547

4648
// Run the API server
4749
let join_handle = tokio::spawn(async move {
48-
info!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting on: {protocol}://{}", bind_addr);
50+
tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting on: {protocol}://{}", bind_addr);
4951

5052
let handle = server::start(bind_addr, tx_start, rx_halt, register);
5153

5254
if let Ok(()) = handle.await {
53-
info!(target: HEALTH_CHECK_API_LOG_TARGET, "Stopped server running on: {protocol}://{}", bind_addr);
55+
tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "Stopped server running on: {protocol}://{}", bind_addr);
5456
}
5557
});
5658

5759
// Wait until the server sends the started message
5860
match rx_start.await {
59-
Ok(msg) => info!(target: HEALTH_CHECK_API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", msg.address),
61+
Ok(msg) => tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", msg.address),
6062
Err(e) => panic!("the Health Check API server was dropped: {e}"),
6163
}
6264

src/bootstrap/jobs/http_tracker.rs

+4
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use std::sync::Arc;
1616
use axum_server::tls_rustls::RustlsConfig;
1717
use tokio::task::JoinHandle;
1818
use torrust_tracker_configuration::HttpTracker;
19+
use tracing::instrument;
1920

2021
use super::make_rust_tls;
2122
use crate::core;
@@ -32,6 +33,7 @@ use crate::servers::registar::ServiceRegistrationForm;
3233
///
3334
/// It would panic if the `config::HttpTracker` struct would contain inappropriate values.
3435
///
36+
#[instrument(skip(config, tracker, form))]
3537
pub async fn start_job(
3638
config: &HttpTracker,
3739
tracker: Arc<core::Tracker>,
@@ -49,6 +51,8 @@ pub async fn start_job(
4951
}
5052
}
5153

54+
#[allow(clippy::async_yields_async)]
55+
#[instrument(skip(socket, tls, tracker, form))]
5256
async fn start_v1(
5357
socket: SocketAddr,
5458
tls: Option<RustlsConfig>,

src/bootstrap/jobs/mod.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ pub struct Started {
2020
pub address: std::net::SocketAddr,
2121
}
2222

23+
#[instrument(skip(opt_tsl_config))]
2324
pub async fn make_rust_tls(opt_tsl_config: &Option<TslConfig>) -> Option<Result<RustlsConfig, Error>> {
2425
match opt_tsl_config {
2526
Some(tsl_config) => {
@@ -32,8 +33,8 @@ pub async fn make_rust_tls(opt_tsl_config: &Option<TslConfig>) -> Option<Result<
3233
}));
3334
}
3435

35-
info!("Using https: cert path: {cert}.");
36-
info!("Using https: key path: {key}.");
36+
tracing::info!("Using https: cert path: {cert}.");
37+
tracing::info!("Using https: key path: {key}.");
3738

3839
Some(
3940
RustlsConfig::from_pem_file(cert, key)
@@ -89,7 +90,7 @@ use axum_server::tls_rustls::RustlsConfig;
8990
use thiserror::Error;
9091
use torrust_tracker_configuration::TslConfig;
9192
use torrust_tracker_located_error::{DynError, LocatedError};
92-
use tracing::info;
93+
use tracing::instrument;
9394

9495
/// Error returned by the Bootstrap Process.
9596
#[derive(Error, Debug)]

src/bootstrap/jobs/torrent_cleanup.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use std::sync::Arc;
1515
use chrono::Utc;
1616
use tokio::task::JoinHandle;
1717
use torrust_tracker_configuration::Core;
18-
use tracing::info;
18+
use tracing::instrument;
1919

2020
use crate::core;
2121

@@ -25,6 +25,7 @@ use crate::core;
2525
///
2626
/// Refer to [`torrust-tracker-configuration documentation`](https://docs.rs/torrust-tracker-configuration) for more info about that option.
2727
#[must_use]
28+
#[instrument(skip(config, tracker))]
2829
pub fn start_job(config: &Core, tracker: &Arc<core::Tracker>) -> JoinHandle<()> {
2930
let weak_tracker = std::sync::Arc::downgrade(tracker);
3031
let interval = config.inactive_peer_cleanup_interval;
@@ -37,15 +38,15 @@ pub fn start_job(config: &Core, tracker: &Arc<core::Tracker>) -> JoinHandle<()>
3738
loop {
3839
tokio::select! {
3940
_ = tokio::signal::ctrl_c() => {
40-
info!("Stopping torrent cleanup job..");
41+
tracing::info!("Stopping torrent cleanup job..");
4142
break;
4243
}
4344
_ = interval.tick() => {
4445
if let Some(tracker) = weak_tracker.upgrade() {
4546
let start_time = Utc::now().time();
46-
info!("Cleaning up torrents..");
47+
tracing::info!("Cleaning up torrents..");
4748
tracker.cleanup_torrents();
48-
info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds());
49+
tracing::info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds());
4950
} else {
5051
break;
5152
}

src/bootstrap/jobs/tracker_apis.rs

+4
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use std::sync::Arc;
2626
use axum_server::tls_rustls::RustlsConfig;
2727
use tokio::task::JoinHandle;
2828
use torrust_tracker_configuration::{AccessTokens, HttpApi};
29+
use tracing::instrument;
2930

3031
use super::make_rust_tls;
3132
use crate::core;
@@ -53,6 +54,7 @@ pub struct ApiServerJobStarted();
5354
/// It would panic if unable to send the `ApiServerJobStarted` notice.
5455
///
5556
///
57+
#[instrument(skip(config, tracker, form))]
5658
pub async fn start_job(
5759
config: &HttpApi,
5860
tracker: Arc<core::Tracker>,
@@ -72,6 +74,8 @@ pub async fn start_job(
7274
}
7375
}
7476

77+
#[allow(clippy::async_yields_async)]
78+
#[instrument(skip(socket, tls, tracker, form, access_tokens))]
7579
async fn start_v1(
7680
socket: SocketAddr,
7781
tls: Option<RustlsConfig>,

src/bootstrap/jobs/udp_tracker.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::sync::Arc;
1010

1111
use tokio::task::JoinHandle;
1212
use torrust_tracker_configuration::UdpTracker;
13-
use tracing::debug;
13+
use tracing::instrument;
1414

1515
use crate::core;
1616
use crate::servers::registar::ServiceRegistrationForm;
@@ -28,6 +28,8 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET;
2828
/// It will panic if it is unable to start the UDP service.
2929
/// It will panic if the task did not finish successfully.
3030
#[must_use]
31+
#[allow(clippy::async_yields_async)]
32+
#[instrument(skip(config, tracker, form))]
3133
pub async fn start_job(config: &UdpTracker, tracker: Arc<core::Tracker>, form: ServiceRegistrationForm) -> JoinHandle<()> {
3234
let bind_to = config.bind_address;
3335

@@ -37,8 +39,8 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc<core::Tracker>, form: S
3739
.expect("it should be able to start the udp tracker");
3840

3941
tokio::spawn(async move {
40-
debug!(target: UDP_TRACKER_LOG_TARGET, "Wait for launcher (UDP service) to finish ...");
41-
debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed());
42+
tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Wait for launcher (UDP service) to finish ...");
43+
tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed());
4244

4345
assert!(
4446
!server.state.halt_task.is_closed(),
@@ -51,6 +53,6 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc<core::Tracker>, form: S
5153
.await
5254
.expect("it should be able to join to the udp tracker task");
5355

54-
debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed());
56+
tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed());
5557
})
5658
}

src/bootstrap/logging.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
use std::sync::Once;
1515

1616
use torrust_tracker_configuration::{Configuration, Threshold};
17-
use tracing::info;
1817
use tracing::level_filters::LevelFilter;
1918

2019
static INIT: Once = Once::new();
@@ -54,7 +53,7 @@ fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) {
5453
TraceStyle::Json => builder.json().init(),
5554
};
5655

57-
info!("Logging initialized");
56+
tracing::info!("Logging initialized");
5857
}
5958

6059
#[derive(Debug)]

src/console/ci/e2e/docker.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ use std::process::{Command, Output};
44
use std::thread::sleep;
55
use std::time::{Duration, Instant};
66

7-
use tracing::{debug, info};
8-
97
/// Docker command wrapper.
108
pub struct Docker {}
119

@@ -20,7 +18,7 @@ impl Drop for RunningContainer {
2018
/// Ensures that the temporary container is stopped when the struct goes out
2119
/// of scope.
2220
fn drop(&mut self) {
23-
info!("Dropping running container: {}", self.name);
21+
tracing::info!("Dropping running container: {}", self.name);
2422
if Docker::is_container_running(&self.name) {
2523
let _unused = Docker::stop(self);
2624
}
@@ -89,7 +87,7 @@ impl Docker {
8987

9088
let args = [initial_args, env_var_args, port_args, [image.to_string()].to_vec()].concat();
9189

92-
debug!("Docker run args: {:?}", args);
90+
tracing::debug!("Docker run args: {:?}", args);
9391

9492
let output = Command::new("docker").args(args).output()?;
9593

@@ -176,7 +174,7 @@ impl Docker {
176174

177175
let output_str = String::from_utf8_lossy(&output.stdout);
178176

179-
info!("Waiting until container is healthy: {:?}", output_str);
177+
tracing::info!("Waiting until container is healthy: {:?}", output_str);
180178

181179
if output_str.contains("(healthy)") {
182180
return true;

0 commit comments

Comments
 (0)