Change logging backend to tracing

This commit is contained in:
Cappy Ishihara 2024-06-02 04:11:18 +07:00
parent 92d2a0d906
commit ae260cea85
No known key found for this signature in database
GPG key ID: 50862C285CB76906
6 changed files with 27 additions and 50 deletions

34
Cargo.lock generated
View file

@ -243,17 +243,6 @@ dependencies = [
"windows-targets 0.52.5", "windows-targets 0.52.5",
] ]
[[package]]
name = "colored"
version = "1.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f741c91823341bebf717d4c71bda820630ce065443b58bd1b7451af008355"
dependencies = [
"is-terminal",
"lazy_static",
"winapi",
]
[[package]] [[package]]
name = "core-foundation" name = "core-foundation"
version = "0.9.4" version = "0.9.4"
@ -349,16 +338,6 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a"
[[package]]
name = "fern"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9f0c14694cbd524c8720dd69b0e3179344f04ebb5f90f2e4a440c6ea3b2f1ee"
dependencies = [
"colored",
"log",
]
[[package]] [[package]]
name = "fnv" name = "fnv"
version = "1.0.7" version = "1.0.7"
@ -652,17 +631,6 @@ version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3"
[[package]]
name = "is-terminal"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b"
dependencies = [
"hermit-abi",
"libc",
"windows-sys 0.52.0",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.11" version = "1.0.11"
@ -1174,9 +1142,7 @@ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"chrono", "chrono",
"dashmap", "dashmap",
"fern",
"hex", "hex",
"log",
"rand", "rand",
"reqwest", "reqwest",
"ring", "ring",

View file

@ -7,8 +7,9 @@ publish = false
[dependencies] [dependencies]
# Logging # Logging
log = "0.4.21" tracing-subscriber = { version = "0.3.18", features = ["env-filter", "chrono"] }
fern = { version = "0.6.2", features = ["colored"] } tracing = "0.1.40"
# fern = { version = "0.6.2", features = ["colored"] }
# Errors handelers # Errors handelers
anyhow = "1.0.83" anyhow = "1.0.83"
@ -35,8 +36,7 @@ rand = "0.8.5"
axum = { version = "0.7.5", features = ["ws", "macros", "http2"] } axum = { version = "0.7.5", features = ["ws", "macros", "http2"] }
tower-http = { version = "0.5.2", features = ["trace"] } tower-http = { version = "0.5.2", features = ["trace"] }
tokio = { version = "1.37.0", features = ["full"] } tokio = { version = "1.37.0", features = ["full"] }
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "chrono"] }
tracing = "0.1.40"
# TODO: Sort it! # TODO: Sort it!
# TODO: Replace Vec<u8> and &[u8] by Bytes # TODO: Replace Vec<u8> and &[u8] by Bytes

View file

