diff --git a/.woodpecker.yml b/.woodpecker.yml index 6c393c9..623affb 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -1,5 +1,4 @@ pipeline: - # TODO add config for all other versions test-3.9: group: test image: python:3.9-alpine diff --git a/app/logger.py b/app/logger.py index 81d7cd0..245eeed 100644 --- a/app/logger.py +++ b/app/logger.py @@ -47,6 +47,34 @@ class Logger: if not append: self.log_file.unlink(missing_ok=True) + def custom(self, message: str, header: str = None): + """Log a message given a header and a message. + + If a header is provided (aka truthy), the final form of the messsage + wil be: + + `[YYYY-MM-DD HH:MM:SS][header] message` + + Otherwise, it's just: + + `[YYYY-MM-DD HH:MM:SS] message` + + Args: + message: the message to display + header: the header to add to the message + """ + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + log_message = f"[{timestamp}] {message}\n" + + if header: + log_message = f"[{timestamp}][{header}] {message}\n" + + if self.log_file: + self.log_file.write_text(log_message) + + if self.stdout: + sys.stdout.write(log_message) + def log(self, level: int, message: str): """Log a message with a specific level. @@ -58,14 +86,7 @@ class Logger: return level_name = self.LOG_LEVELS[level - 1].upper() - timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - log_message = f"[{timestamp}][{level_name}]{message}\n" - - if self.log_file: - self.log_file.write_text(log_message) - - if self.stdout: - sys.stdout.write(log_message) + self.custom(level_name, message) def debug(self, message: str): """Log a debug message.""" diff --git a/tests/test_logger.py b/tests/test_logger.py new file mode 100644 index 0000000..ff2debd --- /dev/null +++ b/tests/test_logger.py @@ -0,0 +1,23 @@ +"""Tests for the logger module.""" +from app.logger import Logger +from datetime import datetime + + +def test_custom_stdout(capfd): + """Test the custom command.""" + logger = Logger() + + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + logger.custom("a message", header="cewl") + + out, _ = capfd.readouterr() + + assert out == f"[{timestamp}][cewl] a message\n" + + +def test_log_stdout(capfd): + """Test the log command with several levels.""" + + logger = Logger() + + # TODO