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

demand

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

Realization

logging record

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

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

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


def callHandlers(self, record):
   try:
       return old_callHandlers(self, record)
   finally:
       #  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 
           logger.info("callHandlers: %s", record.message)


#  Replace the original callHandlers Method 
logging.Logger.callHandlers = callHandlers

logger.info("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 
ERROR:root:callback_func>>>>>>>>>>>>>>
Traceback (most recent call last):
  File "C:/Users/dong/PycharmProjects/err-callback-py/main.py", line 14, in <module>
    1 / 0
ZeroDivisionError: division by zero
 Copy code 

Last

  • 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.
https://en.pythonmana.com/2022/02/202202010358236523.html

Random recommended