我有一个以下程序,如果数字为奇数,则引发异常,如果为偶数,则返回值。现在,如果超过最大重试次数,则将引发先前发生的异常。我想做的是,超过最大重试次数后,我想记录此异常。我有点困惑如何实现这一目标。 这是下面的代码:
import random
from celery import Celery
app = Celery('add', broker='redis://localhost:6379/0')
@app.task(bind=True)
def add(self, x, y):
# Get a random number between 1 and 10
num = random.randint(1, 10)
print num # To help properly understand output
try:
# If number is odd, fail the task
if num % 2:
raise Exception()
# If number is even, succeed the task
else:
return x + y
except Exception as e:
self.retry(countdown=2, exc=e, max_retries=1)
例外是
[2015-07-31 17:47:33,681: INFO/MainProcess] Received task: add.add[64e43f81-0f80-49ac-a068-4c84c689ea16]
[2015-07-31 17:47:33,681: WARNING/Worker-2] 7
[2015-07-31 17:47:33,703: INFO/MainProcess] Received task: add.add[64e43f81-0f80-49ac-a068-4c84c689ea16] eta:[2015-07-31 12:17:35.692557+00:00]
[2015-07-31 17:47:33,704: INFO/MainProcess] Task add.add[64e43f81-0f80-49ac-a068-4c84c689ea16] retry: Retry in 2s: Exception()
[2015-07-31 17:47:36,890: WARNING/Worker-4] 3
[2015-07-31 17:47:36,894: ERROR/MainProcess] Task add.add[64e43f81-0f80-49ac-a068-4c84c689ea16] raised unexpected: Exception()
Traceback (most recent call last):
File "/Users/akshar/.virtualenvs/hack/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
...
File "/Users/akshar/Play/Python/hack/add.py", line 15, in add
raise Exception()
Exception
我想以任何方式记录它,而不是引发Exception()。谢谢
答案 0 :(得分:0)
您可以在奇偶数之前添加if支票,并打印或保存日志。
import random
from celery import Celery
app = Celery('add', broker='redis://localhost:6379/0')
@app.task(bind=True)
def add(self, x, y):
# Get a random number between 1 and 10
num = random.randint(1, 10)
print num # To help properly understand output
try:
if max_retries!=1:# count of max_retry
# If number is odd, fail the task
if num % 2:
raise Exception()
# If number is even, succeed the task
else:
return x + y
else:
print "log the result"
except Exception as e:
self.retry(countdown=2, exc=e, max_retries=1)
您也可以在尝试结束时添加一个finally blok,除非在每种情况下它都会运行,并且您可以将所有日志保存在那里。