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

1import logging 

2import os 

3import shutil 

4import time 

5from contextlib import suppress 

6from pathlib import Path 

7 

8from rich.console import Console 

9 

10console = Console() 

11 

12 

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() 

18 

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" 

22 

23 return base_dir / self.app_name / "logs" 

24 

25 def _setup_directories(self) -> None: 

26 self._log_dir.mkdir(parents=True, exist_ok=True) 

27 

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) 

31 

32 @property 

33 def log_dir(self) -> Path: 

34 return self._log_dir 

35 

36 @property 

37 def debug_dir(self) -> Path: 

38 return self._log_dir / "debug" 

39 

40 @property 

41 def error_dir(self) -> Path: 

42 return self._log_dir / "error" 

43 

44 @property 

45 def audit_dir(self) -> Path: 

46 return self._log_dir / "audit" 

47 

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" 

54 

55 return self.debug_dir / filename 

56 

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 

61 

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 

71 

72 removed_count = 0 

73 cutoff_time = time.time() - (max_age_days * 24 * 60 * 60) 

74 

75 log_files = sorted( 

76 log_dir.glob(pattern), 

77 key=lambda p: p.stat().st_mtime, 

78 reverse=True, 

79 ) 

80 

81 for i, log_file in enumerate(log_files): 

82 should_remove = False 

83 reason = "" 

84 

85 if i >= max_files: 

86 should_remove = True 

87 reason = f"exceeds max files ({max_files})" 

88 

89 elif log_file.stat().st_mtime < cutoff_time: 

90 should_remove = True 

91 reason = f"older than {max_age_days} days" 

92 

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 ) 

100 

101 return removed_count 

102 

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 = {} 

111 

112 results["debug"] = self.rotate_logs( 

113 self.debug_dir, 

114 "debug-*.log", 

115 debug_max_files, 

116 max_age_days, 

117 ) 

118 

119 results["error"] = self.rotate_logs( 

120 self.error_dir, 

121 "error-*.log", 

122 error_max_files, 

123 max_age_days, 

124 ) 

125 

126 results["audit"] = self.rotate_logs( 

127 self.audit_dir, 

128 "audit-*.log", 

129 audit_max_files, 

130 max_age_days, 

131 ) 

132 

133 return results 

134 

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} 

142 

143 debug_pattern = "crackerjack - debug-*.log" 

144 legacy_files = list(source_dir.glob(debug_pattern)) 

145 

146 results = {"found": len(legacy_files), "moved": 0, "failed": 0} 

147 

148 if not legacy_files: 

149 console.print("[green]✅ No legacy log files found to migrate[/ green]") 

150 return results 

151 

152 console.print( 

153 f"[yellow]📦 Found {len(legacy_files)} legacy debug log files to migrate[/ yellow]", 

154 ) 

155 

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)) 

163 

164 new_filename = f"debug -{timestamp}- migrated.log" 

165 new_path = self.debug_dir / new_filename 

166 

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 ) 

178 

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 ) 

184 

185 return results 

186 

187 def get_log_stats(self) -> dict[str, dict[str, int | str]]: 

188 stats = {} 

189 

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()) 

198 

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 } 

210 

211 return stats 

212 

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 

221 

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 

228 

229 log_file = log_dir / f"{log_type}.log" 

230 

231 handler = RotatingFileHandler( 

232 log_file, 

233 maxBytes=max_bytes, 

234 backupCount=backup_count, 

235 encoding="utf-8", 

236 ) 

237 

238 formatter = logging.Formatter( 

239 "%(asctime)s - %(name)s - %(levelname)s-%(message)s", 

240 ) 

241 handler.setFormatter(formatter) 

242 

243 logger.addHandler(handler) 

244 

245 return handler 

246 

247 def print_log_summary(self) -> None: 

248 stats = self.get_log_stats() 

249 

250 console.print("\n[bold]📊 Log File Summary[/ bold]") 

251 console.print(f"[dim]Location: {self.log_dir}[/ dim]") 

252 

253 total_files = 0 

254 total_size = 0.0 

255 

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 ) 

265 

266 total_files += count 

267 total_size += size 

268 

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") 

273 

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]") 

280 

281 

282log_manager = LogManager() 

283 

284 

285def get_log_manager() -> LogManager: 

286 return log_manager