1use crate::error::SpriteError;
7use anyhow::Result;
8use chrono::{DateTime, Local, Utc};
9use log::{Level, LevelFilter, Log, Metadata, Record};
10use std::fs::{File, OpenOptions};
11use std::io::{BufWriter, Write};
12use std::path::{Path, PathBuf};
13use std::sync::Mutex;
14
15#[derive(Debug, Clone)]
17#[allow(dead_code)]
18pub struct LoggerConfig {
19 pub log_file: Option<PathBuf>,
21 pub level: Level,
23 pub log_to_stdout: bool,
25 pub include_timestamp: bool,
27 pub include_module: bool,
29 pub use_colors: bool,
31}
32
33impl Default for LoggerConfig {
34 fn default() -> Self {
35 Self {
36 log_file: Some(PathBuf::from("logs/sprite.log")),
37 level: Level::Info,
38 log_to_stdout: true,
39 include_timestamp: true,
40 include_module: true,
41 use_colors: true,
42 }
43 }
44}
45
46#[allow(dead_code)]
48pub struct SpriteLogger {
49 config: LoggerConfig,
50 log_file: Option<Mutex<BufWriter<File>>>,
51 #[allow(dead_code)]
52 start_time: DateTime<Utc>,
53}
54
55impl SpriteLogger {
56 #[allow(dead_code)]
58 pub fn new(config: LoggerConfig) -> Result<Self> {
59 let log_file = if let Some(ref log_path) = config.log_file {
60 if let Some(parent) = log_path.parent() {
62 std::fs::create_dir_all(parent).map_err(|e| {
63 SpriteError::filesystem_with_source(
64 format!("Failed to create log directory: {}", e),
65 parent.display().to_string(),
66 e,
67 )
68 })?;
69 }
70
71 let file = OpenOptions::new()
72 .create(true)
73 .append(true)
74 .open(log_path)
75 .map_err(|e| {
76 SpriteError::filesystem_with_source(
77 format!("Failed to open log file: {}", e),
78 log_path.display().to_string(),
79 e,
80 )
81 })?;
82
83 Some(Mutex::new(BufWriter::new(file)))
84 } else {
85 None
86 };
87
88 Ok(Self {
89 config,
90 log_file,
91 start_time: Utc::now(),
92 })
93 }
94
95 #[allow(dead_code)]
97 fn write_log(&self, level: Level, record: &Record) {
98 let message = record.args().to_string();
99
100 let formatted = self.format_message(
101 level.to_level_filter(),
102 &message,
103 record.file(),
104 record.line(),
105 );
106
107 if let Some(ref file_mutex) = self.log_file {
109 if let Ok(mut file) = file_mutex.lock() {
110 let _ = writeln!(file, "{}", formatted);
111 let _ = file.flush();
112 }
113 }
114
115 if self.config.log_to_stdout {
117 eprintln!("{}", formatted);
118 }
119 }
120
121 #[allow(dead_code)]
123 fn format_message(
124 &self,
125 level: LevelFilter,
126 message: &str,
127 file: Option<&str>,
128 line: Option<u32>,
129 ) -> String {
130 let mut parts = Vec::new();
131
132 if self.config.include_timestamp {
134 parts.push(Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
135 }
136
137 if self.config.use_colors {
139 let level_str = match level {
140 LevelFilter::Error => "\x1b[31mERROR\x1b[0m".to_string(),
141 LevelFilter::Warn => "\x1b[33mWARN \x1b[0m".to_string(),
142 LevelFilter::Info => "\x1b[32mINFO \x1b[0m".to_string(),
143 LevelFilter::Debug => "\x1b[36mDEBUG\x1b[0m".to_string(),
144 LevelFilter::Trace => "\x1b[37mTRACE\x1b[0m".to_string(),
145 _ => "UNKNOWN".to_string(),
146 };
147 parts.push(level_str);
148 } else {
149 let level_str = match level {
150 LevelFilter::Error => "ERROR".to_string(),
151 LevelFilter::Warn => "WARN ".to_string(),
152 LevelFilter::Info => "INFO ".to_string(),
153 LevelFilter::Debug => "DEBUG".to_string(),
154 LevelFilter::Trace => "TRACE".to_string(),
155 _ => "UNKNOWN".to_string(),
156 };
157 parts.push(level_str);
158 }
159
160 if self.config.include_module {
162 if let Some(file) = file {
163 let module = file.rfind('/').map(|i| &file[i + 1..]).unwrap_or(file);
164 parts.push(format!("[{}]", module));
165 }
166 }
167
168 if let Some(line) = line {
170 parts.push(format!(":{}", line));
171 }
172
173 parts.push(message.to_string());
175
176 parts.join(" ")
177 }
178
179 #[allow(dead_code)]
181 fn should_log(&self, level: LevelFilter) -> bool {
182 level <= self.config.level
183 }
184
185 #[allow(dead_code)]
187 pub fn flush(&self) -> Result<()> {
188 if let Some(ref file_mutex) = self.log_file {
189 if let Ok(mut file) = file_mutex.lock() {
190 file.flush()?;
191 }
192 }
193 Ok(())
194 }
195
196 #[allow(dead_code)]
198 pub fn start_time(&self) -> DateTime<Utc> {
199 self.start_time
200 }
201
202 #[allow(dead_code)]
204 pub fn uptime(&self) -> chrono::Duration {
205 Utc::now() - self.start_time
206 }
207}
208
209impl Log for SpriteLogger {
210 fn enabled(&self, metadata: &Metadata) -> bool {
211 self.should_log(metadata.level().to_level_filter())
212 }
213
214 fn log(&self, record: &Record) {
215 if self.should_log(record.level().to_level_filter()) {
216 self.write_log(record.level(), record);
217 }
218 }
219
220 fn flush(&self) {
221 let _ = self.flush();
222 }
223}
224
225#[allow(dead_code)]
227pub fn init_logging(config: LoggerConfig) -> Result<()> {
228 let logger = SpriteLogger::new(config)?;
229 let _ = log::set_boxed_logger(Box::new(logger));
230 Ok(())
231}
232
233#[allow(dead_code)]
235pub fn init_default_logging() -> Result<()> {
236 init_logging(LoggerConfig::default())
237}
238
239#[allow(dead_code)]
241pub fn init_file_logging<P: AsRef<Path>>(log_file: P, level: Level) -> Result<()> {
242 let config = LoggerConfig {
243 log_file: Some(log_file.as_ref().to_path_buf()),
244 level,
245 log_to_stdout: true,
246 include_timestamp: true,
247 include_module: true,
248 use_colors: true,
249 };
250 init_logging(config)
251}
252
253#[allow(dead_code)]
255pub fn init_script_logging<P: AsRef<Path>>(log_file: P, level: Level) -> Result<()> {
256 let config = LoggerConfig {
257 log_file: Some(log_file.as_ref().to_path_buf()),
258 level,
259 log_to_stdout: false,
260 include_timestamp: true,
261 include_module: false,
262 use_colors: false,
263 };
264 init_logging(config)
265}
266
267#[allow(dead_code)]
269pub fn get_log_level() -> LevelFilter {
270 log::max_level()
271}
272
273#[allow(dead_code)]
275pub fn set_log_level(level: LevelFilter) {
276 log::set_max_level(level);
277}
278
279#[allow(dead_code)]
281pub struct RotatingLogger {
282 config: LoggerConfig,
283 #[allow(dead_code)]
284 base_path: PathBuf,
285 #[allow(dead_code)]
286 current_file: PathBuf,
287 max_size: u64,
288 current_size: std::sync::atomic::AtomicU64,
289 file: Option<Mutex<BufWriter<File>>>,
290 #[allow(dead_code)]
291 start_time: DateTime<Utc>,
292}
293
294impl RotatingLogger {
295 #[allow(dead_code)]
297 pub fn new<P: AsRef<Path>>(base_path: P, max_size: u64, level: Level) -> Result<Self> {
298 let base_path = base_path.as_ref().to_path_buf();
299 let current_file = base_path.join(format!("{}.log", Local::now().format("%Y%m%d_%H%M%S")));
300
301 let config = LoggerConfig {
302 log_file: Some(current_file.clone()),
303 level,
304 log_to_stdout: true,
305 include_timestamp: true,
306 include_module: true,
307 use_colors: true,
308 };
309
310 let file = Self::create_log_file(¤t_file)?;
311 let current_size = Self::get_file_size(¤t_file)?;
312
313 Ok(Self {
314 config,
315 base_path,
316 current_file,
317 max_size,
318 current_size: std::sync::atomic::AtomicU64::new(current_size),
319 file: Some(Mutex::new(BufWriter::new(file))),
320 start_time: Utc::now(),
321 })
322 }
323
324 #[allow(dead_code)]
326 fn create_log_file(path: &Path) -> Result<File> {
327 if let Some(parent) = path.parent() {
329 std::fs::create_dir_all(parent).map_err(|e| {
330 SpriteError::filesystem_with_source(
331 format!("Failed to create log directory: {}", e),
332 parent.display().to_string(),
333 e,
334 )
335 })?;
336 }
337
338 Ok(OpenOptions::new()
339 .create(true)
340 .append(true)
341 .open(path)
342 .map_err(|e| {
343 SpriteError::filesystem_with_source(
344 format!("Failed to create log file: {}", e),
345 path.display().to_string(),
346 e,
347 )
348 })?)
349 }
350
351 #[allow(dead_code)]
353 fn get_file_size(path: &Path) -> Result<u64> {
354 let metadata = std::fs::metadata(path).map_err(|e| {
355 SpriteError::filesystem_with_source(
356 format!("Failed to get file size: {}", e),
357 path.display().to_string(),
358 e,
359 )
360 })?;
361 Ok(metadata.len())
362 }
363
364 #[allow(dead_code)]
366 fn write_log_with_rotation(&self, level: LevelFilter, record: &Record) {
367 let message = record.args().to_string();
368 let formatted = self.format_message(level, &message, record.file(), record.line());
369
370 if self.current_size.load(std::sync::atomic::Ordering::Relaxed) >= self.max_size {
372 eprintln!("Log rotation needed but not implemented in this context");
373 }
374
375 if let Some(ref file_mutex) = self.file {
377 if let Ok(mut file) = file_mutex.lock() {
378 let content = format!("{}\n", formatted);
379 if file.write(content.as_bytes()).is_ok() {
380 }
382 let _ = file.flush();
383 }
384 }
385
386 if self.config.log_to_stdout {
388 eprintln!("{}", formatted);
389 }
390 }
391
392 #[allow(dead_code)]
394 fn rotate_files(&self) -> Result<()> {
395 eprintln!("Log rotation is needed but not fully implemented");
397 Ok(())
398 }
399
400 #[allow(dead_code)]
402 fn cleanup_old_files(&self) -> Result<()> {
403 if let Ok(entries) = std::fs::read_dir(&self.base_path) {
405 let mut files: Vec<_> = entries
406 .filter_map(|entry| entry.ok())
407 .filter(|entry| {
408 let binding = entry.file_name();
409 let file_name = binding.to_string_lossy();
410 file_name.ends_with(".log")
411 && Some(file_name.as_ref())
412 != self
413 .current_file
414 .file_name()
415 .map(|n| n.to_string_lossy())
416 .as_deref()
417 })
418 .collect();
419
420 files.sort_by_key(|entry| {
422 entry
423 .metadata()
424 .and_then(|m| m.modified())
425 .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
426 });
427
428 if files.len() > 5 {
430 for old_file in &files[..files.len() - 5] {
431 let _ = std::fs::remove_file(old_file.path());
432 eprintln!("Removed old log file: {}", old_file.path().display());
433 }
434 }
435 }
436
437 Ok(())
438 }
439
440 #[allow(dead_code)]
442 fn format_message(
443 &self,
444 level: LevelFilter,
445 message: &str,
446 file: Option<&str>,
447 line: Option<u32>,
448 ) -> String {
449 let mut parts = Vec::new();
450
451 if self.config.include_timestamp {
452 parts.push(Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
453 }
454
455 let level_str = match level {
456 LevelFilter::Error => "\x1b[31mERROR\x1b[0m".to_string(),
457 LevelFilter::Warn => "\x1b[33mWARN \x1b[0m".to_string(),
458 LevelFilter::Info => "\x1b[32mINFO \x1b[0m".to_string(),
459 LevelFilter::Debug => "\x1b[36mDEBUG\x1b[0m".to_string(),
460 LevelFilter::Trace => "\x1b[37mTRACE\x1b[0m".to_string(),
461 _ => "UNKNOWN".to_string(),
462 };
463 parts.push(level_str);
464
465 if self.config.include_module {
466 if let Some(file) = file {
467 let module = file.rfind('/').map(|i| &file[i + 1..]).unwrap_or(file);
468 parts.push(format!("[{}]", module));
469 }
470 }
471
472 if let Some(line) = line {
473 parts.push(format!(":{}", line));
474 }
475
476 parts.push(message.to_string());
477
478 parts.join(" ")
479 }
480
481 #[allow(dead_code)]
483 fn should_log(&self, level: LevelFilter) -> bool {
484 level <= self.config.level
485 }
486
487 #[allow(dead_code)]
489 pub fn current_file(&self) -> &PathBuf {
490 &self.current_file
491 }
492
493 #[allow(dead_code)]
495 pub fn start_time(&self) -> DateTime<Utc> {
496 self.start_time
497 }
498}
499
500impl Log for RotatingLogger {
501 fn enabled(&self, metadata: &Metadata) -> bool {
502 self.should_log(metadata.level().to_level_filter())
503 }
504
505 fn log(&self, record: &Record) {
506 if self.should_log(record.level().to_level_filter()) {
507 self.write_log_with_rotation(record.level().to_level_filter(), record);
508 }
509 }
510
511 fn flush(&self) {
512 if let Some(ref file_mutex) = self.file {
513 if let Ok(mut file) = file_mutex.lock() {
514 let _ = file.flush();
515 }
516 }
517 }
518}
519
520#[allow(dead_code)]
522pub fn init_rotating_logging<P: AsRef<Path>>(
523 log_dir: P,
524 max_size_mb: u64,
525 level: Level,
526) -> Result<()> {
527 let max_size_bytes = max_size_mb * 1024 * 1024;
528 let logger = RotatingLogger::new(log_dir, max_size_bytes, level)?;
529 let _ = log::set_boxed_logger(Box::new(logger));
530 Ok(())
531}
532
533#[allow(dead_code)]
535pub fn init_default_rotating_logging() -> Result<()> {
536 init_rotating_logging("logs", 10, Level::Info)
537}
538
539#[cfg(test)]
540mod tests {
541 use super::*;
542 use tempfile::TempDir;
543
544 #[test]
545 fn test_logger_config_default() {
546 let config = LoggerConfig::default();
547 assert!(config.log_file.is_some());
548 assert_eq!(config.level, Level::Info);
549 assert!(config.log_to_stdout);
550 assert!(config.include_timestamp);
551 assert!(config.include_module);
552 assert!(config.use_colors);
553 }
554
555 #[test]
556 fn test_sprite_logger_creation() {
557 let config = LoggerConfig {
558 log_file: None,
559 level: Level::Debug,
560 log_to_stdout: false,
561 include_timestamp: false,
562 include_module: false,
563 use_colors: false,
564 };
565
566 let logger = SpriteLogger::new(config);
567 assert!(logger.is_ok());
568 }
569
570 #[test]
571 fn test_rotating_logger() {
572 let temp_dir = TempDir::new().unwrap();
573 let logger = RotatingLogger::new(temp_dir.path(), 100, Level::Info);
574 assert!(logger.is_ok());
575 }
576}