Skip to content

Instantly share code, notes, and snippets.

@gothma
Created November 22, 2015 10:24
Show Gist options
  • Save gothma/2459959b58b8af895574 to your computer and use it in GitHub Desktop.
Save gothma/2459959b58b8af895574 to your computer and use it in GitHub Desktop.
Python logging: Trigger exit on critical error
from __future__ import print_function
import logging
import sys
class ShutdownHandler(logging.Handler):
def emit(self, record):
print(record.msg, file=sys.stderr)
logging.shutdown()
sys.exit(1)
logging.getLogger().addHandler(ShutdownHandler(level=50))
@rlaphoenix
Copy link

logging.shutdown() is unnecessary as stated by the logging.shutdown() docs

When the logging module is imported, it registers this function as an exit handler (see atexit), so normally there’s no need to do that manually.

@rlaphoenix
Copy link

class ShutdownHandler(logging.StreamHandler):
    def emit(self, record):
        super(ExitHandler, self).emit(record)
        if record.levelno >= logging.CRITICAL:
            sys.exit(1)

This worked out a bit better for me. Sending level as a param to logging.Handler doesn't work for me but manually checking it in emit with logging.StreamHandler as the base class worked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment