logger.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """
  2. Logging utility. Adapted from
  3. https://github.com/skypilot-org/skypilot/blob/master/sky/sky_logging.py
  4. """
  5. import logging
  6. import sys
  7. import colorlog
  8. # pylint: disable=line-too-long
  9. _FORMAT = "%(log_color)s%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s"
  10. _DATE_FORMAT = "%m-%d %H:%M:%S"
  11. class ColoredFormatter(colorlog.ColoredFormatter):
  12. """Adds logging prefix to newlines to align multi-line messages."""
  13. def __init__(self,
  14. fmt,
  15. datefmt=None,
  16. log_colors=None,
  17. reset=True,
  18. style="%"):
  19. super().__init__(fmt,
  20. datefmt=datefmt,
  21. log_colors=log_colors,
  22. reset=reset,
  23. style=style)
  24. def format(self, record):
  25. msg = super().format(record)
  26. if record.message != "":
  27. parts = msg.split(record.message)
  28. msg = msg.replace("\n", "\r\n" + parts[0])
  29. return msg
  30. _root_logger = logging.getLogger("aphrodite")
  31. _default_handler = None
  32. def _setup_logger():
  33. _root_logger.setLevel(logging.DEBUG)
  34. global _default_handler
  35. if _default_handler is None:
  36. _default_handler = logging.StreamHandler(sys.stdout)
  37. _default_handler.flush = sys.stdout.flush # type: ignore
  38. _default_handler.setLevel(logging.INFO)
  39. _root_logger.addHandler(_default_handler)
  40. fmt = ColoredFormatter(_FORMAT,
  41. datefmt=_DATE_FORMAT,
  42. log_colors={
  43. "DEBUG": "cyan",
  44. "INFO": "green",
  45. "WARNING": "yellow",
  46. "ERROR": "red",
  47. "CRITICAL": "red,bg_white",
  48. },
  49. reset=True)
  50. _default_handler.setFormatter(fmt)
  51. # Setting this will avoid the message
  52. # being propagated to the parent logger.
  53. _root_logger.propagate = False
  54. # The logger is initialized when the module is imported.
  55. # This is thread-safe as the module is only imported once,
  56. # guaranteed by the Python GIL.
  57. _setup_logger()
  58. def init_logger(name: str):
  59. logger = logging.getLogger(name)
  60. logger.setLevel(logging.DEBUG)
  61. logger.addHandler(_default_handler)
  62. logger.propagate = False
  63. return logger