The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,640 other followers

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: