log.py 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # coding: utf-8
  2. import logging
  3. import sys
  4. import typing
  5. from synergine2.config import Config
  6. STREAM_HANDLER_TAG = '__STREAM_HANDLER__'
  7. class SynergineLogger(logging.getLoggerClass()):
  8. @property
  9. def is_debug(self) -> bool:
  10. return self.isEnabledFor(logging.DEBUG)
  11. def __getstate__(self):
  12. # Multiprocessing fail if stream handler present. Remove it if exist.
  13. # TODO Bug when want to store STREAM_HANDLER_TAG instead stream handler. str still in handlers after
  14. # __setstate__ ...
  15. self.handlers = []
  16. return self.__dict__.copy()
  17. def __setstate__(self, state):
  18. self.__dict__ = state
  19. # TODO: This handler is hardcoded, it must depend of real context
  20. self.handlers.append(logging.StreamHandler(sys.stdout))
  21. def get_default_logger(
  22. name: str='synergine',
  23. level: int=logging.ERROR,
  24. ) -> SynergineLogger:
  25. """
  26. WARNING: Set global logging Logger class to SynergineLogger
  27. """
  28. logging.setLoggerClass(SynergineLogger)
  29. logger = logging.getLogger(name)
  30. logger = typing.cast(SynergineLogger, logger)
  31. handler = logging.StreamHandler(sys.stdout)
  32. formatter = logging.Formatter(
  33. '%(asctime)s|%(name)s|%(process)d|%(levelname)s: %(message)s',
  34. )
  35. handler.setFormatter(formatter)
  36. logger.addHandler(handler)
  37. logger.setLevel(level)
  38. return logger
  39. def get_logger(name: str, config: Config) -> SynergineLogger:
  40. global_logging_level = config.resolve('global.logging_level', 'ERROR')
  41. logger_level_str = config.resolve('global.logger.{}.level', global_logging_level)
  42. logger_level = logging.getLevelName(logger_level_str)
  43. return get_default_logger('synergine-{}'.format(name), logger_level)