|
| 1 | +// This file is Copyright its original authors, visible in version control |
| 2 | +// history. |
| 3 | +// |
| 4 | +// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE |
| 5 | +// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 6 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. |
| 7 | +// You may not use this file except in accordance with one or both of these |
| 8 | +// licenses. |
| 9 | + |
| 10 | +use std::fs::{self, File, OpenOptions}; |
| 11 | +use std::io::{self, Write}; |
| 12 | +use std::path::{Path, PathBuf}; |
| 13 | +use std::sync::{Arc, Mutex}; |
| 14 | + |
| 15 | +use log::{Level, LevelFilter, Log, Metadata, Record}; |
| 16 | + |
| 17 | +/// A logger implementation that writes logs to both stderr and a file. |
| 18 | +/// |
| 19 | +/// The logger formats log messages with RFC3339 timestamps and writes them to: |
| 20 | +/// - stdout/stderr for console output |
| 21 | +/// - A file specified during initialization |
| 22 | +/// |
| 23 | +/// All log messages follow the format: |
| 24 | +/// `[TIMESTAMP LEVEL TARGET FILE:LINE] MESSAGE` |
| 25 | +/// |
| 26 | +/// Example: `[2025-12-04T10:30:45Z INFO ldk_server:42] Starting up...` |
| 27 | +/// |
| 28 | +/// The logger handles SIGHUP for log rotation by reopening the file handle when signaled. |
| 29 | +pub struct ServerLogger { |
| 30 | + /// The maximum log level to display |
| 31 | + level: LevelFilter, |
| 32 | + /// The file to write logs to, protected by a mutex for thread-safe access |
| 33 | + file: Mutex<File>, |
| 34 | + /// Path to the log file for reopening on SIGHUP |
| 35 | + log_file_path: PathBuf, |
| 36 | +} |
| 37 | + |
| 38 | +impl ServerLogger { |
| 39 | + /// Initializes the global logger with the specified level and file path. |
| 40 | + /// |
| 41 | + /// Opens or creates the log file at the given path. If the file exists, logs are appended. |
| 42 | + /// If the file doesn't exist, it will be created along with any necessary parent directories. |
| 43 | + /// |
| 44 | + /// This should be called once at application startup. Subsequent calls will fail. |
| 45 | + /// |
| 46 | + /// Returns an Arc to the logger for signal handling purposes. |
| 47 | + pub fn init(level: LevelFilter, log_file_path: &Path) -> Result<Arc<Self>, io::Error> { |
| 48 | + // Create parent directories if they don't exist |
| 49 | + if let Some(parent) = log_file_path.parent() { |
| 50 | + fs::create_dir_all(parent)?; |
| 51 | + } |
| 52 | + |
| 53 | + let file = open_log_file(log_file_path)?; |
| 54 | + |
| 55 | + let logger = Arc::new(ServerLogger { |
| 56 | + level, |
| 57 | + file: Mutex::new(file), |
| 58 | + log_file_path: log_file_path.to_path_buf(), |
| 59 | + }); |
| 60 | + |
| 61 | + log::set_boxed_logger(Box::new(LoggerWrapper(Arc::clone(&logger)))) |
| 62 | + .map_err(io::Error::other)?; |
| 63 | + log::set_max_level(level); |
| 64 | + Ok(logger) |
| 65 | + } |
| 66 | + |
| 67 | + /// Reopens the log file. Called on SIGHUP for log rotation. |
| 68 | + pub fn reopen(&self) -> Result<(), io::Error> { |
| 69 | + let new_file = open_log_file(&self.log_file_path)?; |
| 70 | + match self.file.lock() { |
| 71 | + Ok(mut file) => { |
| 72 | + // Flush the old buffer before replacing with the new file |
| 73 | + file.flush()?; |
| 74 | + *file = new_file; |
| 75 | + Ok(()) |
| 76 | + }, |
| 77 | + Err(e) => Err(io::Error::other(format!("Failed to acquire lock: {e}"))), |
| 78 | + } |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +impl Log for ServerLogger { |
| 83 | + fn enabled(&self, metadata: &Metadata) -> bool { |
| 84 | + metadata.level() <= self.level |
| 85 | + } |
| 86 | + |
| 87 | + fn log(&self, record: &Record) { |
| 88 | + if self.enabled(record.metadata()) { |
| 89 | + let level_str = format_level(record.level()); |
| 90 | + let line = record.line().unwrap_or(0); |
| 91 | + |
| 92 | + // Log to console |
| 93 | + let _ = match record.level() { |
| 94 | + Level::Error => { |
| 95 | + writeln!( |
| 96 | + io::stderr(), |
| 97 | + "[{} {} {}:{}] {}", |
| 98 | + format_timestamp(), |
| 99 | + level_str, |
| 100 | + record.target(), |
| 101 | + line, |
| 102 | + record.args() |
| 103 | + ) |
| 104 | + }, |
| 105 | + _ => { |
| 106 | + writeln!( |
| 107 | + io::stdout(), |
| 108 | + "[{} {} {}:{}] {}", |
| 109 | + format_timestamp(), |
| 110 | + level_str, |
| 111 | + record.target(), |
| 112 | + line, |
| 113 | + record.args() |
| 114 | + ) |
| 115 | + }, |
| 116 | + }; |
| 117 | + |
| 118 | + // Log to file |
| 119 | + if let Ok(mut file) = self.file.lock() { |
| 120 | + let _ = writeln!( |
| 121 | + file, |
| 122 | + "[{} {} {}:{}] {}", |
| 123 | + format_timestamp(), |
| 124 | + level_str, |
| 125 | + record.target(), |
| 126 | + line, |
| 127 | + record.args() |
| 128 | + ); |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + fn flush(&self) { |
| 134 | + let _ = io::stdout().flush(); |
| 135 | + let _ = io::stderr().flush(); |
| 136 | + if let Ok(mut file) = self.file.lock() { |
| 137 | + let _ = file.flush(); |
| 138 | + } |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +fn format_timestamp() -> String { |
| 143 | + let now = chrono::Utc::now(); |
| 144 | + now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true) |
| 145 | +} |
| 146 | + |
| 147 | +fn format_level(level: Level) -> &'static str { |
| 148 | + match level { |
| 149 | + Level::Error => "ERROR", |
| 150 | + Level::Warn => "WARN ", |
| 151 | + Level::Info => "INFO ", |
| 152 | + Level::Debug => "DEBUG", |
| 153 | + Level::Trace => "TRACE", |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +fn open_log_file(log_file_path: &Path) -> Result<File, io::Error> { |
| 158 | + OpenOptions::new().create(true).append(true).open(log_file_path) |
| 159 | +} |
| 160 | + |
| 161 | +/// Wrapper to allow Arc<ServerLogger> to implement Log trait |
| 162 | +struct LoggerWrapper(Arc<ServerLogger>); |
| 163 | + |
| 164 | +impl Log for LoggerWrapper { |
| 165 | + fn enabled(&self, metadata: &Metadata) -> bool { |
| 166 | + self.0.enabled(metadata) |
| 167 | + } |
| 168 | + |
| 169 | + fn log(&self, record: &Record) { |
| 170 | + self.0.log(record) |
| 171 | + } |
| 172 | + |
| 173 | + fn flush(&self) { |
| 174 | + self.0.flush() |
| 175 | + } |
| 176 | +} |
0 commit comments