Skip to content
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

Fix Listener and ListenerContainer logger names #68

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
22 changes: 11 additions & 11 deletions posttroll/address_receiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

__all__ = ("AddressReceiver", "getaddress")

LOGGER = logging.getLogger(__name__)
logger = logging.getLogger(__name__)

debug = os.environ.get("DEBUG", False)

Expand Down Expand Up @@ -123,7 +123,7 @@
mda = copy.copy(metadata)
mda["receive_time"] = mda["receive_time"].isoformat()
addrs.append(mda)
LOGGER.debug("return address %s", str(addrs))
logger.debug("return address %s", str(addrs))
return addrs

def _check_age(self, pub, min_interval=zero_seconds):
Expand All @@ -132,7 +132,7 @@
if (now - self._last_age_check) <= min_interval:
return

LOGGER.debug("%s - checking addresses", str(dt.datetime.utcnow()))
logger.debug("%s - checking addresses", str(dt.datetime.utcnow()))
self._last_age_check = now
to_del = []
with self._address_lock:
Expand All @@ -144,7 +144,7 @@
"service": metadata["service"]}
msg = Message("/address/" + metadata["name"], "info", mda)
to_del.append(addr)
LOGGER.info(f"publish remove '{msg}'")
logger.info(f"publish remove '{msg}'")
pub.send(str(msg.encode()))
for addr in to_del:
del self._addresses[addr]
Expand All @@ -164,7 +164,7 @@
except TimeoutError:
if self._do_run:
if self._multicast_enabled:
LOGGER.debug("Multicast socket timed out on recv!")
logger.debug("Multicast socket timed out on recv!")
continue
else:
raise
Expand All @@ -178,9 +178,9 @@
ip_, port = fromaddr
if self._restrict_to_localhost and ip_ not in self._local_ips:
# discard external message
LOGGER.debug("Discard external message")
logger.debug("Discard external message")
continue
LOGGER.debug("data %s", data)
logger.debug("data %s", data)
msg = Message.decode(data)
name = msg.subject.split("/")[1]
if msg.type == "info" and msg.subject.lower().startswith(self._subject):
Expand All @@ -189,10 +189,10 @@
metadata = copy.copy(msg.data)
metadata["name"] = name

LOGGER.debug("receiving address %s %s %s", str(addr),
logger.debug("receiving address %s %s %s", str(addr),
str(name), str(metadata))
if addr not in self._addresses:
LOGGER.info("nameserver: publish add '%s'",
logger.info("nameserver: publish add '%s'",
str(msg))
pub.send(msg.encode())
self._add(addr, metadata)
Expand All @@ -209,7 +209,7 @@
recv = MulticastReceiver(port)
except IOError as err:
if err.errno == errno.ENODEV:
LOGGER.error("Receiver initialization failed "
logger.error("Receiver initialization failed "

Check warning on line 212 in posttroll/address_receiver.py

View check run for this annotation

Codecov / codecov/patch

posttroll/address_receiver.py#L212

Added line #L212 was not covered by tests
"(no such device). "
"Trying again in %d s",
10)
Expand All @@ -218,7 +218,7 @@
raise
else:
recv.settimeout(tout=2.0)
LOGGER.info("Receiver initialized.")
logger.info("Receiver initialized.")
break

else:
Expand Down
4 changes: 2 additions & 2 deletions posttroll/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
class ListenerContainer:
"""Container for a listener instance."""

logger = logging.getLogger("ListenerContainer")
logger = logging.getLogger(__name__ + ".ListenerContainer")

def __init__(self, topics=None, addresses=None, nameserver="localhost", services=""):
"""Initialize the class."""
Expand Down Expand Up @@ -82,7 +82,7 @@ def stop(self):
class Listener:
"""PyTroll listener class for reading messages for eg. operational product generation."""

logger = logging.getLogger("Listener")
logger = logging.getLogger(__name__ + ".Listener")

def __init__(self, topics=None, queue=None, addresses=None,
nameserver="localhost", services=""):
Expand Down
37 changes: 24 additions & 13 deletions posttroll/tests/test_pubsub.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

"""Test the publishing and subscribing facilities."""

import logging
import time
import unittest
from contextlib import contextmanager
Expand Down Expand Up @@ -198,6 +199,11 @@ def _get_port_from_publish_instance(min_port=None, max_port=None):
class TestListenerContainerNoNameserver(unittest.TestCase):
"""Testing listener container without nameserver."""

@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog):
"""Inject fixtures."""
self._caplog = caplog

def setUp(self):
"""Set up the testing class."""
test_lock.acquire()
Expand All @@ -215,20 +221,25 @@ def test_listener_container(self):
pub = Publisher(pub_addr, name="test")
pub.start()
time.sleep(2)
sub = ListenerContainer(topics=["/counter"], nameserver=False, addresses=[pub_addr])
time.sleep(2)
for counter in range(5):
tested = False
msg_out = Message("/counter", "info", str(counter))
pub.send(str(msg_out))
with self._caplog.at_level(logging.DEBUG):
sub = ListenerContainer(topics=["/counter"], nameserver=False, addresses=[pub_addr])
time.sleep(2)
for counter in range(5):
tested = False
msg_out = Message("/counter", "info", str(counter))
pub.send(str(msg_out))

msg_in = sub.output_queue.get(True, 1)
if msg_in is not None:
assert str(msg_in) == str(msg_out)
tested = True
assert tested
pub.stop()
sub.stop()

msg_in = sub.output_queue.get(True, 1)
if msg_in is not None:
assert str(msg_in) == str(msg_out)
tested = True
assert tested
pub.stop()
sub.stop()
assert "posttroll.listener.ListenerContainer" in self._caplog.text
assert sub.logger.name == "posttroll.listener.ListenerContainer"
assert sub.listener.logger.name == "posttroll.listener.Listener"


# Test create_publisher_from_config
Expand Down