This repository has been archived by the owner on Mar 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogging_queue.py
62 lines (48 loc) · 2.11 KB
/
logging_queue.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import queue
import asyncio
import logging
from logging.handlers import QueueHandler, QueueListener
from contextlib import contextmanager
class LocalQueueHandler(QueueHandler):
def emit(self, record: logging.LogRecord) -> None:
# There is no need to self.prepare() records that go into a local, in-process queue.
# We can skip that process and further minimise the cost of logging.
try:
self.enqueue(record)
except asyncio.CancelledError:
raise
except Exception:
self.handleError(record)
def setup_logging_queue(name=None, local=False):
logger = logging.getLogger(name)
# Remove logger's current handlers to pass them to the queue listener
handlers = []
for handler in logger.handlers[:]:
logger.removeHandler(handler)
handlers.append(handler)
# Log to a queue instead of doing blocking I/O
que = queue.SimpleQueue() # fast reentrant queue implementation without task tracking (not needed for logging)
logger.addHandler(LocalQueueHandler(que) if local else QueueHandler(que))
if not handlers:
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter('%(asctime)s [%(name)s] %(levelname)s: %(message)s'))
handlers.append(handler)
logger.warning(f'No log handler provided. Using default. Logger level = {logging.getLevelName(logger.level)}')
# Set up a listener that will monitor the queue and run the blocking I/O in a separate thread
return QueueListener(que, *handlers, respect_handler_level=True)
@contextmanager
def listen(listener):
listener.start()
try:
yield listener
finally:
listener.stop()
if __name__ == '__main__':
async def test_coro():
logging.info('Waiting...')
logging.info(await asyncio.sleep(1, 'Finished!'))
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)s, %(lineno)d] %(levelname)s: %(message)s')
log_listener = setup_logging_queue(local=True)
with listen(listener=log_listener):
asyncio.run(test_coro())