logger.py 2.4 KB

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