2019-04-13 15:22:03 +00:00
|
|
|
"""QueueListener that can be configured from logging.dictConfig"""
|
2019-04-13 14:04:48 +00:00
|
|
|
from atexit import register
|
2019-04-13 15:22:03 +00:00
|
|
|
from logging.config import ConvertingList
|
2019-04-13 14:04:48 +00:00
|
|
|
from logging.handlers import QueueHandler, QueueListener
|
|
|
|
from queue import Queue
|
|
|
|
|
|
|
|
|
2019-04-13 15:22:03 +00:00
|
|
|
def _resolve_handlers(_list):
|
|
|
|
"""Evaluates ConvertingList by iterating over it"""
|
|
|
|
if not isinstance(_list, ConvertingList):
|
|
|
|
return _list
|
2019-04-13 14:04:48 +00:00
|
|
|
|
|
|
|
# Indexing the list performs the evaluation.
|
2019-04-13 15:22:03 +00:00
|
|
|
return [_list[i] for i in range(len(_list))]
|
2019-04-13 14:04:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
class QueueListenerHandler(QueueHandler):
|
2019-04-13 15:22:03 +00:00
|
|
|
"""QueueListener that can be configured from logging.dictConfig"""
|
2019-04-13 14:04:48 +00:00
|
|
|
|
2019-04-13 15:22:03 +00:00
|
|
|
def __init__(self, handlers, auto_run=True, queue=Queue(-1)):
|
2019-04-13 14:04:48 +00:00
|
|
|
super().__init__(queue)
|
|
|
|
handlers = _resolve_handlers(handlers)
|
|
|
|
self._listener = QueueListener(
|
|
|
|
self.queue,
|
|
|
|
*handlers,
|
2019-04-13 15:22:03 +00:00
|
|
|
respect_handler_level=True)
|
2019-04-13 14:04:48 +00:00
|
|
|
if auto_run:
|
|
|
|
self.start()
|
|
|
|
register(self.stop)
|
|
|
|
|
|
|
|
def start(self):
|
2019-04-13 15:22:03 +00:00
|
|
|
"""start background thread"""
|
2019-04-13 14:04:48 +00:00
|
|
|
self._listener.start()
|
|
|
|
|
|
|
|
def stop(self):
|
2019-04-13 15:22:03 +00:00
|
|
|
"""stop background thread"""
|
2019-04-13 14:04:48 +00:00
|
|
|
self._listener.stop()
|