Skip to content

Commit

Permalink
Structured logging: DRYing and adding comments (#109)
Browse files Browse the repository at this point in the history
  • Loading branch information
nateinaction authored Jan 24, 2025
1 parent 0079c5b commit 6673f16
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 58 deletions.
117 changes: 61 additions & 56 deletions lib/pysquared/logger.py
Original file line number Diff line number Diff line change
@@ -1,80 +1,85 @@
"""
Logger class for handling logging messages with different severity levels.
Logs can be output to standard output or saved to a file (functionality to be implemented).
"""

import json
import time

import adafruit_logging as logging
# from adafruit_blinka import Enum

# class DebugMode(Enum):
# PRINTMODE = False
# DEBUGMODE = True


class Logger:
def __init__(self):
self.internal_logger = logging.getLogger("logger")
self.internal_logger.setLevel(logging.DEBUG)
self.logToFile = False
self.logToStandardOut = True
# self.debugmode = DebugMode.DEBUGMODE
# self.logToFile = False

# @blakejameson NOTE: functionality to save logs to file will be implemented at a later point. For now, logs will
# be output to standard output
# def saveLogToFile():
# pass

def setLogToFile(self):
self.logToFile = True
self.logToStandardOut = False

def setLogToStdOut(self):
self.logToStandardOut = True
self.logToFile = False

def debug(self, filename, **kwargs):
now = time.localtime()
asctime = f"{now.tm_year}-{now.tm_mon:02d}-{now.tm_mday:02d} {now.tm_hour:02d}:{now.tm_min:02d}:{now.tm_sec:02d}"
kwargs["time"] = asctime
kwargs["level"] = "DEBUG"
kwargs["file"] = filename
json_output = json.dumps(kwargs)

if self.logToStandardOut:
print(json_output)

def info(self, filename, **kwargs):
now = time.localtime()
asctime = f"{now.tm_year}-{now.tm_mon:02d}-{now.tm_mday:02d} {now.tm_hour:02d}:{now.tm_min:02d}:{now.tm_sec:02d}"
kwargs["time"] = asctime
kwargs["level"] = "INFO"
kwargs["file"] = filename
json_output = json.dumps(kwargs)

if self.logToStandardOut:
print(json_output)
# def setLogToFile(self):
# """
# Set the logger to save logs to a file.
# """
# self.logToFile = True
# self.logToStandardOut = False

# def setLogToStdOut(self):
# """
# Set the logger to output logs to standard output.
# """
# self.logToStandardOut = True
# self.logToFile = False

def _log(self, level: str, message: str, **kwargs):
"""
Log a message with a given severity level and any addional key/values.
"""
kwargs["level"] = level
kwargs["msg"] = message

def warning(self, filename, **kwargs):
now = time.localtime()
asctime = f"{now.tm_year}-{now.tm_mon:02d}-{now.tm_mday:02d} {now.tm_hour:02d}:{now.tm_min:02d}:{now.tm_sec:02d}"
kwargs["time"] = asctime
kwargs["level"] = "WARNING"
kwargs["file"] = filename
json_output = json.dumps(kwargs)

if self.logToStandardOut:
print(json_output)

def error(self, filename, **kwargs):
now = time.localtime()
asctime = f"{now.tm_year}-{now.tm_mon:02d}-{now.tm_mday:02d} {now.tm_hour:02d}:{now.tm_min:02d}:{now.tm_sec:02d}"
kwargs["time"] = asctime
kwargs["level"] = "ERROR"
kwargs["file"] = filename
json_output = json.dumps(kwargs)

if self.logToStandardOut:
print(json_output)

def critical(self, filename, **kwargs):
now = time.localtime()
asctime = f"{now.tm_year}-{now.tm_mon:02d}-{now.tm_mday:02d} {now.tm_hour:02d}:{now.tm_min:02d}:{now.tm_sec:02d}"
kwargs["time"] = asctime
kwargs["level"] = "CRITICAL"
kwargs["file"] = filename
json_output = json.dumps(kwargs)

if self.logToStandardOut:
print(json_output)
def debug(self, message: str, **kwargs):
"""
Log a message with severity level DEBUG.
"""
self._log("DEBUG", message, **kwargs)

def info(self, message: str, **kwargs):
"""
Log a message with severity level INFO.
"""
self._log("INFO", message, **kwargs)

def warning(self, message: str, **kwargs):
"""
Log a message with severity level WARNING.
"""
self._log("WARNING", message, **kwargs)

def error(self, message: str, **kwargs):
"""
Log a message with severity level ERROR.
"""
self._log("ERROR", message, **kwargs)

def critical(self, message: str, **kwargs):
"""
Log a message with severity level CRITICAL.
"""
self._log("CRITICAL", message, **kwargs)
2 changes: 0 additions & 2 deletions lib/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
adafruit-circuitpython-asyncio @ git+https://github.com/adafruit/[email protected]
adafruit-circuitpython-drv2605==1.3.4
adafruit-circuitpython-lis2mdl==2.1.23
adafruit-circuitpython-logging==5.5.2
adafruit-circuitpython-lsm303-accel==1.1.22
adafruit-circuitpython-lsm6ds==4.5.13
adafruit-circuitpython-mcp9808==3.3.24
adafruit-circuitpython-neopixel==6.3.12
Expand Down
16 changes: 16 additions & 0 deletions tests/unit/lib/pysquared/test_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import pytest

from lib.pysquared.logger import Logger


@pytest.fixture
def logger():
return Logger()


def test_debug_log(capsys, logger):
logger.debug("This is a debug message", blake="jameson")
captured = capsys.readouterr()
assert "DEBUG" in captured.out
assert "This is a debug message" in captured.out
assert '"blake": "jameson"' in captured.out

0 comments on commit 6673f16

Please sign in to comment.