Coverage for src/taipanstack/utils/logging.py: 100%

188 statements  

« prev     ^ index     » next       coverage.py v7.15.1, created at 2026-11-23 17:43 +0000

1""" 

2Structured logging with context. 

3 

4Provides a configured logger with support for structured output, 

5context propagation, and proper formatting. 

6""" 

7 

8import logging 

9import logging as _std_logging 

10import re 

11import sys 

12from collections.abc import Iterator, MutableMapping 

13from contextlib import AbstractContextManager, contextmanager 

14from datetime import UTC, datetime 

15from functools import lru_cache 

16from typing import Literal, TypeVar, cast 

17 

18from taipanstack.utils.context import get_correlation_id 

19 

20try: 

21 import structlog 

22 

23 HAS_STRUCTLOG = True 

24except ImportError: 

25 HAS_STRUCTLOG = False 

26 

27 

28# Default log format 

29DEFAULT_FORMAT = "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s" 

30JSON_FORMAT = ( 

31 '{"timestamp": "%(asctime)s", "level": "%(levelname)s", ' 

32 '"logger": "%(name)s", "message": "%(message)s"}' 

33) 

34 

35SENSITIVE_KEY_PATTERNS: tuple[str, ...] = ( 

36 "password", 

37 "secret", 

38 "token", 

39 "authorization", 

40 "api_key", 

41) 

42 

43# Pre-compile the regex for O(1) checks per key instead of O(N*M) 

44_SENSITIVE_KEY_REGEX = ( 

45 re.compile("|".join(map(re.escape, SENSITIVE_KEY_PATTERNS)), re.IGNORECASE) 

46 if SENSITIVE_KEY_PATTERNS 

47 else None 

48) 

49 

50REDACTED_VALUE = "***REDACTED***" 

51MAX_REDACT_DEPTH = 100 

52MAX_DEPTH_VALUE = "***MAX_DEPTH_REACHED***" 

53 

54 

55@lru_cache(maxsize=1024) # type: ignore[misc] 

56def _is_sensitive(key: object, regex: re.Pattern[str] | None) -> bool: 

57 """Check if a key is sensitive using cached regex matching. 

58 

59 Args: 

60 key: The key to check. 

61 regex: The regex pattern to use for matching. 

62 

63 Returns: 

64 True if the key is a string and sensitive, False otherwise. 

65 

66 """ 

67 if regex is None: 

68 return False 

69 if not isinstance(key, str): 

70 return False 

71 return bool(regex.search(key)) 

72 

73 

74KT = TypeVar("KT") 

75VT = TypeVar("VT") 

76 

77 

78def _redact_mapping( 

79 obj: MutableMapping[KT, VT], 

80 seen: set[int], 

81 depth: int = 0, 

82) -> dict[KT, object]: 

83 """Redact a mapping object.""" 

84 seen.add(id(obj)) 

85 return { 

86 k: ( 

87 REDACTED_VALUE 

88 if _is_sensitive(k, _SENSITIVE_KEY_REGEX) 

89 else _redact(v, seen, depth + 1) 

90 ) 

91 for k, v in obj.items() 

92 } 

93 

94 

95def _redact_list(obj: list[VT], seen: set[int], depth: int = 0) -> list[object]: 

96 """Redact a list object.""" 

97 seen.add(id(obj)) 

98 return [_redact(item, seen, depth + 1) for item in obj] 

99 

100 

101def _redact_tuple( 

102 obj: tuple[VT, ...], seen: set[int], depth: int = 0 

103) -> tuple[object, ...]: 

104 """Redact a tuple object.""" 

105 seen.add(id(obj)) 

106 return tuple(_redact(item, seen, depth + 1) for item in obj) 

107 

108 

109def _is_unhashable(item: object) -> bool: 

110 try: 

111 hash(item) 

112 return False 

113 except TypeError: 

114 return True 

115 

116 

117def _redact_set( 

118 obj: set[VT], seen: set[int], depth: int = 0 

119) -> set[object] | list[object]: 

120 """Redact a set object.""" 

121 seen.add(id(obj)) 

122 redacted_items = [_redact(item, seen, depth + 1) for item in obj] 

123 if any(_is_unhashable(item) for item in redacted_items): 

124 return redacted_items 

125 return set(redacted_items) 

126 

127 

128def _redact_iterable(obj: object, seen: set[int], depth: int = 0) -> object: 

129 """Dispatch redaction based on iterable type.""" 

130 if isinstance(obj, list): 

131 return _redact_list(obj, seen, depth) 

132 if isinstance(obj, tuple): 

