diff --git a/src/dllib/logger.py b/src/dllib/logger.py new file mode 100644 index 0000000..a22db2e --- /dev/null +++ b/src/dllib/logger.py @@ -0,0 +1,37 @@ +import logging +import sys +from pathlib import Path + + +# Sets the directory of the logfile and creates the file if it doesnt +# already exist. +LOG_DIR = Path.home() / ".local" / "share" / "ytdlp-tui" +LOG_DIR.mkdir( + parents=True, + exist_ok=True, +) +LOG_FILE = LOG_DIR / "ytdlp-tui.log" + +# Initilize the logger and formatting the output which gets written to +# the log. +logging.basicConfig( + level=logging.DEBUG, + format="%(asctime)s - %(levelname)s - %(message)s", + filename=LOG_FILE, +) +logger = logging.getLogger() + + +# Catches Python errors and adds them to the log file instead of +# outputting it to the terminal. +def handle_exception(exec_type, exec_value, exec_traceback): + if issubclass(exec_type, KeyboardInterrupt): + sys.__excepthook__(exec_type, exec_value, exec_traceback) + return + logger.error( + "External error accured", + exc_info=(exec_type, exec_value, exec_traceback), + ) + + +sys.excepthook = handle_exception