import datetime
import logging
import os
import sys


def build_logger(cfg):
    log_dir = os.path.join("log", "{}-{}".format(cfg.GLOBALS.EXPR_NAME, datetime.datetime.now().strftime("%Y%m%d_%H%M%S")))
    log_file = '{}/info.log'.format(log_dir)
    logger = logging.getLogger('my_logger')
    logger.setLevel(cfg.GLOBALS.FILE_VERBOSE_LEVEL)

    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    file_handler = logging.FileHandler(log_file)
    file_handler.setLevel(cfg.GLOBALS.FILE_VERBOSE_LEVEL)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(cfg.GLOBALS.CONSOLE_VERBOSE_LEVEL)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    def handle_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) # 重点


    sys.excepthook = handle_exception
    return logger, log_dir