133 return _redact_tuple(obj, seen, depth) 

134 if isinstance(obj, set): 

135 return _redact_set(obj, seen, depth) 

136 return obj 

137 

138 

139def _redact_collection(obj: object, seen: set[int], depth: int = 0) -> object: 

140 """Dispatch redaction based on collection type.""" 

141 if isinstance(obj, (dict, MutableMapping)): 

142 return _redact_mapping( 

143 cast(MutableMapping[object, object], obj), seen, depth + 1 

144 ) 

145 

146 return _redact_iterable(obj, seen, depth + 1) 

147 

148 

149def _check_redact_early_returns(obj: object, depth: int) -> tuple[bool, object]: 

150 """Check early return conditions for _redact.""" 

151 if depth > MAX_REDACT_DEPTH: 

152 return True, MAX_DEPTH_VALUE 

153 if _SENSITIVE_KEY_REGEX is None: 

154 return True, obj 

155 return False, obj 

156 

157 

158def _redact(obj: object, seen: set[int] | None = None, depth: int = 0) -> object: 

159 """Redact sensitive data recursively with circular reference protection. 

160 

161 Args: 

162 obj: The object to redact. 

163 seen: Set of IDs of already processed containers. 

164 depth: The current recursion depth. 

165 

166 Returns: 

167 A new object with sensitive data redacted. 

168 

169 """ 

170 should_return, val = _check_redact_early_returns(obj, depth) 

171 if should_return: 

172 return val 

173 

174 seen_set = set() if seen is None else seen 

175 

176 # Detect circular references 

177 if id(obj) in seen_set: 

178 return REDACTED_VALUE 

179 

180 return _redact_collection(obj, seen_set, depth) 

181 

182 

183def _redact_dict(d: MutableMapping[str, object]) -> None: 

184 """Redact sensitive keys in a dictionary in-place (top-level only). 

185 

186 Note: Nested structures are replaced with redacted copies to prevent 

187 shared state mutation. 

188 

189 Args: 

190 d: The dictionary to redact. 

191 

192 """ 

193 if _SENSITIVE_KEY_REGEX is None: 

194 return 

195 

196 for key, value in list(d.items()): 

197 if _is_sensitive(key, _SENSITIVE_KEY_REGEX): 

198 d[key] = REDACTED_VALUE 

199 else: 

200 d[key] = _redact(value) 

201 

202 

203def mask_sensitive_data_processor( 

204 _logger: object, 

205 _method: str, 

206 event_dict: MutableMapping[str, object], 

207) -> MutableMapping[str, object]: 

208 """Mask sensitive data in structlog event dictionaries. 

209 

210 Intercept the *event_dict* produced by structlog and replace the 

211 value of any key whose name contains a sensitive substring with 

212 ``"***REDACTED***"``. Matching is case-insensitive. 

213 

214 Args: 

215 _logger: The wrapped logger object (unused, required by structlog). 

216 _method: The name of the log method called (unused, required by structlog). 

217 event_dict: The structured event dictionary. 

218 

219 Returns: 

220 The event dictionary with sensitive values masked. 

221 

222 """ 

223 _redact_dict(event_dict) 

224 return event_dict 

225 

226 

227def correlation_id_processor( 

228 _logger: object, 

229 _method: str, 

230 event_dict: MutableMapping[str, object], 

231) -> MutableMapping[str, object]: 

232 """Structlog processor to inject correlation ID into events. 

233 

234 Args: 

235 _logger: The wrapped logger object. 

236 _method: The name of the log method called. 

237 event_dict: The structured event dictionary. 

238 

239 Returns: 

240 The event dictionary with correlation_id injected if sets. 

241 

242 """ 

243 correlation_id = get_correlation_id() 

244 if correlation_id is not None: 

245 event_dict["correlation_id"] = correlation_id 

246 return event_dict 

247 

248 

249class StackLogger: 

250 """Enhanced logger with context support. 

251 

252 Provides a wrapper around standard logging with additional features 

253 like context propagation and structured output support. 

254 

255 Attributes: 

256 name: Logger name. 

257 level: Current log level. 

258 

259 """ 

260 

261 def __init__( 

262 self, 

263 name: str = "taipanstack", 

264 level: str = "INFO", 

265 *, 

266 use_structured: bool = False, 

267 ) -> None: 

268 """Initialize the logger. 

269 

270 Args: 

271 name: Logger name. 

272 level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL). 

273 use_structured: Use structured logging if structlog is available. 

274 

275 """ 

276 self.name = name 

277 self.level = level 

278 self._context: dict[str, object] = {} 

279 

