Coverage for ntnlog/ntn_logging.py: 100%

129 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-10-28 12:27 +0000

1####################################################################### 

2# 

3# My Logging Module 

4# 

5# Provides logging functionality with timestamping and caller info 

6# Supports configurable logging and tracing options 

7# 

8####################################################################### 

9 

10import asyncio 

11import os 

12import sys 

13import traceback 

14import threading 

15from datetime import datetime 

16from inspect import getframeinfo, stack 

17from .ntn_levels import Level, LevelLike 

18 

19from .ntn_config import ( 

20 GLOBAL_LOGGING_ENABLED, 

21 GLOBAL_LOG_TRACING_ENABLED, 

22 GLOBAL_LOG_LEVEL, 

23 GLOBAL_MAX_BYTES, 

24 GLOBAL_BACKUP_COUNT, 

25 GLOBAL_LOG_COLORS, 

26) 

27 

28_ANSI_RESET = "\033[0m" 

29 

30 

31# --------------------------------------------------------------------------- 

32# Frame-filtering constants 

33# --------------------------------------------------------------------------- 

34 

35# Prefixes of filenames/paths to always skip (logger internals, frozen frames) 

36_IGNORED_PREFIXES = ( 

37 "<frozen", 

38 "<string>", 

39) 

40 

41# Basenames of framework/infra files to skip (blocklist fallback mode) 

42_IGNORED_FILES = { 

43 "spawn.py", 

44 "process.py", 

45 "_subprocess.py", 

46 "server.py", 

47 "runners.py", 

48 "config.py", 

49 "importer.py", 

50 "__init__.py", 

51 "cli.py", 

52 "discover.py", 

53 "ntn_logging.py", # skip this file itself 

54 "ntn_utils.py", 

55} 

56 

57# --------------------------------------------------------------------------- 

58# Logger 

59# --------------------------------------------------------------------------- 

60 

61class Logger: 

62 """ 

63 Lightweight file logger with optional call-stack tracing. 

64 

65 Usage 

66 ----- 

67 log = Logger() 

68 log("Something happened") 

69 log.log("Something happened", console_message="Hey!") 

70 

71 Parameters 

72 ---------- 

73 log_dir : str 

74 Directory (relative or absolute) where log files are written. 

75 Defaults to ``./logs``. Paths outside the current working 

76 directory are written as given. The directory is created on the 

77 first write when it does not already exist. 

78 project_dir : str | None 

79 Root of your project source tree. When supplied, only frames whose 

80 absolute path starts with this directory (and are not inside 

81 ``site-packages``) are considered "your code". When ``None`` the 

82 module falls back to the blocklist defined by ``_IGNORED_FILES`` / 

83 ``_IGNORED_PREFIXES``. 

84 name : str | None 

85 Optional label for this logger instance. Appears as a bracket segment 

86 in every log entry. 

87 level : LevelLike | None 

88 Minimum level threshold for console output. Accepts a ``Level`` member 

89 or a case-insensitive string: ``"TRACE"``, ``"DEBUG"``, ``"INFO"``, 

90 ``"WARN"``, ``"ERROR"``, ``"CRITICAL"``. Entries are always written to 

91 the file; only console output is suppressed below this threshold. When 

92 ``None``, ``GLOBAL_LOG_LEVEL`` is used. 

93 colorize : bool 

94 When ``True``, console output is wrapped in ANSI color codes taken 

95 from *colors* (or ``GLOBAL_LOG_COLORS`` when *colors* is ``None``). 

96 File output is never colorized. 

97 colors : dict[int, str] | None 

98 Per-instance color map keyed by ``int(Level)``. Merged on top of 

99 ``GLOBAL_LOG_COLORS`` at construction time; missing entries fall back 

100 to the global value. 

101 

102 Raises 

103 ------ 

104 ValueError 

105 If *log_dir* exists and is not a directory. 

106 

107 Notes 

108 ----- 

109 Log rotation is controlled globally via ``GLOBAL_MAX_BYTES`` and 

110 ``GLOBAL_BACKUP_COUNT`` in ``ntn_config.py``. 

111 """ 

112 

113 DEFAULT_LOG_DIR = "logs" 

114 

115 _LEVEL_ALIASES: dict[str, str] = {"WARN": "WARNING"} 

116 

117 @staticmethod 

