Gracefully exit with async logger (#4965)

* Gracefully exit with async logger

* Lint
pull/4969/head
Paulus Schoutsen 2016-12-18 00:14:59 -08:00 committed by GitHub
parent a76684f203
commit 01e6bd2c92
2 changed files with 27 additions and 3 deletions

View File

@ -298,9 +298,8 @@ class HomeAssistant(object):
# cleanup async layer from python logging
if self.data.get(DATA_ASYNCHANDLER):
handler = self.data.pop(DATA_ASYNCHANDLER)
logger = logging.getLogger('')
handler.close()
logger.removeHandler(handler)
logging.getLogger('').removeHandler(handler)
yield from handler.async_close(blocking=True)
self.loop.stop()

View File

@ -49,6 +49,23 @@ class AsyncHandler(object):
"""Wrap close to handler."""
self.emit(None)
@asyncio.coroutine
def async_close(self, blocking=False):
"""Close the handler.
When blocking=True, will wait till closed.
"""
self.close()
if blocking:
# Python 3.4.4+
# pylint: disable=no-member
if hasattr(self._queue, 'join'):
yield from self._queue.join()
else:
while not self._queue.empty():
yield from asyncio.sleep(0, loop=self.loop)
def emit(self, record):
"""Process a record."""
ident = self.loop.__dict__.get("_thread_ident")
@ -66,15 +83,23 @@ class AsyncHandler(object):
def _process(self):
"""Process log in a thread."""
support_join = hasattr(self._queue, 'task_done')
while True:
record = run_coroutine_threadsafe(
self._queue.get(), self.loop).result()
# pylint: disable=no-member
if record is None:
self.handler.close()
if support_join:
self.loop.call_soon_threadsafe(self._queue.task_done)
return
self.handler.emit(record)
if support_join:
self.loop.call_soon_threadsafe(self._queue.task_done)
def createLock(self):
"""Ignore lock stuff."""