logging_.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. '''
  2. @author: devone, 02-2020
  3. '''
  4. import logging.config
  5. import sys
  6. import traceback
  7. import yaml
  8. from path import Path
  9. HERE = Path(__file__).parent
  10. LOGDIR = HERE
  11. LOGCONF = HERE / 'logging.yml'
  12. SYS_EXCEPT_HOOK = sys.excepthook
  13. def start(name="main", level=0, filename="", replace=False):
  14. # charge la configuration du logging depuis le fichier 'logging.yaml'
  15. with open(LOGCONF, 'rt') as f:
  16. conf = yaml.load(f, Loader=yaml.FullLoader)
  17. if level:
  18. conf["loggers"][name]["level"] = level
  19. if not filename:
  20. filename = LOGDIR / r'{}.log'.format(name)
  21. if replace:
  22. filename.remove_p()
  23. conf["handlers"]["file"]["filename"] = filename
  24. logging.config.dictConfig(conf)
  25. logger = logging.getLogger(name)
  26. def _excepthook(typ, value, trace):
  27. """ Remplace la gestion d'erreur standard, pour logger aussi les erreurs non gérées """
  28. logger.error("{}\n{}\n{}".format(typ.__name__, value, ''.join(traceback.format_tb(trace))))
  29. SYS_EXCEPT_HOOK(typ, value, trace)
  30. sys.excepthook = _excepthook