118 def _parse_level(value: LevelLike | None) -> Level | None: 

119 if value is None: 

120 return None 

121 if isinstance(value, Level): 

122 return value 

123 name = str(value).upper() 

124 name = Logger._LEVEL_ALIASES.get(name, name) 

125 try: 

126 return Level[name] 

127 except KeyError: 

128 valid = [lvl.name for lvl in Level] 

129 raise ValueError(f"Unknown log level {value!r}. Valid levels: {valid}") 

130 

131 def __init__( 

132 self, 

133 log_dir: str = DEFAULT_LOG_DIR, 

134 project_dir: str | None = None, 

135 name: str | None = None, 

136 level: LevelLike | None = None, 

137 colorize: bool = False, 

138 colors: dict[int, str] | None = None, 

139 ): 

140 # A non-directory at log_dir makes os.makedirs raise FileExistsError 

141 # on the first write. Reject it once, here, instead. 

142 if os.path.lexists(log_dir) and not os.path.isdir(log_dir): 

143 raise ValueError( 

144 f"log_dir {log_dir!r} exists but is not a directory" 

145 ) 

146 

147 self._enable: bool = True 

148 self._enable_log_tracing: bool = False 

149 self._log_dir: str = log_dir 

150 self._project_dir: str | None = ( 

151 os.path.abspath(project_dir) if project_dir is not None else None 

152 ) 

153 self._name: str | None = name 

154 self._level: Level | None = self._parse_level(level) 

155 self._colorize: bool = colorize 

156 self._colors: dict[int, str] = {**GLOBAL_LOG_COLORS, **(colors or {})} 

157 self._lock = threading.Lock() 

158 

159 # ------------------------------------------------------------------ 

160 # Public interface 

161 # ------------------------------------------------------------------ 

162 

163 def __call__( 

164 self, 

165 message: str, 

166 level: LevelLike = Level.INFO, 

167 console_message: str | None = None, 

168 ) -> None: 

169 """ 

170 Write a log entry. Alias for :meth:`log`. 

171 

172 Parameters 

173 ---------- 

174 message : str 

175 Text to write to the log file. 

176 level : LevelLike 

177 Severity of this entry. Always written to file. Suppresses console 

178 output when below the instance threshold. Accepts a ``Level`` enum 

179 member or a case-insensitive string: ``"TRACE"`` (5), 

180 ``"DEBUG"`` (10), ``"INFO"`` (20), ``"WARN"`` (30), 

181 ``"ERROR"`` (40), ``"CRITICAL"`` (50). 

182 console_message : str | None 

183 When ``None`` (default), nothing is printed to stdout. 

184 When ``""`` (empty string), prints the full formatted log entry to stdout. 

185 When any other string, prints that string to stdout instead of *message*. 

186 """ 

187 self.log(message, level=level, console_message=console_message) 

188 

189 def log( 

190 self, 

191 message: str, 

192 level: LevelLike = Level.INFO, 

193 console_message: str | None = None, 

194 ) -> None: 

195 """ 

196 Write a log entry. 

197 

198 Parameters 

199 ---------- 

200 message : str 

201 Text to write to the log file. 

202 level : LevelLike 

203 Severity of this entry. Always written to file. Suppresses console 

204 output when below the instance threshold. Accepts a ``Level`` enum 

205 member or a case-insensitive string: ``"TRACE"`` (5), 

206 ``"DEBUG"`` (10), ``"INFO"`` (20), ``"WARN"`` (30), 

207 ``"ERROR"`` (40), ``"CRITICAL"`` (50). 

208 console_message : str | None 

209 When ``None`` (default), nothing is printed to stdout. 

210 When ``""`` (empty string), prints the full formatted log entry to stdout. 

211 When any other string, prints that string to stdout instead of *message*. 

212 """ 

213 if isinstance(level, str): 

214 level = self._parse_level(level) or Level.INFO 

215 

216 if not GLOBAL_LOGGING_ENABLED or not self._enable: 

217 return 

218 

219 now = datetime.now() 

220 date = now.strftime("%Y-%m-%d") 

221 time_str = now.strftime("%H:%M:%S") 

222 timestamp = f"{date} {time_str}" 

223 

224 name_segment = f"[{self._name}]" if self._name else "" 

225 level_segment = f"[{level.name}]" 

