Skip to content

Commit

Permalink
Merge #623: Move from log to tracing crate
Browse files Browse the repository at this point in the history
f6bace6 feat: move loggin from log to tracing crate (Jose Celano)
213fcd3 chore(deps): [#621] add cargo dependency: tracing-subscriber (Jose Celano)

Pull request description:

  Move from `log` to `tracing` crate.

  Old output:

  ```output
  $ cargo run
     Compiling torrust-index v3.0.0-alpha.3-develop (/home/josecelano/Documents/github/committer/me/torrust/torrust-index)
      Finished `dev` profile [unoptimized + debuginfo] target(s) in 12.31s
       Running `target/debug/torrust-index`
  Loading configuration from default configuration file: `./share/default/config/index.development.sqlite3.toml` ...
  2024-06-07T15:35:08.192302724+01:00 [torrust_index::bootstrap::logging][INFO] logging initialized.
  2024-06-07T15:35:08.252784599+01:00 [torrust_index::web::api::server][INFO] TLS not enabled
  2024-06-07T15:35:08.252892290+01:00 [torrust_index::console::cronjobs::tracker_statistics_importer][INFO] Tracker statistics importer launcher started
  2024-06-07T15:35:08.252979221+01:00 [torrust_index::console::cronjobs::tracker_statistics_importer][INFO] Tracker statistics importer cronjob starting ...
  2024-06-07T15:35:08.252977224+01:00 [torrust_index::web::api::server][INFO] Starting API server with net config: 0.0.0.0:3001 ...
  2024-06-07T15:35:08.253260311+01:00 [torrust_index::console::cronjobs::tracker_statistics_importer][INFO] Tracker statistics importer API server listening on http://127.0.0.1:3002
  2024-06-07T15:35:08.254122817+01:00 [torrust_index::console::cronjobs::tracker_statistics_importer][INFO] Running tracker statistics importer every 2000 milliseconds ...
  2024-06-07T15:35:08.254518031+01:00 [torrust_index::web::api::server][INFO] API server listening on http://0.0.0.0:3001
  2024-06-07T15:35:08.284476791+01:00 [Tracker Stats Importer][INFO] Importing 1 torrents statistics from tracker udp://localhost:6969 ...
  ```

  New output:

  ```
  $ cargo run
      Blocking waiting for file lock on build directory
     Compiling torrust-index v3.0.0-alpha.3-develop (/home/josecelano/Documents/github/committer/me/torrust/torrust-index)
      Finished `dev` profile [unoptimized + debuginfo] target(s) in 52.26s
       Running `target/debug/torrust-index`
  Loading configuration from default configuration file: `./share/default/config/index.development.sqlite3.toml` ...
  2024-06-07T16:50:05.192713Z  INFO torrust_index::bootstrap::logging: logging initialized.
  2024-06-07T16:50:05.352161Z  INFO torrust_index::web::api::server: TLS not enabled
  2024-06-07T16:50:05.352303Z  INFO torrust_index::console::cronjobs::tracker_statistics_importer: Tracker statistics importer launcher started
  2024-06-07T16:50:05.352318Z  INFO torrust_index::web::api::server: Starting API server with net config: 0.0.0.0:3001 ...
  2024-06-07T16:50:05.352363Z  INFO torrust_index::console::cronjobs::tracker_statistics_importer: Tracker statistics importer cronjob starting ...
  2024-06-07T16:50:05.352828Z  INFO torrust_index::console::cronjobs::tracker_statistics_importer: Tracker statistics importer API server listening on http://127.0.0.1:3002
  2024-06-07T16:50:05.353605Z  INFO torrust_index::console::cronjobs::tracker_statistics_importer: Running tracker statistics importer every 2000 milliseconds ...
  2024-06-07T16:50:05.356876Z  INFO torrust_index::web::api::server: API server listening on http://0.0.0.0:3001
  2024-06-07T16:50:05.428304Z  INFO Tracker Stats Importer: Importing 1 torrents statistics from tracker udp://localhost:6969 ...
  ```

ACKs for top commit:
  josecelano:
    ACK f6bace6

Tree-SHA512: 812fe3b62efeb227b5aa73c78c6a38fff4569576ebe286799f228f76e76b5a992bd0943d482f9eee09ddd24fcbc15569e46e733c9c601b557710eb8febf9f5eb
  • Loading branch information
josecelano committed Jun 10, 2024
2 parents 97b7c54 + f6bace6 commit ea28777
Show file tree
Hide file tree
Showing 21 changed files with 161 additions and 72 deletions.
84 changes: 83 additions & 1 deletion Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ tracing = "0.1.40"
url = { version = "2.5.0", features = ["serde"] }
urlencoding = "2"
uuid = { version = "1", features = ["v4"] }
tracing-subscriber = { version = "0.3.18", features = ["json"] }

[dev-dependencies]
tempfile = "3"
Expand Down
3 changes: 2 additions & 1 deletion packages/located-error/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ rust-version.workspace = true
version.workspace = true

[dependencies]
log = { version = "0", features = ["release_max_level_info"] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["json"] }

[dev-dependencies]
thiserror = "1.0"
2 changes: 1 addition & 1 deletion packages/located-error/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ where
source: Arc::new(self.0),
location: Box::new(*std::panic::Location::caller()),
};
log::debug!("{e}");
tracing::debug!("{e}");
e
}
}
Expand Down
74 changes: 46 additions & 28 deletions src/bootstrap/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,55 +8,73 @@
//! - `Trace`
use std::sync::Once;

