简体   繁体   中英

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()')

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..)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM