diff --git a/beeref/config.py b/beeref/config.py index 5b28a1f..36ba074 100644 --- a/beeref/config.py +++ b/beeref/config.py @@ -25,9 +25,6 @@ from PyQt6 import QtCore from beeref import constants -logger = logging.getLogger(__name__) - - parser = argparse.ArgumentParser( description=f'{constants.APPNAME_FULL} {constants.VERSION}') parser.add_argument( @@ -185,3 +182,25 @@ logging_conf = { logging.config.dictConfig(logging_conf) + + +# Redirect Qt logging to Python logger: +qtlogger = logging.getLogger('Qt') + + +def qt_message_handler(mode, context, message): + logfuncs = { + QtCore.QtMsgType.QtDebugMsg: qtlogger.debug, + QtCore.QtMsgType.QtInfoMsg: qtlogger.info, + QtCore.QtMsgType.QtWarningMsg: qtlogger.warning, + QtCore.QtMsgType.QtCriticalMsg: qtlogger.critical, + QtCore.QtMsgType.QtFatalMsg: qtlogger.fatal, + } + if context and (context.file or context.line or context.function): + message = (f'{message}: File {context.file}, line {context.line}, ' + f'in {context.function}') + + logfuncs[mode](message) + + +QtCore.qInstallMessageHandler(qt_message_handler) diff --git a/tests/test_config.py b/tests/test_config.py index 7536df9..973756d 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,10 +1,13 @@ import os.path import tempfile +from types import SimpleNamespace from unittest.mock import patch import pytest -from beeref.config import CommandlineArgs +from PyQt6 import QtCore + +from beeref.config import CommandlineArgs, qt_message_handler def test_command_line_args_singleton(): @@ -71,3 +74,16 @@ def test_settings_recent_files_update_respects_max_num(settings): assert len(recent) == 10 assert recent[0] == os.path.abspath('14.bee') assert recent[-1] == os.path.abspath('5.bee') + + +@patch('beeref.config.qtlogger.info') +def test_qt_message_handler_without(log_mock, qapp): + qt_message_handler(QtCore.QtMsgType.QtInfoMsg, None, 'foo') + log_mock.assert_called_once_with('foo') + + +@patch('beeref.config.qtlogger.warning') +def test_qt_message_handler_with_context(log_mock, qapp): + ctx = SimpleNamespace(file='bla.txt', line='1', function='myfunc') + qt_message_handler(QtCore.QtMsgType.QtWarningMsg, ctx, 'foo') + log_mock.assert_called_once_with('foo: File bla.txt, line 1, in myfunc')