Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 

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

like image 758
Maxim Veksler Avatar asked Dec 22 '10 11:12

Maxim Veksler


People also ask

How do you log an exception in Python?

To log an exception in Python we can use logging module and through that we can log the error. Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger.

What is logging getLogger (__ Name __)?

getLogger(name) is typically executed. The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not. Multiple calls to getLogger() with the same name will return a reference to the same logger object.

How do I log exception traceback in Python?

This is how I do it. try: do_something() except: # How can I log my exception here, complete with its traceback? import traceback traceback. format_exc() # this will print a complete trace to stout.


1 Answers

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.

like image 168
rlotun Avatar answered Sep 21 '22 05:09

rlotun