Getting trace from exceptions without raising them again

I use Twister to create a server. I also maintain a server error log. The problem is that if I allow the exception to be triggered before the stack, this will lead to the failure of the current connection and disconnection of the user, so, obviously, I attach the bare one except to capture everything else.

As soon as I caught something, is there a way to get the trace as a string so that I can store / print it somewhere myself without picking it up and letting Python print it for me after the program crashes?

+4
source share
4 answers

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

Quote from:

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

Before executing the except except package, the details of the exception are assigned to three variables in the sys module: sys.exc_type receives an object that identifies the exception; sys.exc_value receives the exceptions parameter; sys.exc_traceback gets the trace object ...

You can pass the sys.exc_traceback object as the parameter traceback.print_tb so that the trace is printed to stdout in the except clause.

+2
source

Using the logging module , you can write a trace 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) 
+1
source

Try the following:

 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 ) 

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

+1
source

Yes, there is a module . The traceback module contains functions for printing or formatting exception information or for returning raw stack frames so you can do whatever you want with them.

However, for a fairly complex application, I would recommend using a logging system instead of the usual old traceback functions. In particular, the logging.Logger.exception method will record exception information from any destination that you (or your software user) has configured. The default formatter will simply print the trace since Python will be on the console, but you can configure the display of exceptions in your log by creating a Formatter and overriding format_exception . Your overridden method is the place to call traceback functions if you need to format the exception output.

0
source

Source: https://habr.com/ru/post/1390150/


All Articles