Skip to content

Commit

Permalink
refactor: [torrust#884] move from log to tracing crate
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Jun 10, 2024
1 parent 3ccc0e4 commit 6e06b2e
Show file tree
Hide file tree
Showing 37 changed files with 112 additions and 141 deletions.
2 changes: 1 addition & 1 deletion packages/located-error/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use std::error::Error;
use std::panic::Location;
use std::sync::Arc;

use log::debug;
use tracing::debug;

pub type DynError = Arc<dyn std::error::Error + Send + Sync>;

Expand Down
2 changes: 1 addition & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@
//! - Tracker REST API: the tracker API can be enabled/disabled.
use std::sync::Arc;

use log::warn;
use tokio::task::JoinHandle;
use torrust_tracker_configuration::Configuration;
use tracing::warn;

use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker};
use crate::servers::registar::Registar;
Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap/jobs/health_check_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@
//! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration)
//! for the API configuration options.

use log::info;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use torrust_tracker_configuration::HealthCheckApi;
use tracing::info;

use super::Started;
use crate::servers::health_check_api::server;
Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap/jobs/http_tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ use std::net::SocketAddr;
use std::sync::Arc;

use axum_server::tls_rustls::RustlsConfig;
use log::info;
use tokio::task::JoinHandle;
use torrust_tracker_configuration::HttpTracker;
use tracing::info;

use super::make_rust_tls;
use crate::core;
Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap/jobs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ use std::panic::Location;
use std::sync::Arc;

use axum_server::tls_rustls::RustlsConfig;
use log::info;
use thiserror::Error;
use torrust_tracker_configuration::TslConfig;
use torrust_tracker_located_error::{DynError, LocatedError};
use tracing::info;

/// Error returned by the Bootstrap Process.
#[derive(Error, Debug)]
Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap/jobs/torrent_cleanup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
use std::sync::Arc;

use chrono::Utc;
use log::info;
use tokio::task::JoinHandle;
use torrust_tracker_configuration::v1::core::Core;
use tracing::info;

use crate::core;

Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap/jobs/tracker_apis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ use std::net::SocketAddr;
use std::sync::Arc;

use axum_server::tls_rustls::RustlsConfig;
use log::info;
use tokio::task::JoinHandle;
use torrust_tracker_configuration::{AccessTokens, HttpApi};
use tracing::info;

use super::make_rust_tls;
use crate::core;
Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap/jobs/udp_tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
//! > for the configuration options.
use std::sync::Arc;

use log::debug;
use tokio::task::JoinHandle;
use torrust_tracker_configuration::UdpTracker;
use tracing::debug;

use crate::core;
use crate::servers::registar::ServiceRegistrationForm;
Expand Down
73 changes: 45 additions & 28 deletions src/bootstrap/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,55 +12,72 @@
//! Refer to the [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) to know how to change log settings.
use std::sync::Once;

use log::{info, LevelFilter};
use torrust_tracker_configuration::{Configuration, LogLevel};
use tracing::info;
use tracing::level_filters::LevelFilter;

static INIT: Once = Once::new();

/// It redirects the log info to the standard output with the log level defined in the configuration
pub fn setup(cfg: &Configuration) {
let level = config_level_or_default(&cfg.core.log_level);
let tracing_level = config_level_or_default(&cfg.core.log_level);

if level == log::LevelFilter::Off {
if tracing_level == LevelFilter::OFF {
return;
}

INIT.call_once(|| {
stdout_config(level);
tracing_stdout_init(tracing_level, &TraceStyle::Default);
});
}

fn config_level_or_default(log_level: &Option<LogLevel>) -> LevelFilter {
match log_level {
None => log::LevelFilter::Info,
None => LevelFilter::INFO,
Some(level) => match level {
LogLevel::Off => LevelFilter::Off,
LogLevel::Error => LevelFilter::Error,
LogLevel::Warn => LevelFilter::Warn,
LogLevel::Info => LevelFilter::Info,
LogLevel::Debug => LevelFilter::Debug,
LogLevel::Trace => LevelFilter::Trace,
LogLevel::Off => LevelFilter::OFF,
LogLevel::Error => LevelFilter::ERROR,
LogLevel::Warn => LevelFilter::WARN,
LogLevel::Info => LevelFilter::INFO,
LogLevel::Debug => LevelFilter::DEBUG,
LogLevel::Trace => LevelFilter::TRACE,
},
}
}

fn stdout_config(level: LevelFilter) {
if let Err(_err) = fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{} [{}][{}] {}",
chrono::Local::now().format("%+"),
record.target(),
record.level(),
message
));
})
.level(level)
.chain(std::io::stdout())
.apply()
{
panic!("Failed to initialize logging.")
}
fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) {
let builder = tracing_subscriber::fmt().with_max_level(filter);

let () = match style {
TraceStyle::Default => builder.init(),
TraceStyle::Pretty(display_filename) => builder.pretty().with_file(*display_filename).init(),
TraceStyle::Compact => builder.compact().init(),
TraceStyle::Json => builder.json().init(),
};

info!("logging initialized.");
}

