Function to log exceptions and keep on truckin

S

Steve M

import sys, traceback
def e2str(id):
"""Return a string with information about the current exception. id
is arbitrary string included in output."""

exc = sys.exc_info()
file, line, func, stmt = traceback.extract_tb(exc[2])[-1]
return("%s: %s line %s (%s): %s" % (id, func, line, repr(stmt),
str(exc[1])))


This function returns a string containing useful information about the
current exception.
It takes as argument an arbitrary string that gets included in the
output. You can include anything else that might be useful in this
string, such as a loop counter or other local variable.
You can use this function to log anything you'd want to know about an
exception but continue running.
For example:

for i in interable:
try:
some_function(i)
except NonFatalError:
print e2str(str(i))


For some reason I've been into closures lately, so I like to have the
following code in a general utility module, from which I import *:

def _make_e2str():
"""This function creates a closure e2str."""
import sys, traceback
def e2str(id):
"""Return a string with information about the current
exception. id is arbitrary string included in output."""

exc = sys.exc_info()
file, line, func, stmt = traceback.extract_tb(exc[2])[-1]
return("%s: %s line %s (%s): %s" % (id, func, line, repr(stmt),
str(exc[1])))
return e2str
e2str = _make_e2str()
del _make_e2str #clean up the namespace...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,234
Messages
2,571,179
Members
47,811
Latest member
GregoryHal

Latest Threads

Top