logger.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. _FORMAT = "%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s"
  8. _DATE_FORMAT = "%m-%d %H:%M:%S"
  9. class NewLineFormatter(logging.Formatter):
  10. """Adds logging prefix to newlines to align multi-line messages."""
  11. def __init__(self, fmt, datefmt=None):
  12. logging.Formatter.__init__(self, fmt, datefmt)
  13. def format(self, record):
  14. msg = logging.Formatter.format(self, record)
  15. if record.message != "":
  16. parts = msg.split(record.message)
  17. msg = msg.replace("\n", "\r\n" + parts[0])
  18. return msg
  19. _root_logger = logging.getLogger("aphrodite")
  20. _default_handler = None
  21. def _setup_logger():
  22. _root_logger.setLevel(logging.DEBUG)
  23. global _default_handler
  24. if _default_handler is None:
  25. _default_handler = logging.StreamHandler(sys.stdout)
  26. _default_handler.flush = sys.stdout.flush # type: ignore
  27. _default_handler.setLevel(logging.INFO)
  28. _root_logger.addHandler(_default_handler)
  29. fmt = NewLineFormatter(_FORMAT, datefmt=_DATE_FORMAT)
  30. _default_handler.setFormatter(fmt)
  31. # Setting this will avoid the message
  32. # being propagated to the parent logger.
  33. _root_logger.propagate = False
  34. # The logger is initialized when the module is imported.
  35. # This is thread-safe as the module is only imported once,
  36. # guaranteed by the Python GIL.
  37. _setup_logger()
  38. def init_logger(name: str):
  39. logger = logging.getLogger(name)
  40. logger.setLevel(logging.DEBUG)
  41. logger.addHandler(_default_handler)
  42. logger.propagate = False
  43. return logger