Coverage for /Users/les/Projects/crackerjack/crackerjack/services/log_manager.py: 0%
141 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import logging
2import os
3import shutil
4import time
5from contextlib import suppress
6from pathlib import Path
8from rich.console import Console
10console = Console()
13class LogManager:
14 def __init__(self, app_name: str = "crackerjack") -> None:
15 self.app_name = app_name
16 self._log_dir = self._get_log_directory()
17 self._setup_directories()
19 def _get_log_directory(self) -> Path:
20 cache_home = os.environ.get("XDG_CACHE_HOME")
21 base_dir = Path(cache_home) if cache_home else Path.home() / ".cache"
23 return base_dir / self.app_name / "logs"
25 def _setup_directories(self) -> None:
26 self._log_dir.mkdir(parents=True, exist_ok=True)
28 (self._log_dir / "debug").mkdir(exist_ok=True)
29 (self._log_dir / "error").mkdir(exist_ok=True)
30 (self._log_dir / "audit").mkdir(exist_ok=True)
32 @property
33 def log_dir(self) -> Path:
34 return self._log_dir
36 @property
37 def debug_dir(self) -> Path:
38 return self._log_dir / "debug"
40 @property
41 def error_dir(self) -> Path:
42 return self._log_dir / "error"
44 @property
45 def audit_dir(self) -> Path:
46 return self._log_dir / "audit"
48 def create_debug_log_file(self, session_id: str | None = None) -> Path:
49 timestamp = int(time.time())
50 if session_id:
51 filename = f"debug -{timestamp}-{session_id}.log"
52 else:
53 filename = f"debug -{timestamp}.log"
55 return self.debug_dir / filename
57 def create_error_log_file(self, error_type: str = "general") -> Path:
58 timestamp = int(time.time())
59 filename = f"error -{error_type}-{timestamp}.log"
60 return self.error_dir / filename
62 def rotate_logs(
63 self,
64 log_dir: Path,
65 pattern: str,
66 max_files: int = 10,
67 max_age_days: int = 30,
68 ) -> int:
69 if not log_dir.exists():
70 return 0
72 removed_count = 0
73 cutoff_time = time.time() - (max_age_days * 24 * 60 * 60)
75 log_files = sorted(
76 log_dir.glob(pattern),
77 key=lambda p: p.stat().st_mtime,
78 reverse=True,
79 )
81 for i, log_file in enumerate(log_files):
82 should_remove = False
83 reason = ""
85 if i >= max_files:
86 should_remove = True
87 reason = f"exceeds max files ({max_files})"
89 elif log_file.stat().st_mtime < cutoff_time:
90 should_remove = True
91 reason = f"older than {max_age_days} days"
93 if should_remove:
94 with suppress(OSError, PermissionError):
95 log_file.unlink()
96 removed_count += 1
97 console.print(
98 f"[dim]🗑️ Removed old log: {log_file.name} ({reason})[/ dim]",
99 )
101 return removed_count
103 def cleanup_all_logs(
104 self,
105 debug_max_files: int = 10,
106 error_max_files: int = 20,
107 audit_max_files: int = 50,
108 max_age_days: int = 30,
109 ) -> dict[str, int]:
110 results = {}
112 results["debug"] = self.rotate_logs(
113 self.debug_dir,
114 "debug-*.log",
115 debug_max_files,
116 max_age_days,
117 )
119 results["error"] = self.rotate_logs(
120 self.error_dir,
121 "error-*.log",
122 error_max_files,
123 max_age_days,
124 )
126 results["audit"] = self.rotate_logs(
127 self.audit_dir,
128 "audit-*.log",
129 audit_max_files,
130 max_age_days,
131 )
133 return results
135 def migrate_legacy_logs(
136 self,
137 source_dir: Path,
138 dry_run: bool = False,
139 ) -> dict[str, int]:
140 if not source_dir.exists():
141 return {"moved": 0, "failed": 0, "found": 0}
143 debug_pattern = "crackerjack - debug-*.log"
144 legacy_files = list(source_dir.glob(debug_pattern))
146 results = {"found": len(legacy_files), "moved": 0, "failed": 0}
148 if not legacy_files:
149 console.print("[green]✅ No legacy log files found to migrate[/ green]")
150 return results
152 console.print(
153 f"[yellow]📦 Found {len(legacy_files)} legacy debug log files to migrate[/ yellow]",
154 )
156 for legacy_file in legacy_files:
157 try:
158 parts = legacy_file.stem.split("-")
159 if len(parts) >= 3 and parts[-1].isdigit():
160 timestamp = parts[-1]
161 else:
162 timestamp = str(int(legacy_file.stat().st_mtime))
164 new_filename = f"debug -{timestamp}- migrated.log"
165 new_path = self.debug_dir / new_filename
167 if dry_run:
168 console.print(
169 f"[cyan]📋 Would move: {legacy_file.name} → {new_filename}[/ cyan]",
170 )
171 results["moved"] += 1
172 else:
173 shutil.move(str(legacy_file), str(new_path))
174 results["moved"] += 1
175 console.print(
176 f"[green]✅ Moved: {legacy_file.name} → {new_filename}[/ green]",
177 )
179 except (OSError, ValueError) as e:
180 results["failed"] += 1
181 console.print(
182 f"[red]❌ Failed to migrate {legacy_file.name}: {e}[/ red]",
183 )
185 return results
187 def get_log_stats(self) -> dict[str, dict[str, int | str]]:
188 stats = {}
190 for log_type, log_dir in (
191 ("debug", self.debug_dir),
192 ("error", self.error_dir),
193 ("audit", self.audit_dir),
194 ):
195 if log_dir.exists():
196 files = list(log_dir.glob("*.log"))
197 total_size = sum(f.stat().st_size for f in files if f.exists())
199 stats[log_type] = {
200 "count": len(files),
201 "size_mb": round(total_size / (1024 * 1024), 2),
202 "location": str(log_dir),
203 }
204 else:
205 stats[log_type] = {
206 "count": 0,
207 "size_mb": 0.0,
208 "location": str(log_dir),
209 }
211 return stats
213 def setup_rotating_file_handler(
214 self,
215 logger: logging.Logger,
216 log_type: str = "debug",
217 max_bytes: int = 10 * 1024 * 1024,
218 backup_count: int = 5,
219 ) -> logging.FileHandler:
220 from logging.handlers import RotatingFileHandler
222 if log_type == "error":
223 log_dir = self.error_dir
224 elif log_type == "audit":
225 log_dir = self.audit_dir
226 else:
227 log_dir = self.debug_dir
229 log_file = log_dir / f"{log_type}.log"
231 handler = RotatingFileHandler(
232 log_file,
233 maxBytes=max_bytes,
234 backupCount=backup_count,
235 encoding="utf-8",
236 )
238 formatter = logging.Formatter(
239 "%(asctime)s - %(name)s - %(levelname)s-%(message)s",
240 )
241 handler.setFormatter(formatter)
243 logger.addHandler(handler)
245 return handler
247 def print_log_summary(self) -> None:
248 stats = self.get_log_stats()
250 console.print("\n[bold]📊 Log File Summary[/ bold]")
251 console.print(f"[dim]Location: {self.log_dir}[/ dim]")
253 total_files = 0
254 total_size = 0.0
256 for log_type, data in stats.items():
257 count = (
258 int(data["count"]) if isinstance(data["count"], str) else data["count"]
259 )
260 size = (
261 float(data["size_mb"])
262 if isinstance(data["size_mb"], str)
263 else data["size_mb"]
264 )
266 total_files += count
267 total_size += size
269 if count > 0:
270 console.print(f" {log_type.capitalize()}: {count} files, {size}MB")
271 else:
272 console.print(f" {log_type.capitalize()}: No files")
274 if total_files > 0:
275 console.print(
276 f"\n[bold]Total: {total_files} files, {total_size: .2f}MB[/ bold]",
277 )
278 else:
279 console.print("\n[dim]No log files found[/ dim]")
282log_manager = LogManager()
285def get_log_manager() -> LogManager:
286 return log_manager