0
0

More than 1 year has passed since last update.

backoff: リトライをギブアップしたときに出力されるログメッセージのレベルを変える

Last updated at Posted at 2022-01-08

環境

  • Python 3.9.7
  • backoff 1.11.1

はじめに

backoffモジュールを使って、webapiへのアクセスのリトライ処理を実装しています。

bar.py
import backoff
import requests
import logging

@backoff.on_exception(
    wait_gen=backoff.expo, exception=requests.exceptions.RequestException, max_tries=3
)
def get_url(url):
    res = requests.get(url)
    res.raise_for_status()
    return res


def main():
    logging.basicConfig()
    get_url("https://httpbin.org/status/500")


if __name__ == "__main__":
    main()
$ python bar.py
INFO:backoff:Backing off get_url(...) for 0.3s (requests.exceptions.HTTPError: 500 Server Error: INTERNAL SERVER ERROR for url: https://httpbin.org/status/500)
INFO:backoff:Backing off get_url(...) for 0.6s (requests.exceptions.HTTPError: 500 Server Error: INTERNAL SERVER ERROR for url: https://httpbin.org/status/500)
ERROR:backoff:Giving up get_url(...) after 3 tries (requests.exceptions.HTTPError: 500 Server Error: INTERNAL SERVER ERROR for url: https://httpbin.org/status/500)

リトライしたとき(backing off)はINFOレベル、リトライをギブアップしたとき(giving up)はERRORレベルのログが出力されます。

リトライをギブアップしたときのログレベルを変える

リトライをギブアップしたときのログレベルがERRORなのは、ツールによってはログレベルが高すぎる場合があります。
そのようなときは、on_exception関数のgiveup_log_level引数に、適切なログレベルを指定しましょう。

@backoff.on_exception(
    wait_gen=backoff.expo,
    exception=requests.exceptions.RequestException,
    max_tries=3,
    giveup_log_level=logging.INFO,
)

なお、リトライしたときのログレベルはbackoff_log_levelで指定できます。

giveup_log_level, backoff_log_levelに関する説明は、backoffのREADMEには書かれていなかったので、Qiitaに投稿することにしました。
各引数の説明は、ソースコードのコメントを参照してください。
https://github.com/litl/backoff/blob/c2f4e1826b1996348177215f4c009c055777603f/backoff/_decorator.py#L77

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0