tenacity icon indicating copy to clipboard operation
tenacity copied to clipboard

Logging while using Retrying as context manager prints calls to 'None'

Open czechnology opened this issue 4 years ago • 2 comments

When using the logging functions like before_log, after_log or before_sleep_log in a Retrying instance as a context manager, it prints messages like call to 'None' or Retrying None.

Example code:

import logging
import sys

from tenacity import (
    RetryError,
    Retrying,
    after_log,
    before_log,
    before_sleep_log,
    retry,
    retry_if_exception,
    stop_after_attempt,
    wait_fixed,
)

logging.basicConfig(level=logging.DEBUG, format="%(message)s", stream=sys.stdout)


@retry(
    before=before_log(logging, logging.DEBUG),
    after=after_log(logging, logging.DEBUG),
    before_sleep=before_sleep_log(logging, logging.DEBUG),
    stop=stop_after_attempt(2),
)
def fail():
    raise RuntimeError()


def main():
    print("# @retry decorator")
    try:
        fail()
    except RetryError:
        pass

    print("\n# Retrying context manager")
    try:
        for attempt in Retrying(
            before=before_log(logging, logging.DEBUG),
            after=after_log(logging, logging.DEBUG),
            before_sleep=before_sleep_log(logging, logging.DEBUG),
            stop=stop_after_attempt(2),
        ):
            with attempt:
                raise RuntimeError()
    except RetryError:
        pass


if __name__ == "__main__":
    main()

Output:

# @retry decorator
Starting call to '__main__.fail', this is the 1st time calling it.
Finished call to '__main__.fail' after 0.000(s), this was the 1st time calling it.
Retrying __main__.fail in 0.0 seconds as it raised RuntimeError: .
Starting call to '__main__.fail', this is the 2nd time calling it.
Finished call to '__main__.fail' after 0.001(s), this was the 2nd time calling it.

# Retrying context manager
Starting call to 'None', this is the 1st time calling it.
Finished call to 'None' after 0.000(s), this was the 1st time calling it.
Retrying None in 0.0 seconds as it raised RuntimeError: .
Starting call to 'None', this is the 2nd time calling it.
Finished call to 'None' after 0.001(s), this was the 2nd time calling it.

czechnology avatar Oct 20 '21 11:10 czechnology

Same thing with AsyncRetrying

FyZzyss avatar Nov 11 '21 13:11 FyZzyss

I think that it is reasonable, because when you use Retrying context manager, the Retrying is working on code block, there are no function, so the function name is None

xingdongzhe avatar Apr 05 '22 06:04 xingdongzhe