stefantaubert's picture
update
e3bcf30
raw
history blame
2.35 kB
import logging
from logging import getLogger
from time import perf_counter
from typing import Callable
from en_tts_app.globals import get_conf_dir, get_log_path
from en_tts_app.logging_configuration import (configure_app_logger, configure_file_logger,
configure_root_logger, get_file_logger)
INITIALIZED = False
def ensure_conf_dir_exists():
conf_dir = get_conf_dir()
if not conf_dir.is_dir():
root_logger = getLogger()
root_logger.debug("Creating configuration directory ...")
conf_dir.mkdir(parents=False, exist_ok=False)
def configure_external_loggers() -> None:
file_logger = get_file_logger()
for logger_name in ("httpcore", "httpx", "asyncio", "matplotlib"):
logger = getLogger(logger_name)
logger.parent = file_logger
logger.disabled = False
logger.propagate = True
logger.level = logging.DEBUG
def initialize_app() -> int:
global INITIALIZED
assert not INITIALIZED
# CLI logging = INFO
# External loggers go to file-logger
# file-logger = DEBUG
# # disable mpl temporarily
# mpl_logger = getLogger("matplotlib")
# mpl_logger.disabled = True
# mpl_logger.propagate = False
configure_root_logger(logging.INFO)
root_logger = getLogger()
logfile = get_log_path()
try:
configure_file_logger(logfile, logging.DEBUG)
except Exception as ex:
root_logger.exception("Logging to file is not possible. Exiting.", exc_info=ex, stack_info=True)
return 1
configure_app_logger(logging.INFO)
configure_external_loggers()
ensure_conf_dir_exists()
# path not encapsulated in "" because it is only console out
root_logger.info(f"Log will be written to: {logfile.absolute()}")
INITIALIZED = True
return 0
def run_main(method: Callable) -> int:
global INITIALIZED
assert INITIALIZED
flogger = get_file_logger()
start = perf_counter()
success = True
try:
method()
except ValueError as error:
success = False
logger = getLogger(__name__)
logger.debug("ValueError occurred.", exc_info=error)
except Exception as error:
success = False
logger = getLogger(__name__)
logger.debug("Exception occurred.", exc_info=error)
duration = perf_counter() - start
flogger.debug(f"Total duration (seconds): {duration}")
exit_code = 0 if success else 1
return exit_code