-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.py
49 lines (42 loc) · 1.16 KB
/
logger.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
import sys
from subprocess import PIPE, Popen
from threading import Thread, main_thread, Lock
from queue import Queue, Empty
from time import sleep
from pathlib import Path
from util import non_block_read
READ_SIZE = 8096
LOG_DIR = "logs/"
class Logger(Thread):
def __init__(self):
Thread.__init__(self)
self.streams = dict()
self.files = dict()
self.mutex = Lock()
Path(LOG_DIR).mkdir(exist_ok=True)
def add(self, stream, filename):
self.mutex.acquire()
try:
if not filename in self.files.keys():
self.files[filename] = open(LOG_DIR + filename, "ab")
self.streams[filename] = stream
finally:
self.mutex.release()
def run(self):
while main_thread().is_alive():
self.mutex.acquire()
try:
for filename, stream in self.streams.items():
f = self.files[filename]
while True:
output = non_block_read(stream)
if output == None or output == b'':
break
f.write(output)
f.flush()
print(output.decode('utf-8'))
finally:
self.mutex.release()
sleep(0.1)
logger = Logger()
logger.start()