@ -8,9 +8,9 @@ use axum::{
routing::get, routing::get,
Router, Router,
}; };
use log::{debug, info, trace};
use ring::digest::{self, digest}; use ring::digest::{self, digest};
use serde::Deserialize; use serde::Deserialize;
use tracing::{debug, info, trace};
use uuid::Uuid; use uuid::Uuid;
use crate::AppState; use crate::AppState;
@ -108,7 +108,7 @@ where
.headers .headers
.get("token") .get("token")
.and_then(|value| value.to_str().ok()); .and_then(|value| value.to_str().ok());
trace!("[Extractor Token] Data: {token:?}"); trace!(token = ?token);
match token { match token {
Some(token) => Ok(Self(Some(token.to_string()))), Some(token) => Ok(Self(Some(token.to_string()))),
None => Ok(Self(None)), None => Ok(Self(None)),
@ -134,6 +134,15 @@ impl ToString for AuthSystem {
} }
} }
/// Get UUID from JSON response
// Written to be reusable so we don't have to specify the same complex code twice
#[inline]
fn get_id_json(json: &serde_json::Value) -> anyhow::Result<Uuid> {
trace!("json: {json:#?}"); // For debugging, we'll get to this later!
let uuid = Uuid::parse_str(json.get("id").unwrap().as_str().unwrap())?;
Ok(uuid)
}
pub async fn has_joined( pub async fn has_joined(
server_id: &str, server_id: &str,
username: &str, username: &str,
@ -147,7 +156,7 @@ pub async fn has_joined(
match res.status().as_u16() { match res.status().as_u16() {
200 => { 200 => {
let json = serde_json::from_str::<serde_json::Value>(&res.text().await?)?; let json = serde_json::from_str::<serde_json::Value>(&res.text().await?)?;
let uuid = Uuid::parse_str(json["id"].as_str().unwrap())?; let uuid = get_id_json(&json)?;
Ok(Some((uuid, AuthSystem::ElyBy))) Ok(Some((uuid, AuthSystem::ElyBy)))
}, },
401 => Ok(None), 401 => Ok(None),
@ -161,7 +170,7 @@ pub async fn has_joined(
match res.status().as_u16() { match res.status().as_u16() {
200 => { 200 => {
let json = serde_json::from_str::<serde_json::Value>(&res.text().await?)?; let json = serde_json::from_str::<serde_json::Value>(&res.text().await?)?;
let uuid = Uuid::parse_str(json["id"].as_str().unwrap())?; let uuid = get_id_json(&json)?;
Ok(Some((uuid, AuthSystem::Mojang))) Ok(Some((uuid, AuthSystem::Mojang)))
}, },
204 => Ok(None), 204 => Ok(None),

View file

@ -5,10 +5,10 @@ use axum::{
Router, Router,
}; };
use dashmap::DashMap; use dashmap::DashMap;
use log::info;
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::{broadcast, Mutex}; use tokio::sync::{broadcast, Mutex};
use tower_http::trace::TraceLayer; use tower_http::trace::TraceLayer;
use tracing::info;
use uuid::Uuid; use uuid::Uuid;
// WebSocket worker // WebSocket worker
@ -97,7 +97,9 @@ pub struct AppState {
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
tracing_subscriber::fmt::fmt() tracing_subscriber::fmt::fmt()
.with_env_filter("trace,axum=info,tower_http=info,tokio=info,tungstenite=info,tokio_tungstenite=info") .with_env_filter(
"trace,axum=info,tower_http=info,tokio=info,tungstenite=info,tokio_tungstenite=info",
)
.pretty() .pretty()
.init(); .init();

View file

@ -5,7 +5,7 @@ use axum::{
extract::{Path, State}, extract::{Path, State},
Json, Json,
}; };
use log::{debug, warn}; use tracing::{debug, warn};
use serde_json::{json, Value}; use serde_json::{json, Value};
use tokio::{ use tokio::{
fs, fs,
@ -25,7 +25,7 @@ pub async fn user_info(
Path(uuid): Path<Uuid>, Path(uuid): Path<Uuid>,
State(state): State<AppState>, // FIXME: Variable doesn't using! State(state): State<AppState>, // FIXME: Variable doesn't using!
) -> Json<Value> { ) -> Json<Value> {
log::info!("Receiving profile information for {}", uuid); tracing::info!("Receiving profile information for {}", uuid);
let formatted_uuid = format_uuid(&uuid); let formatted_uuid = format_uuid(&uuid);
@ -88,7 +88,7 @@ pub async fn user_info(
#[debug_handler] #[debug_handler]
pub async fn download_avatar(Path(uuid): Path<Uuid>) -> Result<Vec<u8>> { pub async fn download_avatar(Path(uuid): Path<Uuid>) -> Result<Vec<u8>> {
let uuid = format_uuid(&uuid); let uuid = format_uuid(&uuid);
log::info!("Requesting an avatar: {}", uuid); tracing::info!("Requesting an avatar: {}", uuid);
let mut file = if let Ok(file) = fs::File::open(format!("avatars/{}.moon", uuid)).await { let mut file = if let Ok(file) = fs::File::open(format!("avatars/{}.moon", uuid)).await {
file file
} else { } else {
@ -118,7 +118,7 @@ pub async fn upload_avatar(
}; };
if let Some(user_info) = state.authenticated.get(&token) { if let Some(user_info) = state.authenticated.get(&token) {
log::info!( tracing::info!(
"{} ({}) trying to upload an avatar", "{} ({}) trying to upload an avatar",
user_info.uuid, user_info.uuid,
user_info.username user_info.username
@ -152,7 +152,7 @@ pub async fn delete_avatar(Token(token): Token, State(state): State<AppState>) -
None => http_error_ret!(UNAUTHORIZED, "Authentication error!"), None => http_error_ret!(UNAUTHORIZED, "Authentication error!"),
}; };
if let Some(user_info) = state.authenticated.get(&token) { if let Some(user_info) = state.authenticated.get(&token) {
log::info!( tracing::info!(
"{} ({}) is trying to delete the avatar", "{} ({}) is trying to delete the avatar",
user_info.uuid, user_info.uuid,
user_info.username user_info.username

View file

@ -8,7 +8,7 @@ use axum::{
response::Response, response::Response,
}; };
use dashmap::DashMap; use dashmap::DashMap;
use log::{debug, error, info, trace, warn}; use tracing::{debug, error, info, trace, warn};
use tokio::sync::{ use tokio::sync::{
broadcast::{self, Receiver}, broadcast::{self, Receiver},
mpsc, Notify, mpsc, Notify,