logging.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. # coding=utf-8
  2. # Copyright 2020 Optuna, Hugging Face
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Logging utilities."""
  16. import functools
  17. import logging
  18. import os
  19. import sys
  20. import threading
  21. from logging import (
  22. CRITICAL, # NOQA
  23. DEBUG, # NOQA
  24. ERROR, # NOQA
  25. FATAL, # NOQA
  26. INFO, # NOQA
  27. NOTSET, # NOQA
  28. WARN, # NOQA
  29. WARNING, # NOQA
  30. )
  31. from logging import captureWarnings as _captureWarnings
  32. from typing import Optional
  33. import huggingface_hub.utils as hf_hub_utils
  34. from tqdm import auto as tqdm_lib
  35. _lock = threading.Lock()
  36. _default_handler: Optional[logging.Handler] = None
  37. log_levels = {
  38. "detail": logging.DEBUG, # will also print filename and line number
  39. "debug": logging.DEBUG,
  40. "info": logging.INFO,
  41. "warning": logging.WARNING,
  42. "error": logging.ERROR,
  43. "critical": logging.CRITICAL,
  44. }
  45. _default_log_level = logging.WARNING
  46. _tqdm_active = not hf_hub_utils.are_progress_bars_disabled()
  47. def _get_default_logging_level():
  48. """
  49. If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is
  50. not - fall back to `_default_log_level`
  51. """
  52. env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None)
  53. if env_level_str:
  54. if env_level_str in log_levels:
  55. return log_levels[env_level_str]
  56. else:
  57. logging.getLogger().warning(
  58. f"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, "
  59. f"has to be one of: { ', '.join(log_levels.keys()) }"
  60. )
  61. return _default_log_level
  62. def _get_library_name() -> str:
  63. return __name__.split(".")[0]
  64. def _get_library_root_logger() -> logging.Logger:
  65. return logging.getLogger(_get_library_name())
  66. def _configure_library_root_logger() -> None:
  67. global _default_handler
  68. with _lock:
  69. if _default_handler:
  70. # This library has already configured the library root logger.
  71. return
  72. _default_handler = logging.StreamHandler() # Set sys.stderr as stream.
  73. # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176
  74. if sys.stderr is None:
  75. sys.stderr = open(os.devnull, "w")
  76. _default_handler.flush = sys.stderr.flush
  77. # Apply our default configuration to the library root logger.
  78. library_root_logger = _get_library_root_logger()
  79. library_root_logger.addHandler(_default_handler)
  80. library_root_logger.setLevel(_get_default_logging_level())
  81. # if logging level is debug, we add pathname and lineno to formatter for easy debugging
  82. if os.getenv("TRANSFORMERS_VERBOSITY", None) == "detail":
  83. formatter = logging.Formatter("[%(levelname)s|%(pathname)s:%(lineno)s] %(asctime)s >> %(message)s")
  84. _default_handler.setFormatter(formatter)
  85. library_root_logger.propagate = False
  86. def _reset_library_root_logger() -> None:
  87. global _default_handler
  88. with _lock:
  89. if not _default_handler:
  90. return
  91. library_root_logger = _get_library_root_logger()
  92. library_root_logger.removeHandler(_default_handler)
  93. library_root_logger.setLevel(logging.NOTSET)
  94. _default_handler = None
  95. def get_log_levels_dict():
  96. return log_levels
  97. def captureWarnings(capture):
  98. """
  99. Calls the `captureWarnings` method from the logging library to enable management of the warnings emitted by the
  100. `warnings` library.
  101. Read more about this method here:
  102. https://docs.python.org/3/library/logging.html#integration-with-the-warnings-module
  103. All warnings will be logged through the `py.warnings` logger.
  104. Careful: this method also adds a handler to this logger if it does not already have one, and updates the logging
  105. level of that logger to the library's root logger.
  106. """
  107. logger = get_logger("py.warnings")
  108. if not logger.handlers:
  109. logger.addHandler(_default_handler)
  110. logger.setLevel(_get_library_root_logger().level)
  111. _captureWarnings(capture)
  112. def get_logger(name: Optional[str] = None) -> logging.Logger:
  113. """
  114. Return a logger with the specified name.
  115. This function is not supposed to be directly accessed unless you are writing a custom transformers module.
  116. """
  117. if name is None:
  118. name = _get_library_name()
  119. _configure_library_root_logger()
  120. return logging.getLogger(name)
  121. def get_verbosity() -> int:
  122. """
  123. Return the current level for the 🤗 Transformers's root logger as an int.
  124. Returns:
  125. `int`: The logging level.
  126. <Tip>
  127. 🤗 Transformers has following logging levels:
  128. - 50: `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
  129. - 40: `transformers.logging.ERROR`
  130. - 30: `transformers.logging.WARNING` or `transformers.logging.WARN`
  131. - 20: `transformers.logging.INFO`
  132. - 10: `transformers.logging.DEBUG`
  133. </Tip>"""
  134. _configure_library_root_logger()
  135. return _get_library_root_logger().getEffectiveLevel()
  136. def set_verbosity(verbosity: int) -> None:
  137. """
  138. Set the verbosity level for the 🤗 Transformers's root logger.
  139. Args:
  140. verbosity (`int`):
  141. Logging level, e.g., one of:
  142. - `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
  143. - `transformers.logging.ERROR`
  144. - `transformers.logging.WARNING` or `transformers.logging.WARN`
  145. - `transformers.logging.INFO`
  146. - `transformers.logging.DEBUG`
  147. """
  148. _configure_library_root_logger()
  149. _get_library_root_logger().setLevel(verbosity)
  150. def set_verbosity_info():
  151. """Set the verbosity to the `INFO` level."""
  152. return set_verbosity(INFO)
  153. def set_verbosity_warning():
  154. """Set the verbosity to the `WARNING` level."""
  155. return set_verbosity(WARNING)
  156. def set_verbosity_debug():
  157. """Set the verbosity to the `DEBUG` level."""
  158. return set_verbosity(DEBUG)
  159. def set_verbosity_error():
  160. """Set the verbosity to the `ERROR` level."""
  161. return set_verbosity(ERROR)
  162. def disable_default_handler() -> None:
  163. """Disable the default handler of the HuggingFace Transformers's root logger."""
  164. _configure_library_root_logger()
  165. assert _default_handler is not None
  166. _get_library_root_logger().removeHandler(_default_handler)
  167. def enable_default_handler() -> None:
  168. """Enable the default handler of the HuggingFace Transformers's root logger."""
  169. _configure_library_root_logger()
  170. assert _default_handler is not None
  171. _get_library_root_logger().addHandler(_default_handler)
  172. def add_handler(handler: logging.Handler) -> None:
  173. """adds a handler to the HuggingFace Transformers's root logger."""
  174. _configure_library_root_logger()
  175. assert handler is not None
  176. _get_library_root_logger().addHandler(handler)
  177. def remove_handler(handler: logging.Handler) -> None:
  178. """removes given handler from the HuggingFace Transformers's root logger."""
  179. _configure_library_root_logger()
  180. assert handler is not None and handler not in _get_library_root_logger().handlers
  181. _get_library_root_logger().removeHandler(handler)
  182. def disable_propagation() -> None:
  183. """
  184. Disable propagation of the library log outputs. Note that log propagation is disabled by default.
  185. """
  186. _configure_library_root_logger()
  187. _get_library_root_logger().propagate = False
  188. def enable_propagation() -> None:
  189. """
  190. Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to
  191. prevent double logging if the root logger has been configured.
  192. """
  193. _configure_library_root_logger()
  194. _get_library_root_logger().propagate = True
  195. def enable_explicit_format() -> None:
  196. """
  197. Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows:
  198. ```
  199. [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE
  200. ```
  201. All handlers currently bound to the root logger are affected by this method.
  202. """
  203. handlers = _get_library_root_logger().handlers
  204. for handler in handlers:
  205. formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s")
  206. handler.setFormatter(formatter)
  207. def reset_format() -> None:
  208. """
  209. Resets the formatting for HuggingFace Transformers's loggers.
  210. All handlers currently bound to the root logger are affected by this method.
  211. """
  212. handlers = _get_library_root_logger().handlers
  213. for handler in handlers:
  214. handler.setFormatter(None)
  215. def warning_advice(self, *args, **kwargs):
  216. """
  217. This method is identical to `logger.warning()`, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this
  218. warning will not be printed
  219. """
  220. no_advisory_warnings = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS", False)
  221. if no_advisory_warnings:
  222. return
  223. self.warning(*args, **kwargs)
  224. logging.Logger.warning_advice = warning_advice
  225. @functools.lru_cache(None)
  226. def warning_once(self, *args, **kwargs):
  227. """
  228. This method is identical to `logger.warning()`, but will emit the warning with the same message only once
  229. Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
  230. The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
  231. another type of cache that includes the caller frame information in the hashing function.
  232. """
  233. self.warning(*args, **kwargs)
  234. logging.Logger.warning_once = warning_once
  235. @functools.lru_cache(None)
  236. def info_once(self, *args, **kwargs):
  237. """
  238. This method is identical to `logger.info()`, but will emit the info with the same message only once
  239. Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
  240. The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
  241. another type of cache that includes the caller frame information in the hashing function.
  242. """
  243. self.info(*args, **kwargs)
  244. logging.Logger.info_once = info_once
  245. class EmptyTqdm:
  246. """Dummy tqdm which doesn't do anything."""
  247. def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
  248. self._iterator = args[0] if args else None
  249. def __iter__(self):
  250. return iter(self._iterator)
  251. def __getattr__(self, _):
  252. """Return empty function."""
  253. def empty_fn(*args, **kwargs): # pylint: disable=unused-argument
  254. return
  255. return empty_fn
  256. def __enter__(self):
  257. return self
  258. def __exit__(self, type_, value, traceback):
  259. return
  260. class _tqdm_cls:
  261. def __call__(self, *args, **kwargs):
  262. if _tqdm_active:
  263. return tqdm_lib.tqdm(*args, **kwargs)
  264. else:
  265. return EmptyTqdm(*args, **kwargs)
  266. def set_lock(self, *args, **kwargs):
  267. self._lock = None
  268. if _tqdm_active:
  269. return tqdm_lib.tqdm.set_lock(*args, **kwargs)
  270. def get_lock(self):
  271. if _tqdm_active:
  272. return tqdm_lib.tqdm.get_lock()
  273. tqdm = _tqdm_cls()
  274. def is_progress_bar_enabled() -> bool:
  275. """Return a boolean indicating whether tqdm progress bars are enabled."""
  276. global _tqdm_active
  277. return bool(_tqdm_active)
  278. def enable_progress_bar():
  279. """Enable tqdm progress bar."""
  280. global _tqdm_active
  281. _tqdm_active = True
  282. hf_hub_utils.enable_progress_bars()
  283. def disable_progress_bar():
  284. """Disable tqdm progress bar."""
  285. global _tqdm_active
  286. _tqdm_active = False
  287. hf_hub_utils.disable_progress_bars()