Context manager for source switching (simplified - no tree tracking). Usage: with log_context("Processing request", logger): logger.info("Step 1") With silent=True, no header is logged: with log_context("", logger, silent=True): logger.info("Som
(
name: str,
logger: Optional[logging.Logger] = None,
source: Optional[str] = None,
silent: bool = False,
)
| 55 | |
| 56 | @contextmanager |
| 57 | def log_context( |
| 58 | name: str, |
| 59 | logger: Optional[logging.Logger] = None, |
| 60 | source: Optional[str] = None, |
| 61 | silent: bool = False, |
| 62 | ) -> Generator[None, None, None]: |
| 63 | """ |
| 64 | Context manager for source switching (simplified - no tree tracking). |
| 65 | |
| 66 | Usage: |
| 67 | with log_context("Processing request", logger): |
| 68 | logger.info("Step 1") |
| 69 | |
| 70 | With silent=True, no header is logged: |
| 71 | with log_context("", logger, silent=True): |
| 72 | logger.info("Some work") |
| 73 | """ |
| 74 | if logger is None: |
| 75 | logger = logging.getLogger() |
| 76 | |
| 77 | # Handle optional source change |
| 78 | source_token = None |
| 79 | if source is not None: |
| 80 | source_token = source_var.set(source) |
| 81 | |
| 82 | # Log the context entry (unless silent) |
| 83 | if not silent and name: |
| 84 | logger.info(name) |
| 85 | |
| 86 | try: |
| 87 | yield |
| 88 | finally: |
| 89 | # Restore previous source |
| 90 | if source_token is not None: |
| 91 | source_var.reset(source_token) |
| 92 | |
| 93 | |
| 94 | @contextmanager |