Skip to content

Commit

Permalink
Fixed excepthook problems
Browse files Browse the repository at this point in the history
  • Loading branch information
seankmartin committed Jul 27, 2020
1 parent 21f5df9 commit 90184db
Showing 1 changed file with 15 additions and 13 deletions.
28 changes: 15 additions & 13 deletions skm_pyutils/py_log.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""
Logging related functions.
TODO test the except hooks more.
"""
import datetime
import logging
Expand Down Expand Up @@ -32,9 +30,7 @@ def log_exception(ex, more_info="", location=None):
"""
if location is None:
default_loc = os.path.join(
os.path.expanduser("~"), ".skm_python", "caught_errors.txt"
)
default_loc = get_default_log_loc("caught_errors.txt")
else:
default_loc = location

Expand All @@ -53,27 +49,25 @@ def log_exception(ex, more_info="", location=None):

def default_excepthook(exc_type, exc_value, exc_traceback):
"""Any uncaught exceptions will be logged from here."""
default_loc = os.path.join(
os.path.expanduser("~"), ".skm_python", "uncaught_errors.txt"
)
default_loc = get_default_log_loc("uncaught_errors.txt")

this_logger = logging.getLogger(__name__)
file_logger = logging.getLogger(__name__)
file_logger.propagate = False
handler = logging.FileHandler(default_loc)
this_logger.addHandler(handler)
file_logger.addHandler(handler)

# Don't catch CTRL+C exceptions
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return

now = datetime.datetime.now()
this_logger.critical(
file_logger.critical(
"\n----------Uncaught Exception at {}----------".format(now),
exc_info=(exc_type, exc_value, exc_traceback),
)

sys.stdout.write = default_write
print("A fatal error occurred in this Python program")
print("\nA fatal error occurred in this Python program")
print(
"The error info was: {}".format(
"".join(
Expand All @@ -83,6 +77,8 @@ def default_excepthook(exc_type, exc_value, exc_traceback):
)
print("Please report this to {} and provide the file {}".format("us", default_loc))

sys.exit(-1)


def override_excepthook(excepthook=None):
"""
Expand All @@ -104,3 +100,9 @@ def override_excepthook(excepthook=None):
if excepthook is None:
excepthook = default_excepthook
sys.excepthook = excepthook


def get_default_log_loc(name):
default_loc = os.path.join(os.path.expanduser("~"), ".skm_python", name)

return default_loc

0 comments on commit 90184db

Please sign in to comment.