File size: 2,350 Bytes
a31f9ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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