Skip to content

Commit

Permalink
feat: move loggin from log to tracing crate
Browse files Browse the repository at this point in the history
Current outpuit:

```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:

```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 ...
```
  • Loading branch information
josecelano committed Jun 7, 2024
1 parent 213fcd3 commit f7f9aee
Show file tree
Hide file tree
Showing 18 changed files with 75 additions and 70 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 @@ -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
10 changes: 5 additions & 5 deletions src/databases/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
});

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion src/mailer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ impl Service {

fn build_letter(verification_url: &str, username: &str, builder: MessageBuilder) -> Result<Message, ServiceError> {
let (plain_body, html_body) = build_content(verification_url, username).map_err(|e| {
log::error!("{e}");
tracing::error!("{e}");
ServiceError::InternalServerError
})?;

Expand Down
2 changes: 1 addition & 1 deletion src/models/torrent_file.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/services/torrent.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/services/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
2 changes: 1 addition & 1 deletion src/tracker/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
2 changes: 1 addition & 1 deletion src/tracker/statistics_importer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
2 changes: 1 addition & 1 deletion src/web/api/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
2 changes: 1 addition & 1 deletion src/web/api/server/signals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/web/api/server/v1/contexts/torrent/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion tests/environments/app_starter.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down

0 comments on commit f7f9aee

Please sign in to comment.