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

Disable logging unless code is running in CLI #37

Merged
merged 2 commits into from
Jan 11, 2023
Merged
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
5 changes: 5 additions & 0 deletions src/pms/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
from loguru import logger

logger.disable("pms") # disable logging by default
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure that disabling the longing is the right behaviour for library use.
In principle, the library user should decide the logging level.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have two problems with this:

  1. The default logging level is "DEBUG", which is not a sensible default.
import loguru
loguru.logger.debug('test')
2023-01-07 10:27:45.491 | DEBUG    | __main__:<module>:1 - test
  1. PyPMS logs now have to be configured using a different framework.
import logging
logging.configure({ ... })  # main logging for other libraries

import loguru
loguru.logger.configure(...)  # special config just for PyPMS

Normally I don't need DEBUG logs for PyPMS. If I do need them, then as a developer I am willing to go find out how to turn them on. Conversely, when I start using a library I don't want to spend extra effort working out how to switch all the DEBUG logs off to stop them polluting my normal / day-to-day logs.

logger.disable("pms") seemed like the easiest solution to get back to a sensible default for library users. I also think some documentation would be helpful, but that should be a secondary priority to just having some sensible defaults in the first place - the priority should be ease of use / minimal setup effort.



class SensorWarning(UserWarning):
"""Recoverable errors"""

Expand Down
20 changes: 12 additions & 8 deletions src/pms/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,24 @@
import importlib_metadata as metadata

from loguru import logger
from typer import Argument, Context, Exit, Option, Typer, echo
from typer import Argument, Context, Exit, Option, Typer, echo, run

from pms.core import MessageReader, SensorReader, Supported, exit_on_fail

main = Typer(help="Data acquisition and logging for Air Quality Sensors with UART interface")

app = Typer(help="Data acquisition and logging for Air Quality Sensors with UART interface")
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why change the name of the CLI entry point?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typer looks for an entry point called main, but I want to make this a function so I can override the logging behaviour before the main CLI starts. We can't have:

main = Typer(...)

...

def main(): ...


"""
Extra cli commands from plugins

additional Typer commands are loaded from plugins (entry points) advertized as `"pypms.extras"`
"""
for ep in metadata.entry_points(group="pypms.extras"):
main.command(name=ep.name)(ep.load())
app.command(name=ep.name)(ep.load())


def main(): # pragma: no cover
logger.enable("pms")
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can this not be done on the CLI callback function?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question. I did try this originally but it doesn't work for testing: some of the other tests execute the callback, which overrides the package default (that logging is disabled).

Since the purpose of the test I added is to check for regression in the package default, I needed to put this line somewhere where no other test would cause it to run.

I admit it's not a great change or a great test, but since this is the second PR to try and make logging work better for library users, I wanted to put something in to protect the behaviour.

app()


def version_callback(value: bool): # pragma: no cover
Expand All @@ -35,7 +39,7 @@ def version_callback(value: bool): # pragma: no cover
raise Exit()


@main.callback()
@app.callback()
def callback(
ctx: Context,
model: Supported = Option(Supported.default, "--sensor-model", "-m", help="sensor model"),
Expand All @@ -60,7 +64,7 @@ def callback(
ctx.obj = {"reader": SensorReader(model, port, seconds, samples)}


@main.command()
@app.command()
def info(ctx: Context): # pragma: no cover
"""Information about the sensor observations"""
sensor = ctx.obj["reader"].sensor
Expand All @@ -84,7 +88,7 @@ def __str__(self) -> str:
return self.value


@main.command()
@app.command()
def serial(
ctx: Context,
format: Optional[Format] = Option(None, "--format", "-f", help="formatted output"),
Expand All @@ -111,7 +115,7 @@ def serial(
echo(str(obs))


@main.command()
@app.command()
def csv(
ctx: Context,
capture: bool = Option(False, "--capture", help="write raw messages instead of observations"),
Expand Down
21 changes: 21 additions & 0 deletions tests/core/reader/test_SensorReader.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import pytest
from _pytest.logging import LogCaptureFixture
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please do not import private modules. Use pytest.LogCaptureFixture instread.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I get an error if I do this:

E   ModuleNotFoundError: No module named 'pytest.logging'

I'm just following loguru's own docs here: https://loguru.readthedocs.io/en/stable/resources/migration.html#making-things-work-with-pytest-and-caplog

from loguru import logger

from pms import SensorWarmingUp, SensorWarning
from pms.core.reader import SensorReader, UnableToRead
from pms.core.sensor import Sensor


@pytest.fixture
def caplog(caplog: LogCaptureFixture):
handler_id = logger.add(caplog.handler, format="{message}")
yield caplog
logger.remove(handler_id)


@pytest.fixture
def mock_sleep(monkeypatch):
def sleep(seconds):
Expand Down Expand Up @@ -233,3 +242,15 @@ def test_reader_sensor_no_response(reader: SensorReader):
pass

assert "did not respond" in str(e.value)


def test_logging(reader: SensorReader, capfd, caplog):
with reader:
obs = tuple(reader())

# check data was read
assert len(obs) == 1
assert obs[0].pm10 == 11822 # type:ignore

# check no logs output
assert caplog.text == ""
12 changes: 6 additions & 6 deletions tests/extra/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ def client_sub(

def test_mqtt(capture, mock_mqtt):

from pms.cli import main
from pms.cli import app

result = runner.invoke(main, capture.options("mqtt"))
result = runner.invoke(app, capture.options("mqtt"))
assert result.exit_code == 0


Expand All @@ -62,9 +62,9 @@ def pub(*, time: int, tags: Dict[str, str], data: Dict[str, float]) -> None:

def test_influxdb(capture, mock_influxdb):

from pms.cli import main
from pms.cli import app

result = runner.invoke(main, capture.options("influxdb"))
result = runner.invoke(app, capture.options("influxdb"))
assert result.exit_code == 0


Expand Down Expand Up @@ -110,8 +110,8 @@ def client_sub(

def test_bridge(mock_bridge):

from pms.cli import main
from pms.cli import app

capture = mock_bridge
result = runner.invoke(main, capture.options("bridge"))
result = runner.invoke(app, capture.options("bridge"))
assert result.exit_code == 0
14 changes: 7 additions & 7 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@
@pytest.mark.parametrize("format", {"csv", "hexdump"})
def test_serial(capture, format):

from pms.cli import main
from pms.cli import app

result = runner.invoke(main, capture.options(f"serial_{format}"))
result = runner.invoke(app, capture.options(f"serial_{format}"))
assert result.exit_code == 0
assert result.stdout == capture.output(format)


def test_csv(capture):

from pms.cli import main
from pms.cli import app

result = runner.invoke(main, capture.options("csv"))
result = runner.invoke(app, capture.options("csv"))
assert result.exit_code == 0

csv = Path(capture.options("csv")[-1])
Expand All @@ -31,15 +31,15 @@ def test_csv(capture):

def test_capture_decode(capture):

from pms.cli import main
from pms.cli import app

result = runner.invoke(main, capture.options("capture"))
result = runner.invoke(app, capture.options("capture"))
assert result.exit_code == 0

csv = Path(capture.options("capture")[-1])
assert csv.exists()

result = runner.invoke(main, capture.options("decode"))
result = runner.invoke(app, capture.options("decode"))
assert result.exit_code == 0
csv.unlink()
assert result.stdout == capture.output("csv")