Skip to content

Commit

Permalink
Log repr of incoming message only in debug mode (#80)
Browse files Browse the repository at this point in the history
Resolved #74.
  • Loading branch information
atugushev committed Nov 4, 2022
1 parent d796a39 commit 42cd062
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 23 deletions.
7 changes: 4 additions & 3 deletions ansq/tcp/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
)
from ansq.tcp.types import TCPConnection as NSQConnectionBase
from ansq.typedefs import TCPResponse
from ansq.utils import truncate_text, validate_topic_channel_name
from ansq.utils import validate_topic_channel_name

# Auto reconnect settings
AUTO_RECONNECT_INITIAL_INTERVAL = 2
Expand Down Expand Up @@ -402,7 +402,8 @@ async def _parse_data(self) -> bool:
await self._pulse()
return True

self.logger.debug("NSQ: Got data: %s", truncate_text(str(response)))
if self._debug:
self.logger.debug("NSQ: Got data: %s", response)

if response.is_message:
assert isinstance(response, NSQMessageSchema)
Expand All @@ -420,7 +421,7 @@ async def _parse_data(self) -> bool:
# non-error responses must have a command waiter, otherwise,
# it's more likely a bug
if not self._cmd_waiters: # pragma: no cover
self.logger.error("Unexpected response: %s", truncate_text(response.text))
self.logger.error("Unexpected response: %s", response)
return False

future, callback = self._cmd_waiters.popleft()
Expand Down
13 changes: 8 additions & 5 deletions ansq/tcp/types/response_schemas.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import Union

from ...utils import truncate
from . import FrameType, NSQCommands


Expand All @@ -16,8 +17,9 @@ def __init__(self, body: bytes, frame_type: Union[FrameType, int]) -> None:
)

def __repr__(self) -> str:
return "<NSQResponseSchema frame_type:{}, body:{!r}, is_ok:{}>".format(
self.frame_type, self.body, self.is_ok
return (
f"<NSQResponseSchema frame_type:{self.frame_type},"
f" body:{truncate(self.body)!r}, is_ok:{self.is_ok}>"
)

def __bool__(self) -> bool:
Expand Down Expand Up @@ -70,9 +72,10 @@ def __init__(

def __repr__(self) -> str:
return (
"<NSQMessageSchema frame_type:{}, body:{!r}, timestamp:{}, "
"attempts:{}, id:{}>"
).format(self.frame_type, self.body, self.timestamp, self.attempts, self.id)
f"<NSQMessageSchema frame_type:{self.frame_type},"
f" body:{truncate(self.body)!r}, timestamp:{self.timestamp},"
f" attempts:{self.attempts}, id:{self.id}>"
)


class NSQErrorSchema(NSQResponseSchema):
Expand Down
9 changes: 6 additions & 3 deletions ansq/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,12 @@ def get_logger(
return logger


def truncate_text(text: str, limit: int = 256) -> str:
"""Truncate a given `text` if the `limit` is reached"""
def truncate(data: bytes, limit: int = 256) -> bytes:
"""Truncate a given `data` if the `limit` is reached"""
if limit <= 0:
raise ValueError("limit must be greater than 0")

return text[:limit] + "..." if len(text) > limit else text
if len(data) <= limit:
return data

return data[:limit] + b"..."
26 changes: 14 additions & 12 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
import pytest

from ansq.utils import truncate_text
from ansq.utils import truncate


@pytest.mark.parametrize(
"text, limit, expected",
(
pytest.param("0123456789", 11, "0123456789", id="no trunc, greater than limit"),
pytest.param("0123456789", 10, "0123456789", id="no trunc, equal limit"),
pytest.param("0123456789", 9, "012345678...", id="trunc"),
pytest.param("0123456789", 1, "0...", id="minimal trunc"),
pytest.param("", 10, "", id="empty string"),
pytest.param(
b"0123456789", 11, b"0123456789", id="no trunc, greater than limit"
),
pytest.param(b"0123456789", 10, b"0123456789", id="no trunc, equal limit"),
pytest.param(b"0123456789", 9, b"012345678...", id="trunc"),
pytest.param(b"0123456789", 1, b"0...", id="minimal trunc"),
pytest.param(b"", 10, b"", id="empty string"),
),
)
def test_truncate_text(text, limit, expected):
assert truncate_text(text, limit) == expected
def test_truncate(text, limit, expected):
assert truncate(text, limit) == expected


@pytest.mark.parametrize(
"text, limit",
(
pytest.param("0123456789", 0, id="zero"),
pytest.param("0123456789", -1, id="negative"),
pytest.param(b"0123456789", 0, id="zero"),
pytest.param(b"0123456789", -1, id="negative"),
),
)
def test_truncate_text_raises_value_error(text, limit):
def test_truncate_raises_value_error(text, limit):
with pytest.raises(ValueError, match=r"^limit must be greater than 0$"):
assert truncate_text(text, limit)
assert truncate(text, limit)

0 comments on commit 42cd062

Please sign in to comment.