226 logistic_data = f"[{timestamp}]{level_segment}{name_segment}[{self.get_caller_info()}]" 

227 padded_space = "".rjust(len(logistic_data) + 1) 

228 formatted_message = str(message).replace("\n", f"\n{padded_space}") 

229 log_entry = f"{logistic_data} {formatted_message}\n" 

230 

231 self._write_to_file(log_entry, date, time_str) 

232 

233 if console_message is not None: 

234 threshold = self._level if self._level is not None else GLOBAL_LOG_LEVEL 

235 if level >= threshold: 

236 text = log_entry.rstrip("\n") if console_message == "" else console_message 

237 if self._colorize: 

238 color = self._colors.get(int(level), "") 

239 text = f"{color}{text}{_ANSI_RESET}" 

240 print(text) 

241 

242 def enable_logging(self, enable_logging: bool) -> None: 

243 self._enable = enable_logging 

244 

245 def enable_log_tracing(self, enable_log_tracing: bool) -> None: 

246 self._enable_log_tracing = enable_log_tracing 

247 

248 def exception( 

249 self, 

250 message: str, 

251 level: LevelLike = Level.ERROR, 

252 console_message: str | None = None, 

253 ) -> None: 

254 """ 

255 Log the current exception with a traceback appended. 

256 

257 Parameters 

258 ---------- 

259 message : str 

260 Text prepended to the traceback in the log entry. 

261 level : LevelLike 

262 Severity of this entry. Always written to file. Suppresses console 

263 output when below the instance threshold. Accepts a ``Level`` enum 

264 member or a case-insensitive string: ``"TRACE"`` (5), 

265 ``"DEBUG"`` (10), ``"INFO"`` (20), ``"WARN"`` (30), 

266 ``"ERROR"`` (40), ``"CRITICAL"`` (50). 

267 console_message : str | None 

268 When ``None`` (default), nothing is printed to stdout. 

269 When ``""`` (empty string), prints the full formatted log entry to stdout. 

270 When any other string, prints that string to stdout instead of *message*. 

271 """ 

272 if sys.exc_info()[0] is None: 

273 tb_text = "" 

274 else: 

275 tb_text = "\n" + traceback.format_exc().rstrip() 

276 self.log( 

277 f"{message}{tb_text}", 

278 level=level, 

279 console_message=console_message, 

280 ) 

281 

282 async def alog( 

283 self, 

284 message: str, 

285 level: LevelLike = Level.INFO, 

286 console_message: str | None = None, 

287 ) -> None: 

288 """ 

289 Async version of :meth:`log`. 

290 

291 Parameters 

292 ---------- 

293 message : str 

294 Text to write to the log file. 

295 level : LevelLike 

296 Severity of this entry. Always written to file. Suppresses console 

297 output when below the instance threshold. Accepts a ``Level`` enum 

298 member or a case-insensitive string: ``"TRACE"`` (5), 

299 ``"DEBUG"`` (10), ``"INFO"`` (20), ``"WARN"`` (30), 

300 ``"ERROR"`` (40), ``"CRITICAL"`` (50). 

301 console_message : str | None 

302 When ``None`` (default), nothing is printed to stdout. 

303 When ``""`` (empty string), prints the full formatted log entry to stdout. 

304 When any other string, prints that string to stdout instead of *message*. 

305 """ 

306 await asyncio.to_thread( 

307 self.log, message, level, console_message 

308 ) 

309 

310 async def aexception( 

311 self, 

312 message: str, 

313 level: LevelLike = Level.ERROR, 

314 console_message: str | None = None, 

315 ) -> None: 

316 """ 

317 Async version of :meth:`exception`. 

318 

319 Parameters 

320 ---------- 

321 message : str 

322 Text prepended to the traceback in the log entry. 

323 level : LevelLike 

324 Severity of this entry. Always written to file. Suppresses console 

325 output when below the instance threshold. Accepts a ``Level`` enum 

326 member or a case-insensitive string: ``"TRACE"`` (5), 

327 ``"DEBUG"`` (10), ``"INFO"`` (20), ``"WARN"`` (30), 

328 ``"ERROR"`` (40), ``"CRITICAL"`` (50). 

329 console_message : str | None 

330 When ``None`` (default), nothing is printed to stdout. 

331 When ``""`` (empty string), prints the full formatted log entry to stdout. 

332 When any other string, prints that string to stdout instead of *message*. 

333 """ 

