Skip to content

Commit 4e5b661

Browse files
committed
logging: Hide too verbose logs, introduce verbose logging by env variable
The system now provides clean, minimal logging by default while preserving all critical error information about upload/download disruptions or security issues. Debug mode (STORAGE_DEBUG=1) still shows all the verbose details when troubleshooting. Signed-off-by: Denys Fedoryshchenko <denys.f@collabora.com>
1 parent 330588d commit 4e5b661

4 files changed

Lines changed: 59 additions & 46 deletions

File tree

src/azure.rs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,15 @@ use serde::Deserialize;
2323
use std::fs::read_to_string;
2424
use std::fs::File;
2525
use std::io::Read;
26+
use std::env;
27+
28+
macro_rules! debug_log {
29+
($($arg:tt)*) => {
30+
if env::var("STORAGE_DEBUG").is_ok() {
31+
println!($($arg)*);
32+
}
33+
};
34+
}
2635
use std::io::Write;
2736
use std::sync::Arc;
2837
use tempfile::Builder;
@@ -250,7 +259,7 @@ async fn get_file_from_blob(filename: String) -> ReceivedFile {
250259
return received_file;
251260
} else {
252261
// delete cache file and headers
253-
println!("Cache file {} is zero length, deleting", cache_filename);
262+
debug_log!("Cache file {} is zero length, deleting", cache_filename);
254263
match std::fs::remove_file(&cache_filename) {
255264
Ok(_) => {}
256265
Err(e) => {
@@ -273,17 +282,12 @@ async fn get_file_from_blob(filename: String) -> ReceivedFile {
273282
}
274283
}
275284
}
276-
/*
277-
println!(
278-
"Downloading blob to cache file {} from {}",
279-
cache_filename, blob_url
280-
);
281-
*/
285+
debug_log!("Downloading blob to cache file {} from {}", cache_filename, blob_url);
282286
let client = Client::new();
283287
let response = client.get(blob_url).send().await;
284288
match response {
285289
Ok(response) => {
286-
println!("Response: {:?}", response);
290+
debug_log!("Azure response: {:?}", response);
287291
// is status anything else than 200?
288292
// TODO: Do we need to return headers as well or it is data leakage?
289293
if response.status() != 200 {
@@ -359,7 +363,7 @@ async fn azure_list_files(directory: String) -> Vec<String> {
359363
};
360364
listing.push(blob_name.clone());
361365
}
362-
println!("Listing count: {}", listing.len());
366+
debug_log!("Listing count: {}", listing.len());
363367
}
364368
//println!("Listing: {:?}", listing);
365369
listing

src/main.rs

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,16 @@ use axum_server::tls_rustls::RustlsConfig;
2626
use clap::Parser;
2727
use headers::HeaderMap;
2828
use std::path;
29-
use std::{net::SocketAddr, path::PathBuf};
29+
use std::{env, net::SocketAddr, path::PathBuf};
3030
use tokio::io::AsyncSeekExt;
31+
32+
macro_rules! debug_log {
33+
($($arg:tt)*) => {
34+
if env::var("STORAGE_DEBUG").is_ok() {
35+
println!($($arg)*);
36+
}
37+
};
38+
}
3139
use tokio_util::io::ReaderStream;
3240
use toml::Table;
3341
use tower::ServiceBuilder;
@@ -390,7 +398,6 @@ async fn ax_post_file(headers: HeaderMap, State(state): State<AppState>, mut mul
390398
if let Some(expect) = headers.get("Expect") {
391399
println!("Expect: {:?}", expect);
392400
if expect == "100-continue" {
393-
println!("Expect 100-continue");
394401
return (StatusCode::CONTINUE, Vec::new());
395402
}
396403
}
@@ -418,18 +425,17 @@ async fn ax_post_file(headers: HeaderMap, State(state): State<AppState>, mut mul
418425

419426
match data {
420427
Ok(data) => {
421-
println!("Length of `{}` is {} bytes", name, data.len());
428+
println!("Field {}: {} bytes", name, data.len());
422429
if name == "path" {
423430
path = String::from_utf8(data.to_vec()).unwrap();
424-
println!("Path: {}", path);
425431
} else if name == "file0" {
426432
file0 = data.to_vec();
427433
match filename {
428434
Some(filename) => file0_filename = filename.to_string(),
429435
None => todo!(),
430436
}
431437
} else {
432-
println!("Unknown field: {} len: {}", name, data.len());
438+
println!("Unknown field {}: {} bytes", name, data.len());
433439
}
434440
}
435441
Err(e) => {
@@ -441,12 +447,7 @@ async fn ax_post_file(headers: HeaderMap, State(state): State<AppState>, mut mul
441447
}
442448
}
443449
}
444-
println!(
445-
"File: {} bytes filename: {} path: {}",
446-
file0.len(),
447-
file0_filename,
448-
path
449-
);
450+
println!("Upload: {} bytes, {}/{}", file0.len(), path, file0_filename);
450451
// if path ends on /, remove it
451452
if path.ends_with("/") {
452453
// TBD: Fix it!
@@ -468,15 +469,11 @@ async fn ax_post_file(headers: HeaderMap, State(state): State<AppState>, mut mul
468469

469470
let content_type: String = match hdr_content_type {
470471
Some(content_type) => {
471-
println!("Content-Type: {:?}", content_type);
472472
content_type.to_str().unwrap().to_string()
473473
}
474474
None => {
475475
let heuristic_ctype = heuristic_filetype(file0_filename);
476-
println!(
477-
"Content-Type not found, using heuristics: {}",
478-
heuristic_ctype
479-
);
476+
debug_log!("Content-Type not found, using heuristics: {}", heuristic_ctype);
480477
heuristic_ctype
481478
}
482479
};
@@ -559,7 +556,6 @@ async fn ax_get_file(
559556
let metadata = tokio::fs::metadata(&cached_file).await.unwrap();
560557
let mut headers = HeaderMap::new();
561558
if let Some(content_type) = upstream_headers.get(CONTENT_TYPE) {
562-
println!("Stored content-Type: {:?}", content_type);
563559
headers.insert(header::CONTENT_TYPE, content_type.clone());
564560
} else {
565561
headers.insert(
@@ -631,12 +627,10 @@ async fn ax_get_file(
631627
let mut end = metadata.len();
632628
// is Content-Range present?
633629
if let Some(range) = rxheaders.get("Range") {
634-
println!("Range: {:?}", range);
635630
(start, end) = parse_range(range.to_str().unwrap());
636631
}
637632
// if start is set to non-zero, we need to seek
638633
if start != 0 && (end == metadata.len() || end == 0) {
639-
println!("Seeking to {}", start);
640634
file.seek(std::io::SeekFrom::Start(start)).await.unwrap();
641635
headers.insert(
642636
header::CONTENT_RANGE,
@@ -688,7 +682,7 @@ async fn ax_get_file(
688682
return (StatusCode::OK, headers, axbody).into_response();
689683
}
690684
Err(_) => {
691-
println!("Error opening file in ax_get_file");
685+
eprintln!("Error opening file in ax_get_file");
692686
println!(
693687
"{:?} 404 0 {} {} {} {}",
694688
remote_addr, human_time, method, filepath, user_agent_str
@@ -739,7 +733,7 @@ fn verify_auth_hdr(headers: &HeaderMap) -> Result<String, Option<String>> {
739733
let bmap = match verif_result {
740734
Ok(bmap) => bmap.clone(),
741735
Err(_) => {
742-
println!("Error verifying token");
736+
eprintln!("Error verifying token");
743737
return Err(None);
744738
}
745739
};
@@ -753,7 +747,7 @@ fn verify_auth_hdr(headers: &HeaderMap) -> Result<String, Option<String>> {
753747
let bmap = match verif_result {
754748
Ok(bmap) => bmap.clone(),
755749
Err(_) => {
756-
println!("Error verifying bearer token");
750+
eprintln!("Error verifying bearer token");
757751
return Err(None);
758752
}
759753
};

src/storcaching.rs

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
use std::fs;
22
use std::time::SystemTime;
33
use tokio::time::Duration;
4+
use std::env;
5+
6+
macro_rules! debug_log {
7+
($($arg:tt)*) => {
8+
if env::var("STORAGE_DEBUG").is_ok() {
9+
println!($($arg)*);
10+
}
11+
};
12+
}
413

514
struct Files {
615
file: String,
@@ -26,7 +35,7 @@ async fn read_filesinfo(cache_dir: String) -> Vec<Files> {
2635
files
2736
}
2837
Err(_) => {
29-
println!("Error reading files");
38+
eprintln!("Error reading cache directory files");
3039
Vec::new()
3140
}
3241
}
@@ -38,14 +47,14 @@ async fn freediskspace_percent(cache_dir: String) -> u64 {
3847
let total = match total_r {
3948
Ok(total) => total as f64,
4049
Err(_) => {
41-
println!("Error getting total space");
50+
eprintln!("Error getting disk total space");
4251
return 0;
4352
}
4453
};
4554
let free = match free_r {
4655
Ok(free) => free as f64,
4756
Err(_) => {
48-
println!("Error getting free space");
57+
eprintln!("Error getting disk free space");
4958
return 0;
5059
}
5160
};
@@ -58,22 +67,19 @@ fn delete_cache_file(file: String) {
5867
// Truncate from filename .content, and add .headers, delete both files
5968
let content_filename = file.clone();
6069
let headers_filename = file.replace(".content", ".headers");
61-
println!(
62-
"Deleting files: {} {}",
63-
&content_filename, &headers_filename
64-
);
70+
debug_log!("Deleting files: {} {}", &content_filename, &headers_filename);
6571
let res = fs::remove_file(&content_filename);
6672
match res {
6773
Ok(_) => {}
6874
Err(_) => {
69-
println!("Error deleting file: {}", content_filename);
75+
debug_log!("Error deleting file: {}", content_filename);
7076
}
7177
}
7278
let res = fs::remove_file(&headers_filename);
7379
match res {
7480
Ok(_) => {}
7581
Err(_) => {
76-
println!("Error deleting file: {}", headers_filename);
82+
debug_log!("Error deleting file: {}", headers_filename);
7783
}
7884
}
7985
}
@@ -93,7 +99,7 @@ async fn clean_disk(cache_dir: String) {
9399
if oldest_file.last_update.elapsed().unwrap() > Duration::from_secs(60 * 60) {
94100
delete_cache_file(oldest_file.file);
95101
} else {
96-
println!("File is less than 60 min old, skipping: {}, sleeping 60 seconds", oldest_file.file);
102+
debug_log!("File is less than 60 min old, skipping: {}, sleeping 60 seconds", oldest_file.file);
97103
// sleep 60 seconds
98104
tokio::time::sleep(Duration::from_secs(60)).await;
99105
}
@@ -119,7 +125,7 @@ pub async fn cache_loop(cache_dir: &str) {
119125
// critical mode, sleep only 100ms
120126
tokio::time::sleep(Duration::from_millis(100)).await;
121127
} else {
122-
println!("Free disk space: {}%", free_space);
128+
debug_log!("Free disk space: {}%", free_space);
123129
// normal mode, sleep 10 seconds
124130
tokio::time::sleep(Duration::from_secs(10)).await;
125131
}

src/storjwt.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,15 @@ use jwt::{Header, SignWithKey, Token, VerifyWithKey};
44
use sha2::Sha256;
55
use std::collections::BTreeMap;
66
use toml::value::Table;
7+
use std::env;
8+
9+
macro_rules! debug_log {
10+
($($arg:tt)*) => {
11+
if env::var("STORAGE_DEBUG").is_ok() {
12+
println!($($arg)*);
13+
}
14+
};
15+
}
716
pub fn verify_jwt_token(token_str: &str) -> Result<BTreeMap<String, String>, jwt::Error> {
817
// config.toml, jwt_secret parameter
918
let toml_cfg = get_config_content();
@@ -14,7 +23,7 @@ pub fn verify_jwt_token(token_str: &str) -> Result<BTreeMap<String, String>, jwt
1423
let token: Token<Header, BTreeMap<String, String>, _> = match verify_result {
1524
Ok(token) => token,
1625
Err(e) => {
17-
println!("verify_result Error: {:?} token_str: {}", e, token_str);
26+
eprintln!("JWT verification error: {:?}", e);
1827
return Err(e);
1928
}
2029
};
@@ -23,10 +32,10 @@ pub fn verify_jwt_token(token_str: &str) -> Result<BTreeMap<String, String>, jwt
2332
let email = claims.get("email");
2433
match email {
2534
Some(email) => {
26-
println!("email: {}", email);
35+
debug_log!("email: {}", email);
2736
}
2837
None => {
29-
println!("email not found");
38+
debug_log!("email not found");
3039
return Err(jwt::Error::InvalidSignature);
3140
}
3241
}
@@ -42,7 +51,7 @@ pub fn generate_jwt_secret() {
4251
.take(32)
4352
.map(char::from)
4453
.collect();
45-
println!("jwt_secret=\"{}\"", secret);
54+
debug_log!("jwt_secret=\"{}\"", secret);
4655
}
4756

4857
pub fn generate_jwt_token(email: &str) -> Result<String, jwt::Error> {

0 commit comments

Comments
 (0)