/py/ch2/lib/log.py

https://github.com/andrewcooke/choochoo · Python · 68 lines · 56 code · 12 blank · 0 comment · 14 complexity · 4a0f806fc1e3b227d52c2a3a404b2b1a MD5 · raw file

  1. from contextlib import contextmanager
  2. from logging import getLogger, DEBUG, INFO, WARNING
  3. from os.path import join
  4. from ..commands.args import LOG_DIR
  5. from ..common.log import configure_log, log_current_exception, set_log_color
  6. from ..common.names import UNDEF, COLOR
  7. log = getLogger(__name__)
  8. def make_log_from_args(args):
  9. from ..commands.args import LOG, COMMAND, VERBOSITY, PROGNAME, DEV
  10. name = args[LOG] if LOG in args and args[LOG] else (
  11. (args[COMMAND] if COMMAND in args and args[COMMAND] else PROGNAME) + f'.{LOG}')
  12. path = join(args._format_path(LOG_DIR), name)
  13. if args[VERBOSITY] is UNDEF:
  14. verbosity = 5 if args[DEV] else 4
  15. else:
  16. verbosity = args[VERBOSITY]
  17. configure_log('ch2', path, verbosity, {
  18. 'bokeh': DEBUG,
  19. 'ch2': DEBUG,
  20. 'jupyter': DEBUG,
  21. 'matplotlib': DEBUG,
  22. 'sentinelsat': DEBUG,
  23. 'sqlalchemy': WARNING,
  24. 'tornado': DEBUG,
  25. 'werkzeug': DEBUG,
  26. '__main__': DEBUG
  27. })
  28. set_log_color(args[COLOR])
  29. log.info(f'Logging to {path}')
  30. class Record:
  31. def __init__(self, log):
  32. self._log = log
  33. self._warning = []
  34. self._info = []
  35. def warning(self, msg):
  36. self._log.warning(msg)
  37. self._warning.append(msg)
  38. def info(self, msg):
  39. self._log.info(msg)
  40. self._info.append(msg)
  41. def raise_(self, msg):
  42. self.warning(msg)
  43. raise Exception(msg)
  44. @contextmanager
  45. def record_exceptions(self, catch=False):
  46. try:
  47. yield
  48. except Exception as e:
  49. self.warning(e)
  50. if catch:
  51. log_current_exception()
  52. else:
  53. raise
  54. def json(self):
  55. return {'warning': self._warning,
  56. 'info': self._info}