use log::{info, LevelFilter};
use tracing::info;
use tracing::level_filters::LevelFilter;

use crate::config::v1::LogLevel;

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

pub fn setup(log_level: &Option<LogLevel>) {
let level = config_level_or_default(log_level);
let tracing_level = config_level_or_default(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/commands/seeder/api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Action that a user can perform on a Index website.
use log::debug;
use thiserror::Error;
use tracing::debug;

use crate::web::api::client::v1::client::Client;
use crate::web::api::client::v1::contexts::category::forms::AddCategoryForm;
Expand Down
5 changes: 3 additions & 2 deletions src/console/commands/seeder/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,10 @@ use std::time::Duration;

use anyhow::Context;
use clap::Parser;
use log::{debug, info, LevelFilter};
use reqwest::Url;
use text_colorizer::Colorize;
use tracing::level_filters::LevelFilter;
use tracing::{debug, info};
use uuid::Uuid;

use super::api::Error;
Expand Down Expand Up @@ -171,7 +172,7 @@ struct Args {
///
/// Will not return any errors for the time being.
pub async fn run() -> anyhow::Result<()> {
logging::setup(LevelFilter::Info);
logging::setup(LevelFilter::INFO);

let args = Args::parse();

Expand Down
20 changes: 3 additions & 17 deletions src/console/commands/seeder/logging.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,12 @@
//! Logging setup for the `seeder`.
use log::{debug, LevelFilter};
use tracing::debug;
use tracing::level_filters::LevelFilter;

/// # Panics
///
///
pub fn setup(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.")
}
tracing_subscriber::fmt().with_max_level(level).init();

debug!("logging initialized.");
}
2 changes: 1 addition & 1 deletion src/console/cronjobs/tracker_statistics_importer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ use axum::extract::State;
use axum::routing::{get, post};
use axum::{Json, Router};
use chrono::{DateTime, Utc};
use log::{debug, error, info};
use serde_json::{json, Value};
use text_colorizer::Colorize;
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
use tracing::{debug, error, info};

use crate::tracker::statistics_importer::StatisticsImporter;
use crate::utils::clock::seconds_ago_utc;
Expand Down
10 changes: 5 additions & 5 deletions src/databases/mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ impl Database for Mysql {
.map(|v| i64::try_from(v.last_insert_id()).expect("last ID is larger than i64"))
.map_err(|e| match e {
sqlx::Error::Database(err) => {
log::error!("DB error: {:?}", err);
tracing::error!("DB error: {:?}", err);
if err.message().contains("Duplicate entry") && err.message().contains("info_hash") {
database::Error::TorrentAlreadyExists
} else {
Expand All @@ -530,7 +530,7 @@ impl Database for Mysql {
.await
.map(|_| ())
.map_err(|err| {
log::error!("DB error: {:?}", err);
tracing::error!("DB error: {:?}", err);
database::Error::Error
});

Expand Down Expand Up @@ -683,7 +683,7 @@ impl Database for Mysql {
.await
.map_err(|e| match e {
sqlx::Error::Database(err) => {
log::error!("DB error: {:?}", err);
tracing::error!("DB error: {:?}", err);
if err.message().contains("Duplicate entry") && err.message().contains("title") {
database::Error::TorrentTitleAlreadyExists
} else {
Expand Down Expand Up @@ -931,7 +931,7 @@ impl Database for Mysql {
.await
.map_err(|e| match e {
sqlx::Error::Database(err) => {
log::error!("DB error: {:?}", err);
tracing::error!("DB error: {:?}", err);
if err.message().contains("Duplicate entry") && err.message().contains("title") {
database::Error::TorrentTitleAlreadyExists
} else {
Expand Down Expand Up @@ -989,7 +989,7 @@ impl Database for Mysql {
.map(|v| i64::try_from(v.last_insert_id()).expect("last ID is larger than i64"))
.map_err(|e| match e {
sqlx::Error::Database(err) => {
log::error!("DB error: {:?}", err);
tracing::error!("DB error: {:?}", err);
if err.message().contains("Duplicate entry") && err.message().contains("name") {
database::Error::TagAlreadyExists
} else {
Expand Down
Loading

0 comments on commit ea28777

Please sign in to comment.