Last active
September 3, 2021 09:25
-
-
Save angely-dev/d2d72275bdde7e9430ceba61dda3e2be to your computer and use it in GitHub Desktop.
Python logging exit on error or critical levels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import logging.handlers | |
import sys | |
# | |
# The logger and the logging level | |
# | |
logger = logging.getLogger('mylogger') | |
logger.setLevel(logging.DEBUG) | |
# | |
# Exit handler | |
# | |
class ExitHandler(logging.StreamHandler): | |
def emit(self, record): | |
super().emit(record) | |
if record.levelno in (logging.ERROR, logging.CRITICAL): | |
sys.exit(1) | |
eh = ExitHandler() | |
logger.addHandler(eh) | |
# | |
# Logging format | |
# | |
fmt = '%(asctime)s %(module)-15s %(levelname)-15s %(message)s' | |
datefmt = '%Y-%m-%d %H:%M:%S' | |
formatter = logging.Formatter(fmt, datefmt) | |
eh.setFormatter(formatter) | |
# | |
# Logging test | |
# | |
logger.debug('debug message') | |
logger.info('info message') | |
logger.warning('warn message') | |
logger.error('error message') # will exit here | |
logger.critical('critical message') # or here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: