Skip to content

Commit f6bace6

Browse files
committed
feat: move loggin from log to tracing crate
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 ... ```
1 parent 213fcd3 commit f6bace6

File tree

18 files changed

+75
-70
lines changed

18 files changed

+75
-70
lines changed

packages/located-error/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ where
9090
source: Arc::new(self.0),
9191
location: Box::new(*std::panic::Location::caller()),
9292
};
93-
log::debug!("{e}");
93+
tracing::debug!("{e}");
9494
e
9595
}
9696
}

src/bootstrap/logging.rs

Lines changed: 46 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -8,55 +8,73 @@
88
//! - `Trace`
99
use std::sync::Once;
1010

11-
use log::{info, LevelFilter};
11+
use tracing::info;
12+
use tracing::level_filters::LevelFilter;
1213

1314
use crate::config::v1::LogLevel;
1415

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

1718
pub fn setup(log_level: &Option<LogLevel>) {
18-
let level = config_level_or_default(log_level);
19+
let tracing_level = config_level_or_default(log_level);
1920

20-
if level == log::LevelFilter::Off {
21+
if tracing_level == LevelFilter::OFF {
2122
return;
2223
}
2324

2425
INIT.call_once(|| {
25-
stdout_config(level);
26+
tracing_stdout_init(tracing_level, &TraceStyle::Default);
2627
});
2728
}
2829

2930
fn config_level_or_default(log_level: &Option<LogLevel>) -> LevelFilter {
3031
match log_level {
31-
None => log::LevelFilter::Info,
32+
None => LevelFilter::INFO,
3233
Some(level) => match level {
33-
LogLevel::Off => LevelFilter::Off,
34-
LogLevel::Error => LevelFilter::Error,
35-
LogLevel::Warn => LevelFilter::Warn,
36-
LogLevel::Info => LevelFilter::Info,
37-
LogLevel::Debug => LevelFilter::Debug,
38-
LogLevel::Trace => LevelFilter::Trace,
34+
LogLevel::Off => LevelFilter::OFF,
35+
LogLevel::Error => LevelFilter::ERROR,
36+
LogLevel::Warn => LevelFilter::WARN,
37+
LogLevel::Info => LevelFilter::INFO,
38+
LogLevel::Debug => LevelFilter::DEBUG,
39+
LogLevel::Trace => LevelFilter::TRACE,
3940
},
4041
}
4142
}
4243

43-
fn stdout_config(level: LevelFilter) {
44-
if let Err(_err) = fern::Dispatch::new()
45-
.format(|out, message, record| {
46-
out.finish(format_args!(
47-
"{} [{}][{}] {}",
48-
chrono::Local::now().format("%+"),
49-
record.target(),
50-
record.level(),
51-
message
52-
));
53-
})
54-
.level(level)
55-
.chain(std::io::stdout())
56-
.apply()
57-
{
58-
panic!("Failed to initialize logging.")
59-
}
44+
fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) {
45+
let builder = tracing_subscriber::fmt().with_max_level(filter);
46+
47+
let () = match style {
48+
TraceStyle::Default => builder.init(),
49+
TraceStyle::Pretty(display_filename) => builder.pretty().with_file(*display_filename).init(),
50+
TraceStyle::Compact => builder.compact().init(),
51+
TraceStyle::Json => builder.json().init(),
52+
};
6053

6154
info!("logging initialized.");
6255
}
56+
57+
#[derive(Debug)]
58+
pub enum TraceStyle {
59+
Default,
60+
Pretty(bool),
61+
Compact,
62+
Json,
63+
}
64+
65+
impl std::fmt::Display for TraceStyle {
66+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67+
let style = match self {
68+
TraceStyle::Default => "Default Style",
69+
TraceStyle::Pretty(path) => match path {
70+
true => "Pretty Style with File Paths",
71+
false => "Pretty Style without File Paths",
72+
},
73+
74+
TraceStyle::Compact => "Compact Style",
75+
TraceStyle::Json => "Json Format",
76+
};
77+
78+
f.write_str(style)
79+
}
80+
}

src/console/commands/seeder/api.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Action that a user can perform on a Index website.
2-
use log::debug;
32
use thiserror::Error;
3+
use tracing::debug;
44

55
use crate::web::api::client::v1::client::Client;
66
use crate::web::api::client::v1::contexts::category::forms::AddCategoryForm;

src/console/commands/seeder/app.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,9 +133,10 @@ use std::time::Duration;
133133

134134
use anyhow::Context;
135135
use clap::Parser;
136-
use log::{debug, info, LevelFilter};
137136
use reqwest::Url;
138137
use text_colorizer::Colorize;
138+
use tracing::level_filters::LevelFilter;
139+
use tracing::{debug, info};
139140
use uuid::Uuid;
140141

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

176177
let args = Args::parse();
177178

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,12 @@
11
//! Logging setup for the `seeder`.
2-
use log::{debug, LevelFilter};
2+
use tracing::debug;
3+
use tracing::level_filters::LevelFilter;
34

45
/// # Panics
56
///
67
///
78
pub fn setup(level: LevelFilter) {
8-
if let Err(_err) = fern::Dispatch::new()
9-
.format(|out, message, record| {
10-
out.finish(format_args!(
11-
"{} [{}][{}] {}",
12-
chrono::Local::now().format("%+"),
13-
record.target(),
14-
record.level(),
15-
message
16-
));
17-
})
18-
.level(level)
19-
.chain(std::io::stdout())
20-
.apply()
21-
{
22-
panic!("Failed to initialize logging.")
23-
}
9+
tracing_subscriber::fmt().with_max_level(level).init();
2410

2511
debug!("logging initialized.");
2612
}

src/console/cronjobs/tracker_statistics_importer.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ use axum::extract::State;
1717
use axum::routing::{get, post};
1818
use axum::{Json, Router};
1919
use chrono::{DateTime, Utc};
20-
use log::{debug, error, info};
2120
use serde_json::{json, Value};
2221
use text_colorizer::Colorize;
2322
use tokio::net::TcpListener;
2423
use tokio::task::JoinHandle;
24+
use tracing::{debug, error, info};
2525

2626
use crate::tracker::statistics_importer::StatisticsImporter;
2727
use crate::utils::clock::seconds_ago_utc;

src/databases/mysql.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,7 @@ impl Database for Mysql {
509509
.map(|v| i64::try_from(v.last_insert_id()).expect("last ID is larger than i64"))
510510
.map_err(|e| match e {
511511
sqlx::Error::Database(err) => {
512-
log::error!("DB error: {:?}", err);
512+
tracing::error!("DB error: {:?}", err);
513513
if err.message().contains("Duplicate entry") && err.message().contains("info_hash") {
514514
database::Error::TorrentAlreadyExists
515515
} else {
@@ -530,7 +530,7 @@ impl Database for Mysql {
530530
.await
531531
.map(|_| ())
532532
.map_err(|err| {
533-
log::error!("DB error: {:?}", err);
533+
tracing::error!("DB error: {:?}", err);
534534
database::Error::Error
535535
});
536536

@@ -683,7 +683,7 @@ impl Database for Mysql {
683683
.await
684684
.map_err(|e| match e {
685685
sqlx::Error::Database(err) => {
686-
log::error!("DB error: {:?}", err);
686+
tracing::error!("DB error: {:?}", err);
687687
if err.message().contains("Duplicate entry") && err.message().contains("title") {
688688
database::Error::TorrentTitleAlreadyExists
689689
} else {
@@ -931,7 +931,7 @@ impl Database for Mysql {
931931
.await
932932
.map_err(|e| match e {
933933
sqlx::Error::Database(err) => {
934-
log::error!("DB error: {:?}", err);
934+
tracing::error!("DB error: {:?}", err);
935935
if err.message().contains("Duplicate entry") && err.message().contains("title") {
936936
database::Error::TorrentTitleAlreadyExists
937937
} else {
@@ -989,7 +989,7 @@ impl Database for Mysql {
989989
.map(|v| i64::try_from(v.last_insert_id()).expect("last ID is larger than i64"))
990990
.map_err(|e| match e {
991991
sqlx::Error::Database(err) => {
992-
log::error!("DB error: {:?}", err);
992+
tracing::error!("DB error: {:?}", err);
993993
if err.message().contains("Duplicate entry") && err.message().contains("name") {
994994
database::Error::TagAlreadyExists
995995
} else {

src/databases/sqlite.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,7 @@ impl Database for Sqlite {
499499
.map(|v| v.last_insert_rowid())
500500
.map_err(|e| match e {
501501
sqlx::Error::Database(err) => {
502-
log::error!("DB error: {:?}", err);
502+
tracing::error!("DB error: {:?}", err);
503503
if err.message().contains("UNIQUE") && err.message().contains("info_hash") {
504504
database::Error::TorrentAlreadyExists
505505
} else {
@@ -520,7 +520,7 @@ impl Database for Sqlite {
520520
.await
521521
.map(|_| ())
522522
.map_err(|err| {
523-
log::error!("DB error: {:?}", err);
523+
tracing::error!("DB error: {:?}", err);
524524
database::Error::Error
525525
});
526526

@@ -677,7 +677,7 @@ impl Database for Sqlite {
677677
.await
678678
.map_err(|e| match e {
679679
sqlx::Error::Database(err) => {
680-
log::error!("DB error: {:?}", err);
680+
tracing::error!("DB error: {:?}", err);
681681
if err.message().contains("UNIQUE") && err.message().contains("title") {
682682
database::Error::TorrentTitleAlreadyExists
683683
} else {
@@ -923,7 +923,7 @@ impl Database for Sqlite {
923923
.await
924924
.map_err(|e| match e {
925925
sqlx::Error::Database(err) => {
926-
log::error!("DB error: {:?}", err);
926+
tracing::error!("DB error: {:?}", err);
927927
if err.message().contains("UNIQUE") && err.message().contains("title") {
928928
database::Error::TorrentTitleAlreadyExists
929929
} else {
@@ -981,7 +981,7 @@ impl Database for Sqlite {
981981
.map(|v| v.last_insert_rowid())
982982
.map_err(|e| match e {
983983
sqlx::Error::Database(err) => {
984-
log::error!("DB error: {:?}", err);
984+
tracing::error!("DB error: {:?}", err);
985985
if err.message().contains("UNIQUE") && err.message().contains("name") {
986986
database::Error::TagAlreadyExists
987987
} else {

src/mailer.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ impl Service {
152152

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

src/models/torrent_file.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
use log::error;
21
use serde::{Deserialize, Serialize};
32
use serde_bencode::ser;
43
use serde_bytes::ByteBuf;
54
use sha1::{Digest, Sha1};
5+
use tracing::error;
66
use url::Url;
77

88
use super::info_hash::InfoHash;

0 commit comments

Comments
 (0)