logging.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import functools
  15. import inspect
  16. import logging
  17. import sys
  18. import colorlog
  19. from .flags import DEBUG
  20. __all__ = ["debug", "info", "warning", "error", "critical", "setup_logging"]
  21. LOGGER_NAME = "paddlex"
  22. _LOG_CONFIG = {
  23. "DEBUG": {"color": "purple"},
  24. "INFO": {"color": "green"},
  25. "WARNING": {"color": "yellow"},
  26. "ERROR": {"color": "red"},
  27. "CRITICAL": {"color": "bold_red"},
  28. }
  29. _logger = logging.getLogger(LOGGER_NAME)
  30. def debug(msg, *args, **kwargs):
  31. """debug"""
  32. if DEBUG:
  33. frame = inspect.currentframe()
  34. caller_frame = frame.f_back
  35. caller_func_name = caller_frame.f_code.co_name
  36. if "self" in caller_frame.f_locals:
  37. caller_class_name = caller_frame.f_locals["self"].__class__.__name__
  38. elif "cls" in caller_frame.f_locals:
  39. caller_class_name = caller_frame.f_locals["cls"].__name__
  40. else:
  41. caller_class_name = None
  42. if caller_class_name:
  43. caller_info = f"{caller_class_name}::{caller_func_name}"
  44. else:
  45. caller_info = f"{caller_func_name}"
  46. msg = f"【{caller_info}】{msg}"
  47. _logger.debug(msg, *args, **kwargs)
  48. def info(msg, *args, **kwargs):
  49. """info"""
  50. _logger.info(msg, *args, **kwargs)
  51. def warning(msg, *args, **kwargs):
  52. """warning"""
  53. _logger.warning(msg, *args, **kwargs)
  54. @functools.lru_cache(None)
  55. def warning_once(msg, *args, **kwargs):
  56. """
  57. This method is identical to `logger.warning()`, but will emit the warning with the same message only once
  58. """
  59. warning(msg, *args, **kwargs)
  60. def error(msg, *args, **kwargs):
  61. """error"""
  62. _logger.error(msg, *args, **kwargs)
  63. def critical(msg, *args, **kwargs):
  64. """critical"""
  65. _logger.critical(msg, *args, **kwargs)
  66. def exception(msg, *args, **kwargs):
  67. """exception"""
  68. _logger.exception(msg, *args, **kwargs)
  69. def setup_logging(verbosity: str = None):
  70. """setup logging level
  71. Args:
  72. verbosity (str, optional): the logging level, `DEBUG`, `INFO`, `WARNING`. Defaults to None.
  73. """
  74. if verbosity is None:
  75. if DEBUG:
  76. verbosity = "DEBUG"
  77. else:
  78. verbosity = "INFO"
  79. if verbosity is not None:
  80. _configure_logger(_logger, verbosity.upper())
  81. def _configure_logger(logger, verbosity):
  82. """_configure_logger"""
  83. if verbosity == "DEBUG":
  84. _logger.setLevel(logging.DEBUG)
  85. elif verbosity == "INFO":
  86. _logger.setLevel(logging.INFO)
  87. elif verbosity == "WARNING":
  88. _logger.setLevel(logging.WARNING)
  89. logger.propagate = False
  90. if not logger.hasHandlers():
  91. _add_handler(logger)
  92. def _add_handler(logger):
  93. """_add_handler"""
  94. format = colorlog.ColoredFormatter(
  95. "%(log_color)s%(message)s",
  96. log_colors={key: conf["color"] for key, conf in _LOG_CONFIG.items()},
  97. )
  98. handler = logging.StreamHandler(sys.stderr)
  99. handler.setFormatter(format)
  100. logger.addHandler(handler)
  101. def advertise():
  102. """
  103. Show the advertising message like the following:
  104. ===========================================================
  105. == PaddleX is powered by PaddlePaddle ! ==
  106. ===========================================================
  107. == ==
  108. == For more info please go to the following website. ==
  109. == ==
  110. == https://github.com/PaddlePaddle/PaddleX ==
  111. ===========================================================
  112. """
  113. copyright = "PaddleX is powered by PaddlePaddle !"
  114. ad = "For more info please go to the following website."
  115. website = "https://github.com/PaddlePaddle/PaddleX"
  116. AD_LEN = 6 + len(max([copyright, ad, website], key=len))
  117. info(
  118. "\n{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n".format(
  119. "=" * (AD_LEN + 4),
  120. "=={}==".format(copyright.center(AD_LEN)),
  121. "=" * (AD_LEN + 4),
  122. "=={}==".format(" " * AD_LEN),
  123. "=={}==".format(ad.center(AD_LEN)),
  124. "=={}==".format(" " * AD_LEN),
  125. "=={}==".format(website.center(AD_LEN)),
  126. "=" * (AD_LEN + 4),
  127. )
  128. )