#[derive(Debug)]
pub enum TraceStyle {
Default,
Pretty(bool),
Compact,
Json,
}

impl std::fmt::Display for TraceStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let style = match self {
TraceStyle::Default => "Default Style",
TraceStyle::Pretty(path) => match path {
true => "Pretty Style with File Paths",
false => "Pretty Style without File Paths",
},
TraceStyle::Compact => "Compact Style",
TraceStyle::Json => "Json Format",
};

f.write_str(style)
}
}
2 changes: 1 addition & 1 deletion src/console/ci/e2e/docker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::process::{Command, Output};
use std::thread::sleep;
use std::time::{Duration, Instant};

use log::{debug, info};
use tracing::{debug, info};

/// Docker command wrapper.
pub struct Docker {}
Expand Down
34 changes: 17 additions & 17 deletions src/console/ci/e2e/logs_parser.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! Utilities to parse Torrust Tracker logs.
use serde::{Deserialize, Serialize};

const UDP_TRACKER_PATTERN: &str = "[UDP TRACKER][INFO] Starting on: udp://";
const HTTP_TRACKER_PATTERN: &str = "[HTTP TRACKER][INFO] Starting on: ";
const HEALTH_CHECK_PATTERN: &str = "[HEALTH CHECK API][INFO] Starting on: ";
const UDP_TRACKER_PATTERN: &str = "INFO UDP TRACKER: Starting on: udp://";
const HTTP_TRACKER_PATTERN: &str = "INFO HTTP TRACKER: Starting on: ";
const HEALTH_CHECK_PATTERN: &str = "INFO HEALTH CHECK API: Starting on: ";

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct RunningServices {
Expand All @@ -18,17 +18,17 @@ impl RunningServices {
/// For example, from this logs:
///
/// ```text
/// Loading default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ...
/// 2024-01-24T16:36:14.614898789+00:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized.
/// 2024-01-24T16:36:14.615586025+00:00 [UDP TRACKER][INFO] Starting on: udp://0.0.0.0:6969
/// 2024-01-24T16:36:14.615623705+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled
/// 2024-01-24T16:36:14.615694484+00:00 [HTTP TRACKER][INFO] Starting on: http://0.0.0.0:7070
/// 2024-01-24T16:36:14.615710534+00:00 [HTTP TRACKER][INFO] Started on: http://0.0.0.0:7070
/// 2024-01-24T16:36:14.615716574+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled
/// 2024-01-24T16:36:14.615764904+00:00 [API][INFO] Starting on http://127.0.0.1:1212
/// 2024-01-24T16:36:14.615767264+00:00 [API][INFO] Started on http://127.0.0.1:1212
/// 2024-01-24T16:36:14.615777574+00:00 [HEALTH CHECK API][INFO] Starting on: http://127.0.0.1:1313
/// 2024-01-24T16:36:14.615791124+00:00 [HEALTH CHECK API][INFO] Started on: http://127.0.0.1:1313
/// Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ...
/// 2024-06-10T14:26:10.040894Z INFO torrust_tracker::bootstrap::logging: logging initialized.
/// 2024-06-10T14:26:10.041363Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969
/// 2024-06-10T14:26:10.041386Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled
/// 2024-06-10T14:26:10.041420Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070
/// 2024-06-10T14:26:10.041516Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070
/// 2024-06-10T14:26:10.041521Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled
/// 2024-06-10T14:26:10.041611Z INFO API: Starting on http://127.0.0.1:1212
/// 2024-06-10T14:26:10.041614Z INFO API: Started on http://127.0.0.1:1212
/// 2024-06-10T14:26:10.041623Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313
/// 2024-06-10T14:26:10.041657Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313
/// ```
///
/// It would extract these services:
Expand Down Expand Up @@ -86,9 +86,9 @@ mod tests {
#[test]
fn it_should_parse_from_logs_with_valid_logs() {
let logs = "\
[UDP TRACKER][INFO] Starting on: udp://0.0.0.0:8080\n\
[HTTP TRACKER][INFO] Starting on: 0.0.0.0:9090\n\
[HEALTH CHECK API][INFO] Starting on: 0.0.0.0:10010";
INFO UDP TRACKER: Starting on: udp://0.0.0.0:8080\n\
INFO HTTP TRACKER: Starting on: 0.0.0.0:9090\n\
INFO HEALTH CHECK API: Starting on: 0.0.0.0:10010";
let running_services = RunningServices::parse_from_logs(logs);

assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:8080"]);
Expand Down
27 changes: 6 additions & 21 deletions src/console/ci/e2e/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
//! ```text
//! cargo run --bin e2e_tests_runner share/default/config/tracker.e2e.container.sqlite3.toml
//! ```
use log::{debug, info, LevelFilter};
use tracing::info;
use tracing::level_filters::LevelFilter;

use super::tracker_container::TrackerContainer;
use crate::console::ci::e2e::docker::RunOptions;
Expand Down Expand Up @@ -32,7 +33,7 @@ pub struct Arguments {
///
/// Will panic if it can't not perform any of the operations.
pub fn run() {
setup_runner_logging(LevelFilter::Info);
tracing_stdout_init(LevelFilter::INFO);

let args = parse_arguments();

Expand Down Expand Up @@ -76,25 +77,9 @@ pub fn run() {
info!("Tracker container final state:\n{:#?}", tracker_container);
}

fn setup_runner_logging(level: LevelFilter) {
if let Err(_err) = fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{} [{}][{}] {}",
chrono::Local::now().format("%+"),
record.target(),
record.level(),
message
));
})
.level(level)
.chain(std::io::stdout())
.apply()
{
panic!("Failed to initialize logging.")
}

debug!("logging initialized.");
fn tracing_stdout_init(filter: LevelFilter) {
tracing_subscriber::fmt().with_max_level(filter).init();
info!("logging initialized.");
}

fn parse_arguments() -> Arguments {
Expand Down
2 changes: 1 addition & 1 deletion src/console/ci/e2e/tracker_checker.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::io;
use std::process::Command;

use log::info;
use tracing::info;

/// Runs the Tracker Checker.
///
Expand Down
2 changes: 1 addition & 1 deletion src/console/ci/e2e/tracker_container.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::time::Duration;

use log::{debug, error, info};
use rand::distributions::Alphanumeric;
use rand::Rng;
use tracing::{debug, error, info};

use super::docker::{RunOptions, RunningContainer};
use super::logs_parser::RunningServices;
Expand Down
27 changes: 6 additions & 21 deletions src/console/clients/checker/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ use std::sync::Arc;

use anyhow::{Context, Result};
use clap::Parser;
use log::{debug, LevelFilter};
use tracing::info;
use tracing::level_filters::LevelFilter;

use super::config::Configuration;
use super::console::Console;
Expand All @@ -40,7 +41,7 @@ struct Args {
///
/// Will return an error if the configuration was not provided.
pub async fn run() -> Result<Vec<CheckResult>> {
setup_logging(LevelFilter::Info);
tracing_stdout_init(LevelFilter::INFO);

let args = Args::parse();

Expand All @@ -56,25 +57,9 @@ pub async fn run() -> Result<Vec<CheckResult>> {
Ok(service.run_checks().await)
}

fn setup_logging(level: LevelFilter) {
if let Err(_err) = fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{} [{}][{}] {}",
chrono::Local::now().format("%+"),
record.target(),
record.level(),
message
));
})
.level(level)
.chain(std::io::stdout())
.apply()
{
panic!("Failed to initialize logging.")
}

debug!("logging initialized.");
fn tracing_stdout_init(filter: LevelFilter) {
tracing_subscriber::fmt().with_max_level(filter).init();
info!("logging initialized.");
}

fn setup_config(args: Args) -> Result<Configuration> {
Expand Down
2 changes: 1 addition & 1 deletion src/console/clients/checker/checks/http.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::str::FromStr;

use log::debug;
use reqwest::Url as ServiceUrl;
use torrust_tracker_primitives::info_hash::InfoHash;
use tracing::debug;
use url::Url;

use super::structs::{CheckerOutput, Status};
Expand Down
2 changes: 1 addition & 1 deletion src/console/clients/checker/checks/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use std::net::SocketAddr;

use aquatic_udp_protocol::{Port, TransactionId};
use hex_literal::hex;
use log::debug;
use torrust_tracker_primitives::info_hash::InfoHash;
use tracing::debug;

use crate::console::clients::checker::checks::structs::{CheckerOutput, Status};
use crate::console::clients::checker::service::{CheckError, CheckResult};
Expand Down
Loading

0 comments on commit 6e06b2e

Please sign in to comment.