Skip to content

Instantly share code, notes, and snippets.

@GenevieveBuckley
Last active July 29, 2019 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GenevieveBuckley/7972a78fd5d81d4d4b761bc302dbefe2 to your computer and use it in GitHub Desktop.
Save GenevieveBuckley/7972a78fd5d81d4d4b761bc302dbefe2 to your computer and use it in GitHub Desktop.
Log all uncaught exceptions to file with sys.excepthook
import os
import logging
import sys
import time
import traceback
from mypackage import __version__
def _exception_handler(error_type, error_value, error_traceback):
"""Log all uncaught exceptions at runtime with sys.excepthook"""
log = logging.getLogger(__name__)
log.exception("Uncaught exception {} {}".format(
str(error_type), str(error_value)))
tb = traceback.format_exception(
error_type, error_value, error_traceback)
traceback_string = ''
for ln in tb:
traceback_string += ln
log.exception(traceback_string)
def begin_log_file(settings=None):
"""Initialize logging and begin writing log file.
Parameters
----------
settings : dictionary of user input settings, optional.
Returns
-------
log_filename : str
Filepath to output log text file location.
"""
timestamp = time.strftime('%d-%b-%Y_%H-%M%p', time.localtime())
log_filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'..', 'logs', 'logging.conf')
if os.path.exists(log_filename):
os.remove(log_filename)
sys.excepthook = _exception_handler
logging.basicConfig(
format="%(asctime)s %(message)s",
level=logging.INFO,
handlers=[
logging.FileHandler("{}".format(log_filename)),
logging.StreamHandler()
])
log = logging.getLogger(__name__)
# Log user input arguments
log.info("Wersion {}".format(__version__))
log.info("{}".format(timestamp))
if settings:
log.info("========== USER CONFIG SETTINGS ==========")
for key, val in settings.items():
log.info("{}: {}".format(key, val))
log.info("=========== END OF USER INPUT ============")
return log_filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment