Skip to content

Commit 3de400e

Browse files
committed
[shared] Fix tqdm.logging_redirect_tqdm not respecting logger verbosity
Being tracked by tqdm/tqdm#1272 upstream.
1 parent 115e6b6 commit 3de400e

File tree

3 files changed

+75
-15
lines changed

3 files changed

+75
-15
lines changed

dvr_scan/__main__.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
from subprocess import CalledProcessError
1919

2020
from scenedetect import VideoOpenFailure
21-
from scenedetect.platform import FakeTqdmLoggingRedirect, logging_redirect_tqdm
2221

2322
from dvr_scan.controller import parse_settings, run_dvr_scan
23+
from dvr_scan.shared import logging_redirect_tqdm
2424

2525
EXIT_SUCCESS: int = 0
2626
EXIT_ERROR: int = 1
@@ -32,14 +32,9 @@ def main():
3232
if settings is None:
3333
sys.exit(EXIT_ERROR)
3434
logger = logging.getLogger("dvr_scan")
35-
# TODO(1.7): The logging redirect does not respect the original log level, which is now set to
36-
# DEBUG mode for rolling log files. https://github.com/tqdm/tqdm/issues/1272
37-
# We might have to just roll our own instead of relying on this one.
38-
redirect = FakeTqdmLoggingRedirect if settings.get("quiet-mode") else logging_redirect_tqdm
39-
# TODO: Use Python __debug__ mode instead of hard-coding as config option.
4035
debug_mode = settings.get("debug")
4136
show_traceback = getattr(logging, settings.get("verbosity").upper()) == logging.DEBUG
42-
with redirect(loggers=[logger]):
37+
with logging_redirect_tqdm(loggers=[logger]):
4338
try:
4439
run_dvr_scan(settings)
4540
except ValueError as ex:

dvr_scan/app/__main__.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,18 @@
1515
from subprocess import CalledProcessError
1616

1717
from scenedetect import VideoOpenFailure
18-
from scenedetect.platform import FakeTqdmLoggingRedirect, logging_redirect_tqdm
1918

2019
import dvr_scan
2120
from dvr_scan import get_license_info
2221
from dvr_scan.app.application import Application
2322
from dvr_scan.config import CHOICE_MAP, USER_CONFIG_FILE_PATH, ConfigLoadFailure, ConfigRegistry
24-
from dvr_scan.shared import ScanSettings, init_logging, logfile_path, setup_logger
23+
from dvr_scan.shared import (
24+
ScanSettings,
25+
init_logging,
26+
logfile_path,
27+
logging_redirect_tqdm,
28+
setup_logger,
29+
)
2530
from dvr_scan.shared.cli import VERSION_STRING, LicenseAction, VersionAction, string_type_check
2631

2732
logger = logging.getLogger("dvr_scan")
@@ -163,15 +168,10 @@ def main():
163168
# failure reason to the user above. We can now exit with an error code.
164169
raise SystemExit(1)
165170

166-
# TODO(1.7): The logging redirect does not respect the original log level, which is now set to
167-
# DEBUG mode for rolling log files. https://github.com/tqdm/tqdm/issues/1272
168-
# We can just remove the use of a context manager here and install our own hooks into the
169-
# loggers instead as a follow-up action.
170-
redirect = FakeTqdmLoggingRedirect if settings.get("quiet-mode") else logging_redirect_tqdm
171171
show_traceback = getattr(logging, settings.get("verbosity").upper()) == logging.DEBUG
172172
# TODO: Use Python __debug__ mode instead of hard-coding as config option.
173173
debug_mode = settings.get("debug")
174-
with redirect(loggers=[logger]):
174+
with logging_redirect_tqdm(loggers=[logger]):
175175
try:
176176
app = Application(
177177
settings=settings, initial_videos=args.input if hasattr(args, "input") else []

dvr_scan/shared/__init__.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,23 @@
1414
import argparse
1515
import logging
1616
import typing as ty
17+
from contextlib import contextmanager
1718
from logging.handlers import RotatingFileHandler
1819
from pathlib import Path
1920

21+
import tqdm
2022
from platformdirs import user_log_path
2123
from scenedetect import FrameTimecode
2224

25+
# TODO: This is a hack and will break eventually, but this is the only way to handle this
26+
# right now unfortunately. logging_redirect_tqdm from the tqdm contrib module doesn't respect
27+
# verbosity unfortunately. This is being tracked by https://github.com/tqdm/tqdm/issues/1272.
28+
from tqdm.contrib.logging import (
29+
_get_first_found_console_logging_handler,
30+
_is_console_logging_handler,
31+
_TqdmLoggingHandler,
32+
)
33+
2334
from dvr_scan.overlays import BoundingBoxOverlay, TextOverlay
2435
from dvr_scan.platform import LOG_FORMAT_ROLLING_LOGS, attach_log_handler
2536
from dvr_scan.platform import init_logger as _init_logger
@@ -186,3 +197,57 @@ def init_scanner(
186197
)
187198

188199
return scanner
200+
201+
202+
@contextmanager
203+
def logging_redirect_tqdm(
204+
loggers: ty.Optional[ty.List[logging.Logger]], instance: ty.Type = tqdm.tqdm
205+
):
206+
"""
207+
Context manager redirecting console logging to `tqdm.write()`, leaving
208+
other logging handlers (e.g. log files) unaffected.
209+
210+
Parameters
211+
----------
212+
loggers : list, optional
213+
Which handlers to redirect (default: [logging.root]).
214+
tqdm_class : optional
215+
216+
Example
217+
-------
218+
```python
219+
import logging
220+
from tqdm import trange
221+
from tqdm.contrib.logging import logging_redirect_tqdm
222+
223+
LOG = logging.getLogger(__name__)
224+
225+
if __name__ == "__main__":
226+
logging.basicConfig(level=logging.INFO)
227+
with logging_redirect_tqdm():
228+
for i in trange(9):
229+
if i == 4:
230+
LOG.info("console logging redirected to `tqdm.write()`")
231+
# logging restored
232+
```
233+
"""
234+
if loggers is None:
235+
loggers = [logging.root]
236+
original_handlers_list = [logger.handlers for logger in loggers]
237+
try:
238+
for logger in loggers:
239+
tqdm_handler = _TqdmLoggingHandler(instance)
240+
orig_handler = _get_first_found_console_logging_handler(logger.handlers)
241+
if orig_handler is not None:
242+
tqdm_handler.setFormatter(orig_handler.formatter)
243+
tqdm_handler.stream = orig_handler.stream
244+
# The following is missing from the original logging_redirect_tqdm.
245+
# This is being tracked by https://github.com/tqdm/tqdm/issues/1272.
246+
tqdm_handler.setLevel(orig_handler.level)
247+
logger.handlers = [
248+
handler for handler in logger.handlers if not _is_console_logging_handler(handler)
249+
] + [tqdm_handler]
250+
yield
251+
finally:
252+
for logger, original_handlers in zip(loggers, original_handlers_list):
253+
logger.handlers = original_handlers

0 commit comments

Comments
 (0)