anoncoward
anoncoward

Reputation: 123

Python error logging

I'd like to find a way to log every error that forces the python interpreter to quit to be saved to a file as well as being printed to the screen. The reason I would like to do this is that I want to keep stats on the types of errors I make while writing code, with an eye towards finding ways to avoid mistakes I make commonly in the future.

I've been attempting to do this by writing a wrapper for the python interpreter using the subprocess module. Basically, it runs the python interpreter, captures any output, parse and saves it to a file, prints the output, and use matplotlib to make some summary figures. However, I'm having a problem getting output from my wrapper script in real time. For example, if the script I'm running is:

import os  
import time

for x in range(10):  
    print "testing"  
    time.sleep(10)  

and I'm using subprocess.Popen() with p.communicate(), the wrapper will wait 100 seconds, and then print all of the output. I'd like the wrapper to be as invisible as possible - ideally in this case it would print "testing" once every ten seconds.

If someone could point me towards a good way of doing this, I'd greatly appreciate it.

Thanks!

Upvotes: 3

Views: 6079

Answers (1)

Chris B.
Chris B.

Reputation: 90161

I believe you can simply replace sys.excepthook with your own function. You can read about it in the Python documentation.

Basically, it allows you to customize what happens when an exception percolates up to the point of forcing the Python interpreter to quit. You use it like this:

import sys

def my_excepthook(type, value, tb):
    # you can log the exception to a file here
    print 'In My Exception Handler'

    # the following line does the default (prints it to err)
    sys.__excepthook__(type, value, tb)

sys.excepthook = my_excepthook

You'll probably also want to look at the traceback module, for formatting the traceback you get.

Upvotes: 6

Related Questions