Skip to content

Commit

Permalink
better logs with loguru
Browse files Browse the repository at this point in the history
  • Loading branch information
avaldebe committed Dec 8, 2022
1 parent 60269f7 commit 43cae17
Show file tree
Hide file tree
Showing 8 changed files with 24 additions and 28 deletions.
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ packages = [{ include = "pms", from = "src" }]
python = ">=3.8,<4.0"
pyserial = ">=3.5"
typer = ">=0.6.1"
loguru = ">=0.6.0"
importlib-metadata = { version = ">=3.6", python = "<3.10" }
# extras
paho-mqtt = { version = ">=1.4.0", optional = true }
Expand Down Expand Up @@ -177,6 +178,7 @@ module = [
"typer.*",
"packaging.*",
"pytest",
"loguru",
]
ignore_missing_imports = true

Expand Down
3 changes: 0 additions & 3 deletions src/pms/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import logging


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

Expand Down
24 changes: 13 additions & 11 deletions src/pms/cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import logging
import os
import sys
from datetime import datetime
from enum import Enum
Expand All @@ -11,12 +9,13 @@
else: # pragma: no cover
import importlib_metadata as metadata

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

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

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


"""
Extra cli commands from plugins
Expand All @@ -27,9 +26,6 @@
main.command(name=ep.name)(ep.load())


logging.basicConfig(level=os.getenv("LEVEL", "WARNING"))


def version_callback(value: bool): # pragma: no cover
if not value:
return
Expand All @@ -50,7 +46,17 @@ def callback(
version: Optional[bool] = Option(None, "--version", "-V", callback=version_callback),
):
"""Read serial sensor"""
logger.setLevel("DEBUG" if debug else os.getenv("LEVEL", "WARNING"))
if not debug:
logger.configure(
handlers=[
{
"sink": sys.stderr,
"format": "<level>{message}</level>",
"level": "INFO",
},
],
)

ctx.obj = {"reader": SensorReader(model, port, seconds, samples)}


Expand Down Expand Up @@ -136,7 +142,3 @@ def csv(
csv.write("time,sensor,hex\n")
for raw in reader(raw=True):
csv.write(f"{raw.time},{sensor_name},{raw.hex}\n")


if __name__ == "__main__": # pragma: no cover
main()
3 changes: 1 addition & 2 deletions src/pms/core/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"""
from __future__ import annotations

import logging
import sys
import time
from abc import abstractmethod
Expand All @@ -17,14 +16,14 @@
from textwrap import wrap
from typing import Iterator, NamedTuple

from loguru import logger
from serial import Serial
from typer import progressbar

from pms import SensorNotReady, SensorWarning
from pms.core import Sensor, Supported
from pms.core.types import ObsData

logger = logging.getLogger(__name__)
"""translation table for raw.hexdump(n)"""
HEXDUMP_TABLE = bytes.maketrans(
bytes(range(0x20)) + bytes(range(0x7E, 0x100)), b"." * (0x20 + 0x100 - 0x7E)
Expand Down
5 changes: 2 additions & 3 deletions src/pms/core/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"""
from __future__ import annotations

import logging
import sys
from datetime import datetime
from enum import Enum
Expand All @@ -13,11 +12,11 @@
else: # pragma: no cover
import importlib_metadata as metadata

from loguru import logger

from pms import InconsistentObservation, SensorWarmingUp, WrongMessageChecksum, WrongMessageFormat
from pms.core.types import Cmd, Commands, Message, ObsData

logger = logging.getLogger(__name__)


class Sensor(Enum):
"""Sensor modules
Expand Down
5 changes: 2 additions & 3 deletions src/pms/extra/mqtt.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
from __future__ import annotations

import logging
from dataclasses import fields
from datetime import datetime
from typing import Callable, NamedTuple

from loguru import logger
from typer import Abort, Context, Option, colors, echo, style

try:
from paho.mqtt import client # type: ignore
except ModuleNotFoundError:
client = None # type: ignore


from pms.core import exit_on_fail
from pms.sensors.base import ObsData

logger = logging.getLogger(__name__)


def __missing_mqtt(): # pragma: no cover
name = style(__name__, fg=colors.GREEN, bold=True)
Expand Down
5 changes: 2 additions & 3 deletions src/pms/sensors/base.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
from __future__ import annotations

import logging
import warnings
from abc import ABCMeta, abstractmethod
from dataclasses import asdict, dataclass
from datetime import datetime
from typing import NamedTuple, Tuple

from pms import WrongMessageFormat
from loguru import logger

logger = logging.getLogger(__name__)
from pms import WrongMessageFormat


class Cmd(NamedTuple):
Expand Down
5 changes: 2 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import logging
from contextlib import closing, contextmanager
from csv import DictReader
from enum import Enum
Expand All @@ -9,12 +8,12 @@
from typing import Iterator, List

import pytest
from loguru import logger

from pms.core import Sensor
from pms.core.reader import RawData
from pms.core.types import ObsData

logger = logging.getLogger(__name__)
captured_data = Path("tests/captured_data/data.csv")


Expand Down Expand Up @@ -95,7 +94,7 @@ def options(self, command: str) -> List[str]:
capture=f"csv --overwrite --capture {self}_pypms.csv",
decode=f"serial -f csv --decode {self}_pypms.csv",
).get(command, command)
return f"{capture} --debug {cmd}".split()
return f"{capture} {cmd}".split()

def output(self, ending: str) -> str:
path = captured_data.parent / f"{self}.{ending}"
Expand Down

0 comments on commit 43cae17

Please sign in to comment.