280 if use_structured and HAS_STRUCTLOG: 

281 self._logger = structlog.get_logger(name) # type: ignore[misc] 

282 self._structured = True 

283 else: 

284 self._logger = logging.getLogger(name) 

285 self._logger.setLevel(getattr(logging, level.upper())) # type: ignore[misc] 

286 self._structured = False 

287 

288 def bind(self, **context: object) -> "StackLogger": 

289 """Add context to logger. 

290 

291 Args: 

292 **context: Key-value pairs to add to context. 

293 

294 Returns: 

295 Self for chaining. 

296 

297 """ 

298 self._context.update(context) 

299 if self._structured and HAS_STRUCTLOG: 

300 self._logger = self._logger.bind(**context) # type: ignore[misc] 

301 return self 

302 

303 def unbind(self, *keys: str) -> "StackLogger": 

304 """Remove context keys. 

305 

306 Args: 

307 *keys: Keys to remove from context. 

308 

309 Returns: 

310 Self for chaining. 

311 

312 """ 

313 for key in keys: 

314 self._context.pop(key, None) 

315 if self._structured and HAS_STRUCTLOG: 

316 self._logger = self._logger.unbind(*keys) # type: ignore[misc] 

317 return self 

318 

319 def _format_message(self, message: str, **kwargs: object) -> str: 

320 """Format message with context. 

321 

322 Args: 

323 message: The log message. 

324 **kwargs: Additional context for this message. 

325 

326 Returns: 

327 Formatted message string. 

328 

329 """ 

330 if not kwargs and not self._context: 

331 return message 

332 

333 context = {**self._context, **kwargs} 

334 _redact_dict(context) 

335 

336 context_str = " ".join(f"{k}={v}" for k, v in context.items()) 

337 return f"{message} | {context_str}" 

338 

339 def debug(self, message: str, **kwargs: object) -> None: 

340 """Log a debug message. 

341 

342 Args: 

343 message: The message to log. 

344 **kwargs: Additional context. 

345 

346 """ 

347 if self._structured: 

348 self._logger.debug(message, **kwargs) # type: ignore[misc] 

349 else: 

350 self._logger.debug(self._format_message(message, **kwargs)) # type: ignore[misc] 

351 

352 def info(self, message: str, **kwargs: object) -> None: 

353 """Log an info message. 

354 

355 Args: 

356 message: The message to log. 

357 **kwargs: Additional context. 

358 

359 """ 

360 if self._structured: 

361 self._logger.info(message, **kwargs) # type: ignore[misc] 

362 else: 

363 self._logger.info(self._format_message(message, **kwargs)) # type: ignore[misc] 

364 

365 def warning(self, message: str, **kwargs: object) -> None: 

366 """Log a warning message. 

367 

368 Args: 

369 message: The message to log. 

370 **kwargs: Additional context. 

371 

372 """ 

373 if self._structured: 

374 self._logger.warning(message, **kwargs) # type: ignore[misc] 

375 else: 

376 self._logger.warning(self._format_message(message, **kwargs)) # type: ignore[misc] 

377 

378 def error(self, message: str, **kwargs: object) -> None: 

379 """Log an error message. 

380 

381 Args: 

382 message: The message to log. 

383 **kwargs: Additional context. 

384 

385 """ 

386 if self._structured: 

387 self._logger.error(message, **kwargs) # type: ignore[misc] 

388 else: 

389 self._logger.error(self._format_message(message, **kwargs)) # type: ignore[misc] 

390 

391 def critical(self, message: str, **kwargs: object) -> None: 

392 """Log a critical message. 

393 

394 Args: 

395 message: The message to log. 

396 **kwargs: Additional context. 

397 

398 """ 

399 if self._structured: 

400 self._logger.critical(message, **kwargs) # type: ignore[misc] 

401 else: 

402 self._logger.critical(self._format_message(message, **kwargs)) # type: ignore[misc] 

403 

404 def exception(self, message: str, **kwargs: object) -> None: 

405 """Log an exception with traceback. 

406 

407 Args: 

408 message: The message to log. 

409 **kwargs: Additional context. 

410 

411 """ 

412 if self._structured: 

413 self._logger.exception(message, **kwargs) # type: ignore[misc] 

414 else: 

415 self._logger.exception(self._format_message(message, **kwargs)) # type: ignore[misc] 

416 

417 

418def _configure_structlog(*, level: int | str | None = None) -> None: 

419 """Configure structlog with default processors and settings.""" 

420 if level is not None: 

421 if isinstance(level, str): 

422 level = getattr(_std_logging, level.upper(), _std_logging.INFO) 

