On this page

Logging for Python-Asyncio SDK

This page explains how to enable logging and handle errors in the PubNub Python-Asyncio Software Development Kit (SDK). Start by enabling basic logs, then learn two error-handling patterns: future() and result().

How to enable logging

1import os
2import asyncio
3import logging
4from pubnub.pnconfiguration import PNConfiguration
5from pubnub.pubnub_asyncio import PubNubAsyncio
6from pubnub.exceptions import PubNubException
7
8
9async def demonstrate_logging(pubnub: PubNubAsyncio):
10 try:
11 # This operation will generate logs we can observe
12 envelope = await pubnub.publish() \
13 .channel("my_channel") \
14 .message({'name': 'Alex', 'action': 'logging_demo'}) \
15 .future()
show all 48 lines

To see how logging integrates with subscription operations, refer to the subscribe example. The example sets a stream logger at the DEBUG level and subscribes to a channel using a listener.

Error handling with future()

For future() calls, errors are wrapped in either AsyncioEnvelope or PubNubAsyncioException. Both expose two fields:

  • e.result: The request result object if the operation succeeds; otherwise None.
  • e.status: A PNStatus object with details about the finished request. Use the e.is_error() helper to determine success or failure.

Future() usage

1import asyncio
2import os
3from pubnub.pnconfiguration import PNConfiguration
4from pubnub.pubnub_asyncio import PubNubAsyncio
5from pubnub.exceptions import PubNubException
6
7
8async def publish_future(pubnub: PubNubAsyncio):
9 try:
10 envelope = await pubnub.publish().channel("my_channel").message("hello!").future()
11 if envelope.status.is_error():
12 print(f"Error: {envelope.status.error_data}")
13 print(f"Error category #{envelope.status.category}")
14 return
15 else:
show all 41 lines

Error handling with result()

result() returns only the request result, without state information. Catch errors with try/except. For server-side errors, the e.status field provides additional information about the request:

1import asyncio
2import os
3from pubnub.pnconfiguration import PNConfiguration
4from pubnub.pubnub_asyncio import PubNubAsyncio
5from pubnub.exceptions import PubNubException
6
7
8async def publish_result(pubnub: PubNubAsyncio):
9 try:
10 result = await pubnub.publish().channel("my_channel").message("hello!").result()
11 print(f"Publish successful: {result}")
12 except PubNubException as e:
13 print(f"Error: {e}")
14 if e.status is not None:
15 print(f"Error category #{e.status.category}")
show all 38 lines
Last updated on