From 5cf2b0c5689307b5bec113dff551c30ca8649ab6 Mon Sep 17 00:00:00 2001 From: Jun Kurihara Date: Mon, 28 Apr 2025 19:09:48 +0900 Subject: [PATCH] wip: impelement file logger --- README.md | 4 ++-- rpxy-bin/src/log.rs | 37 ++++++++++++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 2f90401..e114859 100644 --- a/README.md +++ b/README.md @@ -97,8 +97,8 @@ Options: If you set `--log-dir=`, the log files are created in the specified directory. Otherwise, the log is printed to stdout. - `${log_dir}/access.log` for access log -- `${log_dir}/error.log` for error log -- `${log_dir}/rpxy.log` for system log + +- `${log_dir}/rpxy.log` for system and error log That's all! diff --git a/rpxy-bin/src/log.rs b/rpxy-bin/src/log.rs index 3a9d6bd..16a6b60 100644 --- a/rpxy-bin/src/log.rs +++ b/rpxy-bin/src/log.rs @@ -6,14 +6,30 @@ pub use tracing::{debug, error, info, warn}; /// Initialize the logger with the RUST_LOG environment variable. pub fn init_logger(log_dir_path: Option<&str>) { - if log_dir_path.is_some() { - // TODO: - println!("Activate logging to files") - } - let level_string = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string()); let level = tracing::Level::from_str(level_string.as_str()).unwrap_or(tracing::Level::INFO); + match log_dir_path { + None => { + // log to stdout + init_stdio_logger(level); + } + Some(log_dir_path) => { + // log to files + println!("Activate logging to files: {log_dir_path}"); + init_file_logger(level, log_dir_path); + } + } +} + +/// file logging +fn init_file_logger(level: tracing::Level, log_dir_path: &str) { + // TODO: implement + init_stdio_logger(level); +} + +/// stdio logging +fn init_stdio_logger(level: tracing::Level) { // This limits the logger to emits only this crate with any level above RUST_LOG, for included crates it will emit only ERROR (in prod)/INFO (in dev) or above level. let stdio_layer = fmt::layer().with_level(true).with_thread_ids(false); if level <= tracing::Level::INFO { @@ -47,3 +63,14 @@ pub fn init_logger(log_dir_path: Option<&str>) { tracing_subscriber::registry().with(stdio_layer).init(); }; } + +#[inline] +/// Create a file for logging +fn open_log_file(path: &str) -> std::fs::File { + // crate a file if it does not exist + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .expect("Failed to open the log file") +}