423 _std_logging.basicConfig(level=level) # type: ignore[misc] 

424 

425 structlog.configure( 

426 processors=[ 

427 structlog.stdlib.filter_by_level, 

428 structlog.stdlib.add_logger_name, 

429 structlog.stdlib.add_log_level, # type: ignore[misc] 

430 structlog.processors.TimeStamper(fmt="iso"), 

431 correlation_id_processor, 

432 mask_sensitive_data_processor, 

433 structlog.processors.StackInfoRenderer(), 

434 structlog.processors.format_exc_info, 

435 structlog.processors.UnicodeDecoder(), 

436 structlog.processors.JSONRenderer(), 

437 ], 

438 wrapper_class=structlog.stdlib.BoundLogger, 

439 context_class=dict, 

440 logger_factory=structlog.stdlib.LoggerFactory(), 

441 ) 

442 

443 

444def _get_log_format(format_type: str) -> str: 

445 """Get the appropriate log format string.""" 

446 if format_type == "simple": 

447 return "%(levelname)s: %(message)s" 

448 elif format_type == "json": 

449 return JSON_FORMAT 

450 else: 

451 return DEFAULT_FORMAT 

452 

453 

454def setup_logging( 

455 level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO", 

456 *, 

457 format_type: Literal["simple", "detailed", "json"] = "detailed", 

458 log_file: str | None = None, 

459 use_structured: bool = False, 

460) -> None: 

461 """Configure the root logger. 

462 

463 Args: 

464 level: Log level to set. 

465 format_type: Output format type. 

466 log_file: Optional file to log to. 

467 use_structured: Use structlog if available. 

468 

469 """ 

470 # Configure structlog if available and requested 

471 if use_structured and HAS_STRUCTLOG: 

472 _configure_structlog() 

473 return 

474 

475 log_format = _get_log_format(format_type) 

476 

477 handlers: list[logging.Handler] = [logging.StreamHandler(sys.stdout)] 

478 

479 if log_file: 

480 handlers.append(logging.FileHandler(log_file, encoding="utf-8")) 

481 

482 logging.basicConfig( 

483 level=getattr(logging, level.upper()), # type: ignore[misc] 

484 format=log_format, 

485 handlers=handlers, 

486 force=True, 

487 ) 

488 

489 

490def get_logger( 

491 name: str = "taipanstack", 

492 *, 

493 level: str = "INFO", 

494 use_structured: bool = False, 

495) -> StackLogger: 

496 """Get a configured logger instance. 

497 

498 Args: 

499 name: Logger name. 

500 level: Log level. 

501 use_structured: Use structlog if available. 

502 

503 Returns: 

504 Configured StackLogger instance. 

505 

506 Example: 

507 >>> logger = get_logger("my_module") 

508 >>> logger.bind(request_id="123").info("Processing request") 

509 

510 """ 

511 return StackLogger(name, level, use_structured=use_structured) 

512 

513 

514def log_operation( 

515 operation: str, 

516 *, 

517 logger: StackLogger | None = None, 

518 level: str = "INFO", 

519 expected_exceptions: tuple[type[Exception], ...] | type[Exception] = Exception, 

520) -> AbstractContextManager[StackLogger]: 

521 """Context manager for logging operations. 

522 

523 Args: 

524 operation: Name of the operation. 

525 logger: Logger to use (creates one if not provided). 

526 level: Log level for messages. 

527 expected_exceptions: Exceptions to catch and log as failures. 

528 

529 Yields: 

530 The logger instance. 

531 

532 Example: 

533 >>> with log_operation("setup") as logger: 

534 ... logger.info("Setting up environment") 

535 

536 """ 

537 

538 @contextmanager 

539 def _log_context() -> Iterator[StackLogger]: 

540 nonlocal logger 

541 if logger is None: 

542 logger = get_logger() 

543 

544 start_time = datetime.now(UTC) 

545 logger.bind(operation=operation) 

546 

547 log_method = getattr(logger, level.lower()) # type: ignore[misc] 

548 log_method(f"Starting: {operation}") 

549 

550 try: 

551 yield logger 

552 duration = (datetime.now(UTC) - start_time).total_seconds() 

553 log_method(f"Completed: {operation}", duration_seconds=duration) 

554 except expected_exceptions as e: 

555 duration = (datetime.now(UTC) - start_time).total_seconds() 

556 logger.exception( 

557 f"Failed: {operation}", 

558 duration_seconds=duration, 

559 error=str(e), 

560 ) 

561 raise 

562 finally: 

563 logger.unbind("operation") 

564 

565 return _log_context()