How to register python exception?

How can I register an exception in Python?

I looked through some parameters and found out that I can access the actual details of the details using this code:

import sys import traceback try: 1/0 except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) 

I would like to somehow get the line print_exception() throws to stdout so that I can register it.

+43
python logging exception-handling
Dec 22 2018-10-22
source share
5 answers

To answer your question, you can get a line version of print_exception() using the traceback.format_exception() function. It returns a trace message as a list of strings, and does not print it to stdout, so you can do what you want. For example:

 import sys import traceback try: asdf except NameError: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) print ''.join('!! ' + line for line in lines) # Log it or whatever here 

Displayed:

 !! Traceback (most recent call last): !! File "<stdin>", line 2, in <module> !! NameError: name 'asdf' is not defined 

However, I would definitely recommend using the standard Python logging module, as suggested by rlotun. This is not the easiest setting, but it is very customizable.

+47
Dec 22 2018-10-22
source share

Take a look at logging.exception ( Python logging.exception Module )

 import logging def foo(): try: some_code() except: logging.exception('') 

This should automatically take care of getting a trace for the current exception and correctly registering it.

+91
Dec 22 '10 at 11:49
source share

Log exceptions are as simple as adding the exc_info = True argument to any log message, see the entry for Logger.debug at http://docs.python.org/2/library/logging.html .

Example:

 try: raise Exception('lala') except Exception: logging.info('blah', exc_info=True) 

(depends, of course, on the configuration of your log handler):

 2012-11-29 10:18:12,778 - root - INFO - <ipython-input-27-5af852892344> : 3 - blah Traceback (most recent call last): File "<ipython-input-27-5af852892344>", line 1, in <module> try: raise Exception('lala') Exception: lala 
+39
Nov 29 '12 at 8:22
source share

In Python 3.5, you can pass an instance of an exception to the exc_info argument:

 import logging try: 1/0 except Exception as e: logging.error('Error at %s', 'division', exc_info=e) 
+6
Jun 23 '16 at 13:24
source share

First of all, consider using the correct Exception type in the except clause. Then, calling the exception, you can print it:

 try: 1/0 except Exception as e: print e 

Depending on your version of Python, you should use

 except Exception, e 
+5
Dec 22 2018-10-22
source share



All Articles