Michael
Michael

Reputation: 786

Python: Catching a logging.exception() call

I am trying to catch an exception that is not raised, just logged. Is there any way to do this?

def exampleFunction():
    try:
        x = 1 / 0
    except Exception:
        logging.exception('divide by 0 error here.')

try:
    exampleFunction()
except <condition based on if logging.exception was called>
    print('there was a divide by 0 error when I called exampleFunction()')

Upvotes: 2

Views: 121

Answers (2)

Christian Sauer
Christian Sauer

Reputation: 10889

I assume that exampleFunction is in some horrible third party code that you do not own, otherwise there are lots of better alternatives.

What you can do:

import logging # make sure this is the FIRST import of logging
import horrible_third_party_lib

def catch_log(msg):
   # do something when this is called
old_logging = logging.exception
try:
    logging.exception=catch_log
    horrible_third_party_lib.exampleFunction()
finally:
    logging.exception=old_logging

You can then do everything you want in the function. It's horrible and sensitive to import order, but I have used this and it works (scikit learn does something similarly repugnant..)

Upvotes: 2

stovfl
stovfl

Reputation: 15513

Question: I am trying to catch an exception
The Questions Title should be rewriten to "I am trying to reraise an exception"

Read Python Documentation#raise
Seems somewhat double work, but you can do it like that:

def exampleFunction():
    try:
        x = 1 / 0
    except Exception as e:
        print("logging.exception({})".format(e))
        raise

try:
    exampleFunction()
except ZeroDivisionError as e:
    print('there was a divide by 0 error when I called exampleFunction()')

Output:

logging.exception(division by zero)
there was a divide by 0 error when I called exampleFunction()

Tested with Python:3.5.3

Upvotes: 0

Related Questions