'''
Created on 6 juil. 2017

@author: olivier.massot
'''
import logging.config
import sys
import traceback

import yaml

from core.constants import DEFAULT_LOG_DIR, LOG_CONFIG_FILE


SYS_EXCEPT_HOOK = sys.excepthook

def start(name="main", level=0, filename=""):
    # charge la configuration du logging depuis le fichier 'logging.yaml'
    with open(LOG_CONFIG_FILE, 'rt') as f:
        conf = yaml.load(f)

    if level:
        conf["loggers"][name]["level"] = level

    if not filename:
        filename = DEFAULT_LOG_DIR / r'{}.log'.format(name)
    conf["handlers"]["file"]["filename"] = filename

    conf["handlers"]["mail"]["fromaddr"] = conf["handlers"]["mail"]["fromaddr"].replace("%name%", name)
    conf["handlers"]["mail"]["subject"] = conf["handlers"]["mail"]["subject"].replace("%name%", name)

    logging.config.dictConfig(conf)

    logger = logging.getLogger(name)
    def _excepthook(typ, value, trace):
        """ Remplace la gestion d'erreur standard, pour logger aussi les erreurs non gérées """
        logger.error("{}\n{}\n{}".format(typ.__name__, value, ''.join(traceback.format_tb(trace))))
        SYS_EXCEPT_HOOK(typ, value, trace)
    sys.excepthook = _excepthook

