Python exception logger logging

How to log python exception? [duplicate]

How can I log an exception in Python? I’ve looked at some options and found out I can access the actual exception 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) 

At least raise (without argument, so the stracktrace gets preserved) after logging, otherwise you swallow the exception silently.

You should always explicitly state the exception you are trying to catch: except NameError as e , say. That will prevent you catching things like KeyboardInterrupt and give you a reference to the exception object, which you can study for more details.

5 Answers 5

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

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

This should automatically take care of getting the traceback for the current exception and logging it properly.

In Python 3.5 you can pass exception instance in exc_info argument:

import logging try: 1/0 except Exception as e: logging.error('Error at %s', 'division', exc_info=e) 

This is exactly what I wanted. I needed to log an exception from a task and didn’t have an except block.

To answer your question, you can get the string version of print_exception() using the traceback.format_exception() function. It returns the traceback message as a list of strings rather than printing it to stdout, so you can do what you want with it. 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 
!! Traceback (most recent call last): !! File "", line 2, in !! NameError: name 'asdf' is not defined 

However, I’d definitely recommend using the standard Python logging module, as suggested by rlotun. It’s not the easiest thing to set up, but it’s very customizable.

Источник

Читайте также:  Интерлиньяж
Оцените статью