Skip to content

Adds add_callback/add_errback example to docs #1441

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 29, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,18 @@ KafkaProducer
for _ in range(100):
producer.send('my-topic', b'msg')

def on_send_success(record_metadata):
print(record_metadata.topic)
print(record_metadata.partition)
print(record_metadata.offset)

def on_send_error(excp):
log.exception()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just doublechecking, since I'm not sure how this works:
Is the send exception always going to be the most recent one raised? If you screwed up your callback somehow and threw an exception, it would hide the send exception.

Perhaps it'd be better to illustrate how to pass the excp into log.error()? This is honestly less of a kafka-python thing, and more just showing clearly how python logging works, as we often get questions on the issue tracker about that as well...

Just a thought, I do not have a strong opinion, and I am not even 100% sure how this works in this particular example as I haven't played with it...

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree -- log.exception() may not always work here because we don't guarantee that the errback is evaluated within the context of a exception handler. It would be better to pass the exception explicitly:

def on_send_error(excp):
    log.error('I am an errback', exc_info=excp)

# handle exception

# produce asynchronously with callbacks
producer.send('my-topic', b'raw_bytes').add_callback(on_send_success).add_errback(on_send_error)

# block until all async messages are sent
producer.flush()

Expand Down