Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: filter console logs on the main thread (#1711)

NTFSvolume2b66b542949c
diff --git a/cyberdrop_dl/logs.py b/cyberdrop_dl/logs.py
index 0c071a14a..c21a49886 100644
--- a/cyberdrop_dl/logs.py
+++ b/cyberdrop_dl/logs.py
@@ -4,12 +4,13 @@ import contextlib
import json
import logging
import queue
+import sys
from contextvars import ContextVar
from datetime import datetime
from io import StringIO
from logging.handlers import QueueHandler, QueueListener
from pathlib import Path
-from typing import TYPE_CHECKING, ClassVar, final
+from typing import TYPE_CHECKING, ClassVar, TypeVar, final
from rich._log_render import LogRender
from rich.console import Console, Group
@@ -21,24 +22,23 @@ from typing_extensions import override
from cyberdrop_dl import env
if TYPE_CHECKING:
- from collections.abc import Generator
+ from collections.abc import Callable, Generator, Iterable
+
+ from rich.console import ConsoleRenderable
+
logger = logging.getLogger("cyberdrop_dl")
for noisy_package in ("aiosqlite",):
logging.getLogger(noisy_package).setLevel(logging.ERROR)
-
+_T = TypeVar("_T")
_USER_NAME = Path.home().name
_DEFAULT_CONSOLE_WIDTH = 240
-_MAIN_LOG_LISTENER: ContextVar[QueueListener] = ContextVar("_MAIN_LOGGER_LISTENER")
-MAIN_LOG_FILE: ContextVar[Path] = ContextVar("_MAIN_LOGGER_FILE")
-LOG_TO_CONSOLE: ContextVar[bool] = ContextVar("LOG_TO_CONSOLE", default=True)
-
-
-if TYPE_CHECKING:
- from collections.abc import Callable, Iterable
+_MAIN_LOG_LISTENER: ContextVar[QueueListener] = ContextVar("_MAIN_LOG_LISTENER")
+_CONSOLE_LOG_LISTENER: ContextVar[QueueListener] = ContextVar("_CONSOLE_LOG_LISTENER")
+_LOG_TO_CONSOLE: ContextVar[bool] = ContextVar("LOG_TO_CONSOLE", default=True)
- from rich.console import ConsoleRenderable
+MAIN_LOG_FILE: ContextVar[Path] = ContextVar("MAIN_LOG_FILE")
class RedactedConsole(Console):
@@ -171,26 +171,36 @@ class BareQueueHandler(QueueHandler):
@contextlib.contextmanager
-def _threaded_logger(log_handler: logging.Handler, *, is_main_log: bool = False) -> Generator[None]:
+def _threaded_logger(
+ log_handler: logging.Handler, *, context_var: ContextVar[QueueListener] | None = None
+) -> Generator[BareQueueHandler]:
"""Context-manager to process logs from this handler in another thread"""
q: queue.Queue[logging.LogRecord] = queue.Queue()
q_handler: BareQueueHandler = BareQueueHandler(q)
q_listener: QueueListener = QueueListener(q, log_handler, respect_handler_level=True)
q_listener.start()
- token = _MAIN_LOG_LISTENER.set(q_listener) if is_main_log else None
- logging.getLogger().addHandler(q_handler)
+
+ with _enter_context(context_var, q_listener) if context_var else contextlib.nullcontext():
+ logging.getLogger().addHandler(q_handler)
+ try:
+ yield q_handler
+ finally:
+ logging.getLogger().removeHandler(q_handler)
+ try:
+ q_handler.close()
+ finally:
+ q_listener.stop()
+ for handler in q_listener.handlers[:]:
+ handler.close()
+
+
+def _enter_context(context_var: ContextVar[_T], value: _T) -> Generator[None]:
+ token = context_var.set(value)
try:
yield
finally:
- logging.getLogger().removeHandler(q_handler)
- try:
- q_handler.close()
- finally:
- q_listener.stop()
- for handler in q_listener.handlers[:]:
- handler.close()
- if token is not None:
- _MAIN_LOG_LISTENER.reset(token)
+ context_var.reset(token)
@final
@@ -274,13 +284,14 @@ def log_spacer(char: str = "-") -> None:
def setup_console_logging(level: int = logging.INFO) -> Generator[None]:
handler = LogHandler(level, show_time=False)
logging.getLogger().setLevel(logging.DEBUG)
- handler.addFilter(lambda _: LOG_TO_CONSOLE.get())
try:
- with _threaded_logger(handler):
+ with _threaded_logger(handler, context_var=_CONSOLE_LOG_LISTENER) as q_handler:
+ q_handler.addFilter(lambda _: _LOG_TO_CONSOLE.get())
yield
finally:
- # Re add it as a normal handler to make sure uncatched exceptions show up
- logging.getLogger().addHandler(handler)
+ if "pytest" not in sys.modules:
+ # Re add it as a normal handler to make sure uncatched exceptions show up
+ logging.getLogger().addHandler(handler)
@contextlib.contextmanager
@@ -289,21 +300,18 @@ def setup_file_logging(file: Path, /, level: int = logging.DEBUG) -> Generator[N
with (
_setup_debug_logger() as debug_log_file,
file.open("w", encoding="utf8") as fp,
+ _enter_context(MAIN_LOG_FILE, file),
_threaded_logger(
- is_main_log=True,
log_handler=LogHandler(
level,
show_time=True,
console=RedactedConsole(file=fp, width=_DEFAULT_CONSOLE_WIDTH * 2),
),
+ context_var=_MAIN_LOG_LISTENER,
),
):
logger.info(f"Debug log file: {debug_log_file}")
- token = MAIN_LOG_FILE.set(file)
- try:
- yield
- finally:
- MAIN_LOG_FILE.reset(token)
+ yield
@contextlib.contextmanager
@@ -370,6 +378,17 @@ def flush_logs() -> None:
listener.start()
+def disable_console_logging():
+ try:
+ listener = _CONSOLE_LOG_LISTENER.get()
+ except LookupError:
+ pass
+ else:
+ listener.stop()
+ listener.start()
+ return _enter_context(_LOG_TO_CONSOLE, value=False)
+
+
@contextlib.contextmanager
def borrow_logger(name: str, level: int = logging.INFO) -> Generator[None]:
"""Context manager to temporarily add our log handlers to a third party logger"""
diff --git a/cyberdrop_dl/progress/__init__.py b/cyberdrop_dl/progress/__init__.py
index 5e81923d7..61763ee2c 100644
--- a/cyberdrop_dl/progress/__init__.py
+++ b/cyberdrop_dl/progress/__init__.py
@@ -12,7 +12,7 @@ from rich.markup import escape
from rich.progress import Progress, Task, TaskID
from rich.text import Text
-from cyberdrop_dl.logs import LOG_TO_CONSOLE
+from cyberdrop_dl.logs import disable_console_logging
if TYPE_CHECKING:
from collections.abc import Callable, Generator, Iterable
@@ -93,13 +93,16 @@ class LiveUI(ABC):
def __rich__(self) -> RenderableType: ...
@contextlib.contextmanager
- def __call__(self, *, transient: bool = True) -> Generator[None]:
- if self.disabled or "pytest" in sys.modules:
- yield None
+ def __call__(self, *, transient: bool = True, force: bool = False) -> Generator[None]:
+ if self.disabled and not force:
+ yield
return
- console_token = LOG_TO_CONSOLE.set(False)
- try:
+ with disable_console_logging():
+ if "pytest" in sys.modules and not force:
+ yield
+ return
+
with Live(
refresh_per_second=REFRESH_RATE.get(),
auto_refresh=True,
@@ -108,5 +111,3 @@ class LiveUI(ABC):
get_renderable=self.__rich__,
):
yield
- finally:
- LOG_TO_CONSOLE.reset(console_token)
diff --git a/tests/test_logger.py b/tests/test_logger.py
index c79ca7fb4..771f6c77b 100644
--- a/tests/test_logger.py
+++ b/tests/test_logger.py
@@ -2,8 +2,10 @@ import logging
from pathlib import Path
import pytest
+from rich import get_console
from cyberdrop_dl import logs
+from cyberdrop_dl.progress import LiveUI
TEXT = "\n".join(f"line {idx}" for idx in range(1, 5))
@@ -62,3 +64,44 @@ class TestBorrowLogger:
assert other.handlers == [orig_handler]
assert other.level == logging.CRITICAL
+
+
+def test_disable_console_logging() -> None:
+
+ logger = logging.getLogger("cyberdrop_dl")
+ console = get_console()
+ console.record = True
+ with console, logs.setup_console_logging():
+ logger.info("This msg SHOULD show up")
+ with logs.disable_console_logging():
+ logger.info("This msg SHOULD NOT show up")
+
+ logger.info("This msg also SHOULD show up")
+
+ text = console.export_text()
+ assert "This msg SHOULD show up" in text
+ assert "This msg SHOULD NOT show up" not in text
+ assert "This msg also SHOULD show up" in text
+
+
+def test_entering_a_live_disables_console_logging() -> None:
+ logger = logging.getLogger("cyberdrop_dl")
+ console = get_console()
+ console.record = True
+
+ class DummyLiveUI(LiveUI):
+ def __rich__(self):
+ return "In Live"
+
+ with console, logs.setup_console_logging():
+ logger.info("This msg SHOULD show up")
+ with DummyLiveUI()(transient=False, force=True):
+ logger.info("This msg SHOULD NOT show up")
+
+ logger.info("This msg also SHOULD show up")
+
+ text = console.export_text()
+ assert "In Live" in text
+ assert "This msg SHOULD show up" in text
+ assert "This msg SHOULD NOT show up" not in text
+ assert "This msg also SHOULD show up" in text