334 # Capture traceback now — sys.exc_info() is thread-local and will be 

335 # empty inside the worker thread spawned by asyncio.to_thread(). 

336 if sys.exc_info()[0] is None: 

337 tb_text = "" 

338 else: 

339 tb_text = "\n" + traceback.format_exc().rstrip() 

340 await asyncio.to_thread( 

341 self.log, 

342 f"{message}{tb_text}", 

343 level, 

344 console_message, 

345 ) 

346 

347 # ------------------------------------------------------------------ 

348 # Caller info 

349 # ------------------------------------------------------------------ 

350 

351 def get_caller_info(self) -> str: 

352 tracing_active = GLOBAL_LOG_TRACING_ENABLED and self._enable_log_tracing 

353 frames = self._collect_project_frames() 

354 

355 if not frames: 

356 return "unknown:0" 

357 

358 if not tracing_active: 

359 return frames[0] 

360 

361 return ">".join(frames) 

362 

363 # ------------------------------------------------------------------ 

364 # Private helpers 

365 # ------------------------------------------------------------------ 

366 

367 def _is_project_frame(self, filename: str) -> bool: 

368 """ 

369 Return True when *filename* belongs to project code. 

370 

371 Allowlist mode (project_dir set): 

372 Frame must live inside the project directory and not inside 

373 a ``site-packages`` folder. 

374 

375 Blocklist mode (project_dir is None): 

376 Frame must not match any entry in ``_IGNORED_FILES`` or 

377 ``_IGNORED_PREFIXES``. 

378 """ 

379 # Always skip frozen / string pseudo-files regardless of mode 

380 if any(filename.startswith(prefix) for prefix in _IGNORED_PREFIXES): 

381 return False 

382 

383 if self._project_dir is not None: 

384 abs_filename = os.path.abspath(filename) 

385 return ( 

386 abs_filename.startswith(self._project_dir) 

387 and "site-packages" not in abs_filename 

388 ) 

389 

390 # Blocklist fallback 

391 return os.path.basename(filename) not in _IGNORED_FILES 

392 

393 def _collect_project_frames(self) -> list[str]: 

394 """Walk the call stack and return frame strings for project code only.""" 

395 frames: list[str] = [] 

396 for frame_record in stack(): 

397 try: 

398 info = getframeinfo(frame_record[0]) 

399 if self._is_project_frame(info.filename): 

400 frames.append(f"{os.path.basename(info.filename)}:{info.lineno}") 

401 except (IndexError, TypeError): 

402 # IndexError: stack shorter than expected 

403 # TypeError: frame_record is not subscriptable (e.g. test mocks using None) 

404 continue 

405 return frames 

406 

407 def _write_to_file(self, log_entry: str, date: str, time_str: str) -> None: 

408 """Create the log directory if needed, then append *log_entry*. 

409 

410 *log_dir* is a user-chosen location. It may be relative or absolute, 

411 including a path outside the current working directory, and is not 

412 passed through the working-directory check used for other file ops. 

413 """ 

414 os.makedirs(self._log_dir, exist_ok=True) 

415 file_name = os.path.join(self._log_dir, f"{date}_logging.txt") 

416 

417 max_bytes = GLOBAL_MAX_BYTES 

418 backup_count = GLOBAL_BACKUP_COUNT 

419 

420 with self._lock: 

421 if os.path.exists(file_name) and os.path.getsize(file_name) >= max_bytes: 

422 if backup_count == 0: 

423 os.remove(file_name) 

424 else: 

425 oldest = f"{file_name}.{backup_count}" 

426 if os.path.exists(oldest): 

427 os.remove(oldest) 

428 for i in range(backup_count - 1, 0, -1): 

429 src = f"{file_name}.{i}" 

430 dst = f"{file_name}.{i + 1}" 

431 if os.path.exists(src): 

432 os.rename(src, dst) 

433 os.rename(file_name, f"{file_name}.1") 

434 

435 with open(file_name, "a") as log_file: 

436 # Write a header only on the very first entry (empty file) 

437 if log_file.tell() == 0: 

438 log_file.write(f"Log file created on {date} at {time_str}\n") 

439 log_file.write(log_entry)