diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index bf861868..2844d69d 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -90,7 +90,7 @@ where source: Arc::new(self.0), location: Box::new(*std::panic::Location::caller()), }; - log::debug!("{e}"); + tracing::debug!("{e}"); e } } diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 4fc3ead9..4c02d6ee 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -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) { - 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) -> 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) + } +} diff --git a/src/console/commands/seeder/api.rs b/src/console/commands/seeder/api.rs index 5ddee1d7..ed35dbc6 100644 --- a/src/console/commands/seeder/api.rs +++ b/src/console/commands/seeder/api.rs @@ -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; diff --git a/src/console/commands/seeder/app.rs b/src/console/commands/seeder/app.rs index 84ab55cf..d8e133f0 100644 --- a/src/console/commands/seeder/app.rs +++ b/src/console/commands/seeder/app.rs @@ -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; @@ -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(); diff --git a/src/console/commands/seeder/logging.rs b/src/console/commands/seeder/logging.rs index 85634719..3ba046f3 100644 --- a/src/console/commands/seeder/logging.rs +++ b/src/console/commands/seeder/logging.rs @@ -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."); } diff --git a/src/console/cronjobs/tracker_statistics_importer.rs b/src/console/cronjobs/tracker_statistics_importer.rs index 7f618e61..2794c4cf 100644 --- a/src/console/cronjobs/tracker_statistics_importer.rs +++ b/src/console/cronjobs/tracker_statistics_importer.rs @@ -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; diff --git a/src/databases/mysql.rs b/src/databases/mysql.rs index 14d69ea2..89245ee9 100644 --- a/src/databases/mysql.rs +++ b/src/databases/mysql.rs @@ -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 { @@ -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 }); @@ -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 { @@ -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 { @@ -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 { diff --git a/src/databases/sqlite.rs b/src/databases/sqlite.rs index ceb6e410..f9482838 100644 --- a/src/databases/sqlite.rs +++ b/src/databases/sqlite.rs @@ -499,7 +499,7 @@ impl Database for Sqlite { .map(|v| v.last_insert_rowid()) .map_err(|e| match e { sqlx::Error::Database(err) => { - log::error!("DB error: {:?}", err); + tracing::error!("DB error: {:?}", err); if err.message().contains("UNIQUE") && err.message().contains("info_hash") { database::Error::TorrentAlreadyExists } else { @@ -520,7 +520,7 @@ impl Database for Sqlite { .await .map(|_| ()) .map_err(|err| { - log::error!("DB error: {:?}", err); + tracing::error!("DB error: {:?}", err); database::Error::Error }); @@ -677,7 +677,7 @@ impl Database for Sqlite { .await .map_err(|e| match e { sqlx::Error::Database(err) => { - log::error!("DB error: {:?}", err); + tracing::error!("DB error: {:?}", err); if err.message().contains("UNIQUE") && err.message().contains("title") { database::Error::TorrentTitleAlreadyExists } else { @@ -923,7 +923,7 @@ impl Database for Sqlite { .await .map_err(|e| match e { sqlx::Error::Database(err) => { - log::error!("DB error: {:?}", err); + tracing::error!("DB error: {:?}", err); if err.message().contains("UNIQUE") && err.message().contains("title") { database::Error::TorrentTitleAlreadyExists } else { @@ -981,7 +981,7 @@ impl Database for Sqlite { .map(|v| v.last_insert_rowid()) .map_err(|e| match e { sqlx::Error::Database(err) => { - log::error!("DB error: {:?}", err); + tracing::error!("DB error: {:?}", err); if err.message().contains("UNIQUE") && err.message().contains("name") { database::Error::TagAlreadyExists } else { diff --git a/src/mailer.rs b/src/mailer.rs index 955aefbe..36134b14 100644 --- a/src/mailer.rs +++ b/src/mailer.rs @@ -152,7 +152,7 @@ impl Service { fn build_letter(verification_url: &str, username: &str, builder: MessageBuilder) -> Result { let (plain_body, html_body) = build_content(verification_url, username).map_err(|e| { - log::error!("{e}"); + tracing::error!("{e}"); ServiceError::InternalServerError })?; diff --git a/src/models/torrent_file.rs b/src/models/torrent_file.rs index ac28a6dc..df88b350 100644 --- a/src/models/torrent_file.rs +++ b/src/models/torrent_file.rs @@ -1,8 +1,8 @@ -use log::error; use serde::{Deserialize, Serialize}; use serde_bencode::ser; use serde_bytes::ByteBuf; use sha1::{Digest, Sha1}; +use tracing::error; use url::Url; use super::info_hash::InfoHash; diff --git a/src/services/torrent.rs b/src/services/torrent.rs index b98ef90b..28aa6223 100644 --- a/src/services/torrent.rs +++ b/src/services/torrent.rs @@ -1,8 +1,8 @@ //! Torrent service. use std::sync::Arc; -use log::debug; use serde_derive::{Deserialize, Serialize}; +use tracing::debug; use url::Url; use super::category::DbCategoryRepository; diff --git a/src/services/user.rs b/src/services/user.rs index f18ecc52..e808548e 100644 --- a/src/services/user.rs +++ b/src/services/user.rs @@ -5,10 +5,10 @@ use argon2::password_hash::SaltString; use argon2::{Argon2, PasswordHasher}; use async_trait::async_trait; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; -use log::{debug, info}; #[cfg(test)] use mockall::automock; use pbkdf2::password_hash::rand_core::OsRng; +use tracing::{debug, info}; use super::authentication::DbUserAuthenticationRepository; use crate::config::{Configuration, EmailOnSignup}; diff --git a/src/tracker/service.rs b/src/tracker/service.rs index 5de57d11..f02c605a 100644 --- a/src/tracker/service.rs +++ b/src/tracker/service.rs @@ -2,8 +2,8 @@ use std::sync::Arc; use derive_more::{Display, Error}; use hyper::StatusCode; -use log::{debug, error}; use serde::{Deserialize, Serialize}; +use tracing::{debug, error}; use url::Url; use super::api::{Client, ConnectionInfo}; diff --git a/src/tracker/statistics_importer.rs b/src/tracker/statistics_importer.rs index 87512a42..88265743 100644 --- a/src/tracker/statistics_importer.rs +++ b/src/tracker/statistics_importer.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use std::time::Instant; use chrono::{DateTime, Utc}; -use log::{debug, error, info}; +use tracing::{debug, error, info}; use text_colorizer::Colorize; use url::Url; diff --git a/src/web/api/server/mod.rs b/src/web/api/server/mod.rs index 7d42c9e5..1349b54f 100644 --- a/src/web/api/server/mod.rs +++ b/src/web/api/server/mod.rs @@ -8,10 +8,10 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; -use log::{error, info}; use thiserror::Error; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_index_located_error::LocatedError; +use tracing::{error, info}; use v1::routes::router; use self::signals::{Halted, Started}; diff --git a/src/web/api/server/signals.rs b/src/web/api/server/signals.rs index 872d6094..2eead7da 100644 --- a/src/web/api/server/signals.rs +++ b/src/web/api/server/signals.rs @@ -2,8 +2,8 @@ use std::net::SocketAddr; use std::time::Duration; use derive_more::Display; -use log::info; use tokio::time::sleep; +use tracing::info; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the service was successfully started. diff --git a/src/web/api/server/v1/contexts/torrent/handlers.rs b/src/web/api/server/v1/contexts/torrent/handlers.rs index ddba8df0..5b38d3e4 100644 --- a/src/web/api/server/v1/contexts/torrent/handlers.rs +++ b/src/web/api/server/v1/contexts/torrent/handlers.rs @@ -7,8 +7,8 @@ use std::sync::Arc; use axum::extract::{self, Multipart, Path, Query, State}; use axum::response::{IntoResponse, Redirect, Response}; use axum::Json; -use log::debug; use serde::Deserialize; +use tracing::debug; use uuid::Uuid; use super::errors; diff --git a/tests/environments/app_starter.rs b/tests/environments/app_starter.rs index 3d6fe36c..921418d0 100644 --- a/tests/environments/app_starter.rs +++ b/tests/environments/app_starter.rs @@ -1,11 +1,11 @@ use std::net::SocketAddr; -use log::info; use tokio::sync::{oneshot, RwLock}; use tokio::task::JoinHandle; use torrust_index::config::Configuration; use torrust_index::web::api::Version; use torrust_index::{app, config}; +use tracing::info; /// It launches the app and provides a way to stop it. pub struct AppStarter {