Avoid locking in the logging queue handler (#35700)

* Avoid locking in the logging queue handler

We do not need a lock here as the underlying queue is already
thread safe.

* Add coverage for logging handle
This commit is contained in:
J. Nick Koston 2020-05-17 07:39:27 -05:00 committed by GitHub
parent 65e509ed8f
commit 1297a09344
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 0 deletions

View File

@ -39,6 +39,24 @@ class HomeAssistantQueueHandler(logging.handlers.QueueHandler):
except Exception: # pylint: disable=broad-except
self.handleError(record)
def handle(self, record: logging.LogRecord) -> Any:
"""
Conditionally emit the specified logging record.
Depending on which filters have been added to the handler, push the new
records onto the backing Queue.
The default python logger Handler acquires a lock
in the parent class which we do not need as
SimpleQueue is already thread safe.
See https://bugs.python.org/issue24645
"""
return_value = self.filter(record)
if return_value:
self.emit(record)
return return_value
@callback
def async_activate_log_queue_handler(hass: HomeAssistant) -> None:

View File

@ -38,6 +38,17 @@ async def test_logging_with_queue_handler():
):
handler.emit(log_record)
with patch.object(handler, "emit") as emit_mock:
handler.handle(log_record)
emit_mock.assert_called_once()
with patch.object(handler, "filter") as filter_mock, patch.object(
handler, "emit"
) as emit_mock:
filter_mock.return_value = False
handler.handle(log_record)
emit_mock.assert_not_called()
with patch.object(handler, "enqueue", side_effect=OSError), patch.object(
handler, "handleError"
) as mock_handle_error: