logging.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """
  2. Copyright (c) Contributors to the Open 3D Engine Project.
  3. For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. SPDX-License-Identifier: Apache-2.0 OR MIT
  5. Standardized logging util file for metrics scripts
  6. """
  7. import enum
  8. import logging
  9. import sys
  10. class Level(enum.IntEnum):
  11. """
  12. Enum reference for default log values
  13. """
  14. CRITICAL = 50
  15. ERROR = 40
  16. WARNING = 30
  17. INFO = 20
  18. DEBUG = 10
  19. NOTSET = 0
  20. class Formatter(logging.Formatter):
  21. """
  22. Standardized log formatting for scripts.
  23. """
  24. def __init__(self):
  25. super().__init__("%(asctime)s %(name)-40s %(message)s")
  26. def format(self, record):
  27. return "{} {}".format(Formatter.get_level_acronym(record.levelno), super().format(record))
  28. @classmethod
  29. def get_level_acronym(cls, level: int):
  30. """
  31. Returns the corresponding log letter for formatting.
  32. :param level: The log level enum
  33. :return: The letter of the log level
  34. """
  35. if level == Level.CRITICAL:
  36. return "C"
  37. elif level == Level.ERROR:
  38. return "E"
  39. elif level == Level.WARNING:
  40. return "W"
  41. elif level == Level.INFO:
  42. return "I"
  43. elif level == Level.DEBUG:
  44. return "D"
  45. else:
  46. return f"({level})"
  47. def get_logger(name=None):
  48. """
  49. Wrapper function
  50. """
  51. return logging.getLogger(name)
  52. def setup_logger(logger, min_level=Level.INFO):
  53. """
  54. Standardized logging setup.
  55. :param logger: The logger object
  56. :param min_level: Minimum level of logging to be set
  57. :return: None
  58. """
  59. formatter = Formatter()
  60. out_handler = logging.StreamHandler(sys.stdout)
  61. out_handler.setLevel(Level.DEBUG)
  62. out_handler.addFilter(lambda record: record.levelno < Level.ERROR)
  63. out_handler.setFormatter(formatter)
  64. err_handler = logging.StreamHandler(sys.stderr)
  65. err_handler.setLevel(Level.ERROR)
  66. err_handler.setFormatter(formatter)
  67. logger.setLevel(min_level)
  68. logger.addHandler(out_handler)
  69. logger.addHandler(err_handler)