Question

I'm using Twister to build a server. I am also maintaining a server error log. The issue is that if I let an exception run all the way up the stack, it'll crash the current connection and disconnect the user, so obviously I attach a bare except to grab everything else.

Once I've caught something, is there a way to get the traceback as a string so that I can store it somewhere/print it myself without raising it and letting Python print it for me once the program crashes?

Was it helpful?

Solution

The traceback module contains some helper functions for printing and inspecting the traceback (for exameble, traceback.print_tb ) - but the important thing is that the traceback information itself is stored in a "interpreter global" variable - sys.exc_traceback, on the module sys.

Quoting from:

http://docs.python.org/reference/compound_stmts.html#try

Before an except clause’s suite is executed, details about the exception are assigned to three variables in the sys module: sys.exc_type receives the object identifying the exception; sys.exc_value receives the exception’s parameter; sys.exc_traceback receives a traceback object...

You can pass the sys.exc_traceback object as a parameter to traceback.print_tb to have the traceback printed to stdout within the except clause.

OTHER TIPS

Using the logging module, you could log the traceback to a file:

import logging
logging.basicConfig(level = logging.DEBUG, filename = logfile)
logger = logging.getLogger(__name__)
try:
    1/0
except ZeroDivisionError as err:
    logger.exception(err)

Try this:

import traceback, sys

try:
    # Do something that might raise an exception
    open("/does not exist",'rb')
except:
    traceback.print_exc( file=sys.stderr )
    # Or 
    traceback.print_exc( file=your_open_log_file )

That should do the trick and print full stack traces too.

Yep, there's a module for that. The traceback module contains functions to print or format exception information, or to return the raw stack frames so you can do whatever you want with them.

For a reasonably sophisticated application, though, I would actually recommend using the logging system instead of plain old traceback functions. In particular the method logging.Logger.exception will write information about the exception to whatever logging destination you (or your software's user) has configured. The default formatter will just print out a traceback, as Python would on the console, but you can customize the display of exceptions in your log by creating a Formatter and overriding the format_exception method. Your overridden method is the place to call traceback functions if you need them to format the exception output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top