Retrieving a stacktrace from an exception object / forwarding an exception

S

Samuel

Hi,

I am trying to wrap a function that throws an exeption in such a way
that the stacktrace is logged into a file and the exception is
forwarded after that. For example:

-------------------
def my_func():
raise Exception("hello")

def wrapper():
try:
my_func()
except Exception, e:
f = open("logfile", 'a')
f.write(e.stacktrace())
raise e

wrapper() # should throw the exception with a stacktrace showing
my_func()
 
G

Gabriel Genellina

I am trying to wrap a function that throws an exeption in such a way
that the stacktrace is logged into a file and the exception is
forwarded after that. For example:

-------------------
def my_func():
raise Exception("hello")

def wrapper():
try:
my_func()
except Exception, e:
f = open("logfile", 'a')
f.write(e.stacktrace())
raise e

wrapper() # should throw the exception with a stacktrace showing
my_func()

- see the traceback module
<http://docs.python.org/lib/module-traceback.html>
- use a bare raise (not raise e); this reraises the active exception
without changing its context.
 
A

alg

Use the traceback module:

def log_exception():
"""This function will log the current exception's traceback
to logfile
"""
import traceback
f = open("logfile", 'a')
traceback.print_exc(32, f)
f.close()

def my_func():
raise Exception

def wrapper():
try:
my_func()
except Exception, e:
log_exception()
raise e
 

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

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top