Created
March 30, 2015 13:22
-
-
Save ycopin/bd337bf1f85729575afd to your computer and use it in GitHub Desktop.
Example of implicit logging management.
This file contains hidden or 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
#!/usr/bin/env python | |
# Time-stamp: <2015-03-30 15:21:15 ycopin> | |
from __future__ import division, print_function | |
""" | |
Example of implicit logging management. | |
""" | |
import sys, atexit, traceback | |
class ExitLogger(object): | |
def __init__(self, pid, verbose=True): | |
self.pid = pid | |
self.status = 0 | |
self.msg = "Nothing to report" | |
# Register methods for exceptions and exit | |
sys.excepthook = self._excepthook | |
atexit.register(self._atexit) | |
self.verbose = verbose | |
if self.verbose: | |
print("From now on, all exits will be intercepted.") | |
def __str__(self): | |
return "ExitLogger: pid={}, status={}, msg={!r}".format( | |
self.pid, self.status, self.msg) | |
def critical_warning(self, status, msg): | |
self.status = status | |
self.msg = msg | |
def _excepthook(self, exctype, value, tb): | |
if self.verbose: | |
print("Traceback:") | |
traceback.print_tb(tb) | |
self.status = 1 | |
self.msg = "{}: {}".format(exctype.__name__, value.message) | |
def _atexit(self): | |
print(self.__str__()) | |
if __name__ == '__main__': | |
import os | |
try: | |
case = int(sys.argv[1]) # Could fail | |
except Exception as err: | |
raise RuntimeError("Usage: {} 0|1|2".format(sys.argv[0])) | |
logger = ExitLogger(os.getpid()) | |
if case == 0: # Everything is going smoothly | |
print("Everything is going smoothly.") | |
elif case == 1: # A warning is issued, but the code does not crash | |
print("A critical warning is issued.") | |
logger.critical_warning(2, "Warning") | |
elif case == 2: # An exception is raised somewhere | |
print("Something went wrong.") | |
raise RuntimeError("Error") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment