Exceptions: Logging TB and local variables?

Larry Bates larry.bates at websafe.com
Wed Oct 10 08:26:01 EDT 2007


allen.fowler wrote:
> Hi,
> 
> My code looks like this:
> 
> for item in bigset:
>   self.__sub1(item)
>   self.__sub2(item)
>   self.__sub3(item)
> 
> # the subX functions, in turn, use various 3rd party modules.
> 
> 
> Now, I would like to do this:
> 
> for item in bigset:
>   try:
>     self.__sub1(item)
>     self.__sub2(item)
>     self.__sub3(item)
>   except StandardError:
>     # Log error and continue to next item in set.
>     log_error_to_file()
> 
> 
> In the error log, I would like to record various local variables that
> existed in subX at the time the Exception was thrown... (even though
> the actuall exception may have been thrown from deep inside some 3rd
> party module that subX called)
> 
> How can I do this?
> 
> Thank you,
> Allen
> 


Two possibilieies:

You will need to determine ALL the exceptions that the 3rd party party modules 
can raise.  If they are custom exceptions you will need to import them into your 
application from their modules.

example:

say that 3rd party modules raise TransientError, IOError, and ValueError 
exceptions.  TransientError is a custom exception from module foo

from foo import TransientError

for item in bigset:
   try:
     self.__sub1(item)
     self.__sub2(item)
     self.__sub3(item)
   except (TransientError, IOError, ValueError):
     # Log error and continue to next item in set.
     log_error_to_file()


2) Hook exception traceback handler

def myTraceBackHandler(type, value, tb):
     global <variables I want to dump during traceback>
     #
     # This function allows the user to redefine what happens if the program
     # aborts due to an uncaught exception.
     # This provides a way to get a "partial" session log if the program
     # aborts"as well as some information about what caused the program to
     # abort.
     #
     import traceback
     #
     # Get traceback lines
     #
     tblines=traceback.format_exception(type, value, tb)
     #
     # Write some lines to log
     #
     log_error_to_file()
     #
     # Always write the exceptions to screen
     #
     sys.exit('\n'.join(tblines))


Hope this helps.

-Larry



More information about the Python-list mailing list