before_sleep.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright 2016 Julien Danjou
  2. # Copyright 2016 Joshua Harlow
  3. # Copyright 2013-2014 Ray Holder
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import typing
  17. from tenacity import _utils
  18. if typing.TYPE_CHECKING:
  19. import logging
  20. from tenacity import RetryCallState
  21. def before_sleep_nothing(retry_state: "RetryCallState") -> None:
  22. """Before sleep strategy that does nothing."""
  23. def before_sleep_log(
  24. logger: "logging.Logger",
  25. log_level: int,
  26. exc_info: bool = False,
  27. ) -> typing.Callable[["RetryCallState"], None]:
  28. """Before sleep strategy that logs to some logger the attempt."""
  29. def log_it(retry_state: "RetryCallState") -> None:
  30. local_exc_info: BaseException | bool | None
  31. if retry_state.outcome is None:
  32. raise RuntimeError("log_it() called before outcome was set")
  33. if retry_state.next_action is None:
  34. raise RuntimeError("log_it() called before next_action was set")
  35. if retry_state.outcome.failed:
  36. ex = retry_state.outcome.exception()
  37. verb, value = "raised", f"{ex.__class__.__name__}: {ex}"
  38. if exc_info:
  39. local_exc_info = retry_state.outcome.exception()
  40. else:
  41. local_exc_info = False
  42. else:
  43. verb, value = "returned", retry_state.outcome.result()
  44. local_exc_info = False # exc_info does not apply when no exception
  45. if retry_state.fn is None:
  46. # NOTE(sileht): can't really happen, but we must please mypy
  47. fn_name = "<unknown>"
  48. else:
  49. fn_name = _utils.get_callback_name(retry_state.fn)
  50. logger.log(
  51. log_level,
  52. f"Retrying {fn_name} "
  53. f"in {retry_state.next_action.sleep} seconds as it {verb} {value}.",
  54. exc_info=local_exc_info,
  55. )
  56. return log_it