@@ -55,7 +55,7 @@ def __init__(self, target=None, name=None, args=None, kwargs=None, daemon=True):
5555 # Public state properties
5656 self .progress : int = None # Percent progress of the task
5757 self .data = {} # Dictionary of custom data added during the task
58- self .log = [] # The log will hold dictionary objects with log information
58+ self .log = [] # The log will hold dictionary objects with log information
5959
6060 # Stuff for handling termination
6161 self ._running_lock = Lock () # Lock obtained while self._target is running
@@ -112,8 +112,8 @@ def wrapped(*args, **kwargs):
112112 self ._status = "error"
113113 finally :
114114 self ._end_time = datetime .datetime .now ().strftime ("%Y-%m-%d %H-%M-%S" )
115- logging .getLogger ().removeHandler (handler ) # Stop logging this thread specially
116-
115+ logging .getLogger ().removeHandler (handler ) # Stop logging this thread
116+ # If we don't remove the handler, it's a memory leak.
117117 return wrapped
118118
119119 def run (self ):
@@ -209,11 +209,27 @@ def terminate(self):
209209 self ._status = "terminated"
210210 self .progress = None
211211
212+
212213class ThreadLogHandler (logging .Handler ):
213- def __init__ (self , thread = None , dest = []):
214+ def __init__ (self , thread = None , dest = None ):
215+ """Set up a log handler that appends messages to a list.
216+
217+ This log handler will first filter by ``thread``, if one is
218+ supplied. This should be a ``threading.Thread`` object.
219+ Only log entries from the specified thread will be
220+ saved.
221+
222+ ``dest`` should specify a list, to which we will append
223+ each log entry as it comes in. If none is specified, a
224+ new list will be created.
225+
226+ NB this log handler does not currently rotate or truncate
227+ the list - so if you use it on a thread that produces a
228+ lot of log messages, you may run into memory problems.
229+ """
214230 logging .Handler .__init__ (self )
215231 self .thread = thread
216- self .dest = dest
232+ self .dest = dest if dest else []
217233 self .addFilter (self .check_thread )
218234
219235 def check_thread (self , record ):
@@ -222,8 +238,7 @@ def check_thread(self, record):
222238 return 1
223239 if record .thread == self .thread .ident :
224240 return 1
225- else :
226- return 0
241+ return 0
227242
228243 def emit (self , record ):
229244 """Do something with a logged message"""
@@ -233,4 +248,5 @@ def emit(self, record):
233248 "level" : record .levelname ,
234249 "message" : record .getMessage (),
235250 })
236-
251+ # FIXME: make sure this doesn't become a memory disaster!
252+ # We probably need to check the size of the list...
0 commit comments