Skip to content

Commit

Permalink
fix: correctly setup logging (#215)
Browse files Browse the repository at this point in the history
  • Loading branch information
grdsdev authored Oct 1, 2024
1 parent 7734890 commit f9eb04c
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 15 deletions.
5 changes: 5 additions & 0 deletions realtime/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import logging

# Configure the root logger for the module
logging.getLogger(__name__).addHandler(logging.NullHandler())

from realtime.version import __version__

from ._async.channel import AsyncRealtimeChannel
Expand Down
10 changes: 6 additions & 4 deletions realtime/_async/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
if TYPE_CHECKING:
from .client import AsyncRealtimeClient

logger = logging.getLogger(__name__)


class AsyncRealtimeChannel:
"""
Expand Down Expand Up @@ -83,7 +85,7 @@ def on_join_push_timeout(*args):
if not self.is_joining:
return

logging.error(f"join push timeout for channel {self.topic}")
logger.error(f"join push timeout for channel {self.topic}")
self.state = ChannelStates.ERRORED
self.rejoin_timer.schedule_timeout()

Expand All @@ -92,7 +94,7 @@ def on_join_push_timeout(*args):
)

def on_close(*args):
logging.info(f"channel {self.topic} closed")
logger.info(f"channel {self.topic} closed")
self.rejoin_timer.reset()
self.state = ChannelStates.CLOSED
self.socket.remove_channel(self)
Expand All @@ -101,7 +103,7 @@ def on_error(payload, *args):
if self.is_leaving or self.is_closed:
return

logging.info(f"channel {self.topic} error: {payload}")
logger.info(f"channel {self.topic} error: {payload}")
self.state = ChannelStates.ERRORED
self.rejoin_timer.schedule_timeout()

Expand Down Expand Up @@ -253,7 +255,7 @@ async def unsubscribe(self):
self.join_push.destroy()

def _close(*args):
logging.info(f"channel {self.topic} leave")
logger.info(f"channel {self.topic} leave")
self._trigger(ChannelEvents.close, "leave")

leave_push = AsyncPush(self, ChannelEvents.leave, {})
Expand Down
2 changes: 1 addition & 1 deletion realtime/_async/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ async def send(self, message: Dict[str, Any]) -> None:
"""

message = json.dumps(message)
logging.info(f"send: {message}")
logger.info(f"send: {message}")

async def send_message():
await self.ws_connection.send(message)
Expand Down
3 changes: 3 additions & 0 deletions realtime/_async/presence.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Defines the RealtimePresence class and its dependencies.
"""

import logging
from typing import Any, Callable, Dict, List, Optional, Union

from ..types import (
Expand All @@ -15,6 +16,8 @@
RealtimePresenceState,
)

logger = logging.getLogger(__name__)


class AsyncRealtimePresence:
def __init__(self, channel, opts: Optional[PresenceOpts] = None):
Expand Down
4 changes: 3 additions & 1 deletion realtime/_async/push.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
if TYPE_CHECKING:
from .channel import AsyncRealtimeChannel

logger = logging.getLogger(__name__)


class AsyncPush:
def __init__(
Expand Down Expand Up @@ -53,7 +55,7 @@ async def send(self):
}
)
except Exception as e:
logging.error(f"send push failed: {e}")
logger.error(f"send push failed: {e}")

def update_payload(self, payload: Dict[str, Any]):
self.payload = {**self.payload, **payload}
Expand Down
32 changes: 23 additions & 9 deletions realtime/_async/timer.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,40 @@
import asyncio
from typing import Callable
import logging
from typing import Callable, Optional

logger = logging.getLogger(__name__)


class AsyncTimer:
def __init__(self, callback: Callable, timer_calc: Callable[[int], int]):
self.callback = callback
self.timer_calc = timer_calc
self.timer = None
self.tries = 0
self.timer: Optional[asyncio.Task] = None
self.tries: int = 0

def reset(self):
self.tries = 0
if self.timer:
if self.timer and not self.timer.done():
self.timer.cancel()
self.timer = None
logger.debug(
"AsyncTimer has been reset and any scheduler tasks have been cancelled"
)

def schedule_timeout(self):
if self.timer:
self.timer.cancel()

self.timer = asyncio.create_task(self._run_timer())

async def _run_timer(self):
await asyncio.sleep(self.timer_calc(self.tries + 1))
self.tries += 1
await self.callback()
delay = self.timer_calc(self.tries + 1)
logger.debug(f"Scheduling callback to run after {delay} seconds.")
self.timer = asyncio.create_task(self._run_timer(delay))

async def _run_timer(self, delay: float):
try:
await asyncio.sleep(delay)
await self.callback()
except asyncio.CancelledError:
logger.debug("AsyncTimer task was cancelled.")
except Exception as e:
logger.exception(f"Error in AsyncTimer callback: {e}")

0 comments on commit f9eb04c

Please sign in to comment.