-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.py
54 lines (46 loc) · 1.54 KB
/
logging.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
import math
import os
import queue
import threading
from shutil import move
class LogWriter(threading.Thread):
rollover_size = math.pow(1024, 2) * 100
rollover_postfix = '.1' # Only keep one rolled file
def __init__(self, log_file):
threading.Thread.__init__(self)
self._queue = queue.Queue()
self._log_file = log_file
self._stop_event = threading.Event()
self.setDaemon(True)
self.start()
def run(self):
log_file = open(self._log_file, 'a')
try:
while not self._stop_event.is_set():
try:
result = self._queue.get(timeout=15)
log_file.write(result)
log_file.flush() # TODO: set a manual buffer instead
self._queue.task_done()
if os.fstat(log_file.fileno()).st_size > self.rollover_size:
log_file.close()
log_file = self._roll(log_file)
except queue.Empty:
pass # If we encounter a timeout
except IOError as e:
print(e)
finally:
log_file.flush()
log_file.close()
def stop(self):
self._stop_event.set()
self._queue.join()
def write(self, p):
self._queue.put(p)
def _roll(self, file_obj):
try:
file_obj.close()
move(self._log_file, self._log_file + self.rollover_postfix)
except IOError as e:
raise e
return open(self._log_file, 'a')