current position:Home>Python logging log error and exception exception callback method

Python logging log error and exception exception callback method

2022-02-01 03:58:25 ilyq69


  • stay Python Handle the error level log output or program exceptions , Such as : Log alert , Abnormal notice


logging record

  • By rewriting logging.Logger.callHandlers This method can do some other processing when printing the log
import logging

logger = logging.getLogger(__name__)

old_callHandlers = logging.Logger.callHandlers  #  Copy the original  callHandlers

def callHandlers(self, record):
       return old_callHandlers(self, record)
       #  Custom business logic can be added here ,  Each time printing log Will come in 
       if record.levelno >= logging.ERROR:  #  Greater than or equal to ERROR Levels of log Just output 
 "callHandlers: %s", record.message)

#  Replace the original callHandlers Method 
logging.Logger.callHandlers = callHandlers"info log")
logger.error("error log")
logger.error("error log001")

#  Output 
INFO:__main__:info log
ERROR:__main__:error log
INFO:__main__:callHandlers: error log
ERROR:__main__:error log001
INFO:__main__:callHandlers: error log001
 Copy code 

exception handling

  • Realization sys.excepthook Method , If it is a thread, you need to implement threading.excepthook
import sys
import logging

def callback_func(exc_type, exc_value, exc_traceback):
    logging.error("callback_func>>>>>>>>>>>>>>", exc_info=(
        exc_type, exc_value, exc_traceback))

sys.excepthook = callback_func

1 / 0

#  Output 
Traceback (most recent call last):
  File "C:/Users/dong/PycharmProjects/err-callback-py/", line 14, in <module>
    1 / 0
ZeroDivisionError: division by zero
 Copy code 


  • Recommend an encapsulated Library err-callback-py, In that way, you can write your own business logic directly

copyright notice
author[ilyq69],Please bring the original link to reprint, thank you.

Random recommended