logging.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. import logging
  3. _logger = logging.getLogger('nls')
  4. try:
  5. from logging import NullHandler
  6. except ImportError:
  7. class NullHandler(logging.Handler):
  8. def emit(self, record):
  9. pass
  10. _logger.addHandler(NullHandler())
  11. _traceEnabled = False
  12. __LOG_FORMAT__ = '%(asctime)s - %(levelname)s - %(message)s'
  13. __all__=['enableTrace', 'dump', 'error', 'warning', 'debug', 'trace',
  14. 'isEnabledForError', 'isEnabledForDebug', 'isEnabledForTrace']
  15. def enableTrace(traceable, handler=logging.StreamHandler()):
  16. """
  17. enable log print
  18. Parameters
  19. ----------
  20. traceable: bool
  21. whether enable log print, default log level is logging.DEBUG
  22. handler: Handler object
  23. handle how to print out log, default to stdio
  24. """
  25. global _traceEnabled
  26. _traceEnabled = traceable
  27. if traceable:
  28. _logger.addHandler(handler)
  29. _logger.setLevel(logging.DEBUG)
  30. handler.setFormatter(logging.Formatter(__LOG_FORMAT__))
  31. def dump(title, message):
  32. if _traceEnabled:
  33. _logger.debug('### ' + title + ' ###')
  34. _logger.debug(message)
  35. _logger.debug('########################################')
  36. def error(msg):
  37. _logger.error(msg)
  38. def warning(msg):
  39. _logger.warning(msg)
  40. def debug(msg):
  41. _logger.debug(msg)
  42. def trace(msg):
  43. if _traceEnabled:
  44. _logger.debug(msg)
  45. def isEnabledForError():
  46. return _logger.isEnabledFor(logging.ERROR)
  47. def isEnabledForDebug():
  48. return _logger.isEnabledFor(logging.Debug)
  49. def isEnabledForTrace():
  50. return _traceEnabled