Calmcode - stamina: logging

Telemtry for Retries

1 2 3 4

You may consider using stamina inside of a batch script. Something that runs on a daily basis that you don't want to fail. The retry mechanic will be a great fit, but you'd probably also want to have some logging around for that. If a retry is triggered frequently, you'd like to be able to track that via the logs. So let's talk about how you might be able to customise that.

import random
import stamina


def log_retry(retry_details: stamina.instrumentation.RetryDetails):
    print(f"Retry attempt #{retry_details.retry_num}. Waited sofar={retry_details.waited_so_far}")
    print(f"{retry_details.args=} {retry_details.kwargs=}")

stamina.instrumentation.set_on_retry_hooks([log_retry])

@stamina.retry(on=ValueError, attempts=7)
def run(i):
    if random.random() < 0.5:
        raise ValueError("oh no")
    return i

for i in range(10): 
    run(i)

In this example we've added a log_retry function that is triggered every time that the retry-mechanic is triggered. It receives a RetryDetails object that has information that you may be interested in logging. The log_retry function is configured via the stamina.instrumentation.set_on_retry_hooks call. That means that you could also add extra functions if you'd like.

The main thing thats important here is that you want to take the time to think about how you might want to be notified about these retries. If a retry happens once in a while it's probably fine, but if there's a spike it would be nice to have some telemetry.