【问题标题】:How to get log of every retry attempt made by Python Requests Library?如何获取 Python Requests Library 每次重试尝试的日志?
【发布时间】:2021-06-07 13:19:28
【问题描述】:

我正在使用以下代码在 python 请求中实现重试机制。

from requests import Session
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

s = Session()
retries = Retry(total=5,
                raise_on_redirect=True, 
                raise_on_status=True,
                backoff_factor=1,
                status_forcelist=[ 500, 502, 503, 504 ])
s.mount('http://', HTTPAdapter(max_retries=retries))
s.mount('https://', HTTPAdapter(max_retries=retries))
response=s.get('https://example.com')

它运行良好,但是这一切都在悄无声息地发生。 我想要的是在进行重试时得到通知,如果可能的话,为什么会发生重试。每次重试时我都想要这样的东西。

print(Exception.__class__)
print('Retrying after' + x + 'seconds')

有可能吗?

【问题讨论】:

    标签: python python-requests urllib3


    【解决方案1】:

    您可以编写自己的 Class 来添加应该从 Retry 继承的日志。

    class LogRetry(Retry):
      """
         Adding extra logs before making a retry request     
      """      
      def __init__(self, *args, **kwargs):
        logger.info(f'<add your logs here>')
        super().__init__(*args, **kwargs)
    
    retries = LogRetry(<your args>)
    

    【讨论】:

      猜你喜欢
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 2017-12-29
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      相关资源
      最近更新 更多