Python: Catching Traceback.

For PyQT Development, i have noticed that when or if the application i am working on is crashing i never see the traceback. Using Pycharm IDE i can only get it to display the traceback if i run my app in Debug Mode, which is not always what i want for various reasons. So, after some googling around and experimenting, i have learned a way to properly display and also log (may be even to a file) the crash-reports as the happen.

Here is how to get this setup.

Assuming you are working with MVC type model (can be even super simple), in your ‘main’ module that fires off all other packages, you must defined a custom function, that will be used to handle the logging. Here is how i have it in a simple case:

import logging
import traceback
import sys

def crash_report(exctype, value, tb):
 """Custom Crash-Handler"""
 logger = logging.getLogger('myapp.crash_report')
 logger.critical("\n--- Logging error ---\n"
 "Message: My-App has experienced an unrecoverable error.\n"
 "Traceback: (Most recent call last)"

Now, we need to override default python function, and give it our new function to use instead, we can simply do it like so:

sys.excepthook = crash_report

You only need to do it once, at the top level, and every time your application goes through some hard times, you will know why.

we can test it like this:

test = "mememe"
num = int(test)

Leave a Reply

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

You are commenting using your 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