Skip to content

Commit

Permalink
Merge pull request #35 from atugushev/limit-debug-response-data
Browse files Browse the repository at this point in the history
Truncate response data in debug log
  • Loading branch information
shalakhin authored May 20, 2021
2 parents ed4424d + 47c524e commit 9649e8f
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
4 changes: 2 additions & 2 deletions ansq/tcp/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
)
from ansq.tcp.types import TCPConnection as NSQConnectionBase
from ansq.typedefs import TCPResponse
from ansq.utils import validate_topic_channel_name
from ansq.utils import truncate_text, validate_topic_channel_name


class NSQConnection(NSQConnectionBase):
Expand Down Expand Up @@ -295,7 +295,7 @@ async def _parse_data(self) -> bool:
await self._pulse()
return True

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

if response.is_message:
assert isinstance(response, NSQMessageSchema)
Expand Down
8 changes: 8 additions & 0 deletions ansq/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,11 @@ def get_logger(
logging.basicConfig(format=log_format)
logger.setLevel(logging.DEBUG if debug else logging.INFO)
return logger


def truncate_text(text: str, limit: int = 256) -> str:
"""Truncate a given `text` 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
29 changes: 29 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import pytest

from ansq.utils import truncate_text


@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"),
),
)
def test_truncate_text(text, limit, expected):
assert truncate_text(text, limit) == expected


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

0 comments on commit 9649e8f

Please sign in to comment.