Python threading: logging exceptions during the `run`
Posted by jpluimers on 2018/12/19
In A few observations on Python while I made my first steps into it, I mentioned the standard threading idiom in Python by wrapping the thread in a function. This has the drawback of having to catch and handle any exceptions in that function.
The higher level [WayBack] threading
module has a [WayBack] Thread
class with a [WayBack] run()
method does not handle exceptions either.
For investigation of threading issues, it’s very convenient to know about the exceptions in a thread and their context.
So I’ve made a small base class that automagically logs any exceptions during a run
:
import threading from log import Log class ExceptionLoggingThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.logger = Log().getLogger() self.logger.debug("ExceptionLoggingThread().") def run_logic(self): self.logger.debug("Thread started.") def run(self): try: self.run_logic() except: self.logger.exception('Exception in `run`') raise
–jeroen
Leave a comment