logging.py 13 KB

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