logger.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """
  2. Logging utility. Adapted from https://github.com/skypilot-org/skypilot/blob/master/sky/sky_logging.py
  3. """
  4. import logging
  5. import sys
  6. _FORMAT = "%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s"
  7. _DATE_FORMAT = "%m-%d %H:%M:%S"
  8. class NewLineFormatter(logging.Formatter):
  9. """Adds logging prefix to newlines to align multi-line messages."""
  10. def __init__(self, fmt, datefmt=None):
  11. logging.Formatter.__init__(self, fmt, datefmt)
  12. def format(self, record):
  13. msg = logging.Formatter.format(self, record)
  14. if record.message != "":
  15. parts = msg.split(record.message)
  16. msg = msg.replace('\n', '\r\n' + parts[0])
  17. return msg
  18. _root_logger = logging.getLogger('aphrodite')
  19. _default_handler = None
  20. def _setup_logger():
  21. _root_logger.setLevel(logging.DEBUG)
  22. global _default_handler
  23. if _default_handler is None:
  24. _default_handler = logging.StreamHandler(sys.stdout)
  25. _default_handler.flush = sys.stdout.flush # type: ignore
  26. _default_handler.setLevel(logging.INFO)
  27. _root_logger.addHandler(_default_handler)
  28. fmt = NewLineFormatter(_FORMAT, datefmt=_DATE_FORMAT)
  29. _default_handler.setFormatter(fmt)
  30. # Setting this will avoid the message
  31. # being propagated to the parent logger.
  32. _root_logger.propagate = False
  33. # The logger is initialized when the module is imported.
  34. # This is thread-safe as the module is only imported once,
  35. # guaranteed by the Python GIL.
  36. _setup_logger()
  37. def init_logger(name: str):
  38. return logging.getLogger(name)