Files
web-scraper-rust/src/error_logger.rs
T
2026-08-15 21:21:43 +01:00

52 lines
1.3 KiB
Rust

use chrono::{DateTime, Utc};
use serde::Serialize;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;
use url::Url;
#[derive(Serialize)]
pub struct ErrorEntry {
pub timestamp: DateTime<Utc>,
pub url: String,
pub error_type: String,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub status_code: Option<u16>,
}
pub fn log_error(
log_path: &Path,
url: &Url,
error_type: &str,
message: &str,
status_code: Option<u16>,
) {
let entry = ErrorEntry {
timestamp: Utc::now(),
url: url.to_string(),
error_type: error_type.to_string(),
message: message.to_string(),
status_code,
};
let line = match serde_json::to_string(&entry) {
Ok(json) => json + "\n",
Err(e) => {
log::error!("Failed to serialize error entry: {}", e);
return;
}
};
if let Ok(mut file) = OpenOptions::new().append(true).create(true).open(log_path) {
if let Err(e) = file.write_all(line.as_bytes()) {
log::error!("Failed to write error log: {}", e);
} else {
let _ = file.flush();
log::info!("LOGGED ERROR [{}]: {}", error_type, message);
}
} else {
log::error!("Failed to open error log file: {}", log_path.display());
}
}