Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move from log to tracing crate #623

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading