By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,585 Members | 1,784 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,585 IT Pros & Developers. It's quick & easy.

Function to log exceptions and keep on truckin

P: n/a
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...

Jul 19 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.