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
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
1"""
2Structured logging with context.
4Provides a configured logger with support for structured output,
5context propagation, and proper formatting.
6"""
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
18from taipanstack.utils.context import get_correlation_id
20try:
21 import structlog
23 HAS_STRUCTLOG = True
24except ImportError:
25 HAS_STRUCTLOG = False
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)
35SENSITIVE_KEY_PATTERNS: tuple[str, ...] = (
36 "password",
37 "secret",
38 "token",
39 "authorization",
40 "api_key",
41)
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)
50REDACTED_VALUE = "***REDACTED***"
51MAX_REDACT_DEPTH = 100
52MAX_DEPTH_VALUE = "***MAX_DEPTH_REACHED***"
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.
59 Args:
60 key: The key to check.
61 regex: The regex pattern to use for matching.
63 Returns:
64 True if the key is a string and sensitive, False otherwise.
66 """
67 if regex is None:
68 return False
69 if not isinstance(key, str):
70 return False
71 return bool(regex.search(key))
74KT = TypeVar("KT")
75VT = TypeVar("VT")
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 }
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]
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)
109def _is_unhashable(item: object) -> bool:
110 try:
111 hash(item)
112 return False
113 except TypeError:
114 return True
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)
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
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 )
146 return _redact_iterable(obj, seen, depth + 1)
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
158def _redact(obj: object, seen: set[int] | None = None, depth: int = 0) -> object:
159 """Redact sensitive data recursively with circular reference protection.
161 Args:
162 obj: The object to redact.
163 seen: Set of IDs of already processed containers.
164 depth: The current recursion depth.
166 Returns:
167 A new object with sensitive data redacted.
169 """
170 should_return, val = _check_redact_early_returns(obj, depth)
171 if should_return:
172 return val
174 seen_set = set() if seen is None else seen
176 # Detect circular references
177 if id(obj) in seen_set:
178 return REDACTED_VALUE
180 return _redact_collection(obj, seen_set, depth)
183def _redact_dict(d: MutableMapping[str, object]) -> None:
184 """Redact sensitive keys in a dictionary in-place (top-level only).
186 Note: Nested structures are replaced with redacted copies to prevent
187 shared state mutation.
189 Args:
190 d: The dictionary to redact.
192 """
193 if _SENSITIVE_KEY_REGEX is None:
194 return
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)
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.
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.
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.
219 Returns:
220 The event dictionary with sensitive values masked.
222 """
223 _redact_dict(event_dict)
224 return event_dict
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.
234 Args:
235 _logger: The wrapped logger object.
236 _method: The name of the log method called.
237 event_dict: The structured event dictionary.
239 Returns:
240 The event dictionary with correlation_id injected if sets.
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
249class StackLogger:
250 """Enhanced logger with context support.
252 Provides a wrapper around standard logging with additional features
253 like context propagation and structured output support.
255 Attributes:
256 name: Logger name.
257 level: Current log level.
259 """
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.
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.
275 """
276 self.name = name
277 self.level = level
278 self._context: dict[str, object] = {}
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
288 def bind(self, **context: object) -> "StackLogger":
289 """Add context to logger.
291 Args:
292 **context: Key-value pairs to add to context.
294 Returns:
295 Self for chaining.
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
303 def unbind(self, *keys: str) -> "StackLogger":
304 """Remove context keys.
306 Args:
307 *keys: Keys to remove from context.
309 Returns:
310 Self for chaining.
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
319 def _format_message(self, message: str, **kwargs: object) -> str:
320 """Format message with context.
322 Args:
323 message: The log message.
324 **kwargs: Additional context for this message.
326 Returns:
327 Formatted message string.
329 """
330 if not kwargs and not self._context:
331 return message
333 context = {**self._context, **kwargs}
334 _redact_dict(context)
336 context_str = " ".join(f"{k}={v}" for k, v in context.items())
337 return f"{message} | {context_str}"
339 def debug(self, message: str, **kwargs: object) -> None:
340 """Log a debug message.
342 Args:
343 message: The message to log.
344 **kwargs: Additional context.
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]
352 def info(self, message: str, **kwargs: object) -> None:
353 """Log an info message.
355 Args:
356 message: The message to log.
357 **kwargs: Additional context.
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]
365 def warning(self, message: str, **kwargs: object) -> None:
366 """Log a warning message.
368 Args:
369 message: The message to log.
370 **kwargs: Additional context.
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]
378 def error(self, message: str, **kwargs: object) -> None:
379 """Log an error message.
381 Args:
382 message: The message to log.
383 **kwargs: Additional context.
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]
391 def critical(self, message: str, **kwargs: object) -> None:
392 """Log a critical message.
394 Args:
395 message: The message to log.
396 **kwargs: Additional context.
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]
404 def exception(self, message: str, **kwargs: object) -> None:
405 """Log an exception with traceback.
407 Args:
408 message: The message to log.
409 **kwargs: Additional context.
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]
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]
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 )
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
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.
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.
469 """
470 # Configure structlog if available and requested
471 if use_structured and HAS_STRUCTLOG:
472 _configure_structlog()
473 return
475 log_format = _get_log_format(format_type)
477 handlers: list[logging.Handler] = [logging.StreamHandler(sys.stdout)]
479 if log_file:
480 handlers.append(logging.FileHandler(log_file, encoding="utf-8"))
482 logging.basicConfig(
483 level=getattr(logging, level.upper()), # type: ignore[misc]
484 format=log_format,
485 handlers=handlers,
486 force=True,
487 )
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.
498 Args:
499 name: Logger name.
500 level: Log level.
501 use_structured: Use structlog if available.
503 Returns:
504 Configured StackLogger instance.
506 Example:
507 >>> logger = get_logger("my_module")
508 >>> logger.bind(request_id="123").info("Processing request")
510 """
511 return StackLogger(name, level, use_structured=use_structured)
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.
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.
529 Yields:
530 The logger instance.
532 Example:
533 >>> with log_operation("setup") as logger:
534 ... logger.info("Setting up environment")
536 """
538 @contextmanager
539 def _log_context() -> Iterator[StackLogger]:
540 nonlocal logger
541 if logger is None:
542 logger = get_logger()
544 start_time = datetime.now(UTC)
545 logger.bind(operation=operation)
547 log_method = getattr(logger, level.lower()) # type: ignore[misc]
548 log_method(f"Starting: {operation}")
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")
565 return _log_context()