aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--hazwaz/command.py26
-rw-r--r--tests/test_command.py42
2 files changed, 61 insertions, 7 deletions
diff --git a/hazwaz/command.py b/hazwaz/command.py
index e966792..185070f 100644
--- a/hazwaz/command.py
+++ b/hazwaz/command.py
@@ -38,6 +38,10 @@ class MainCommand:
"""
The subcommands: a tuple of :py:class:`Command` subclasses.
"""
+ logformat = "%(levelname)s:%(name)s: %(message)s"
+ """
+ The format passed to logging.Formatter.
+ """
def __init__(self):
desc = _get_first_docstring_line(self)
@@ -89,13 +93,12 @@ class MainCommand:
help="Show debug messages",
)
- def run(self):
- """
- Run the command.
-
- This is the method called to start running the command.
- """
- self.args = self.parser.parse_args()
+ def setup_logging(self):
+ logger = logging.getLogger()
+ handler = logging.StreamHandler()
+ formatter = logging.Formatter(self.logformat)
+ handler.setFormatter(formatter)
+ logger.addHandler(handler)
if getattr(self.args, "debug", False):
logger.setLevel(logging.DEBUG)
@@ -104,6 +107,15 @@ class MainCommand:
else:
logger.setLevel(logging.WARNING)
+ def run(self):
+ """
+ Run the command.
+
+ This is the method called to start running the command.
+ """
+ self.args = self.parser.parse_args()
+ self.setup_logging()
+
self.args.subcommand.args = self.args
self.args.subcommand.main()
diff --git a/tests/test_command.py b/tests/test_command.py
index 2f9850d..cc64b8f 100644
--- a/tests/test_command.py
+++ b/tests/test_command.py
@@ -1,5 +1,6 @@
import contextlib
import io
+import logging
import sys
import unittest
@@ -25,6 +26,17 @@ class MySubCommand(hazwaz.Command):
print("Hello World")
+class LoggingSubCommand(hazwaz.Command):
+ """
+ A subcommand that logs on various levels.
+ """
+
+ def main(self):
+ logging.debug("This is a DEBUG message")
+ logging.info("This is an INFO message")
+ logging.warning("This is a WARNING message")
+
+
class MyCommand(hazwaz.MainCommand):
"""
A command that does things.
@@ -33,6 +45,7 @@ class MyCommand(hazwaz.MainCommand):
"""
commands = (
MySubCommand(),
+ LoggingSubCommand(),
)
def add_arguments(self, parser):
@@ -158,6 +171,35 @@ class testCommand(unittest.TestCase):
stream = self._run_with_argv(cmd, ["mycommand"])
self.assertEqual(stream["stdout"].getvalue(), cmd_help)
+ def test_logging_regular(self):
+ cmd = MyCommand()
+ with self.assertLogs() as cm:
+ self._run_with_argv(cmd, [
+ "mycommand",
+ "loggingsubcommand",
+ ])
+ self.assertEqual(len(cm.output), 1)
+
+ def test_logging_verbose(self):
+ cmd = MyCommand()
+ with self.assertLogs() as cm:
+ self._run_with_argv(cmd, [
+ "mycommand",
+ "--verbose",
+ "loggingsubcommand",
+ ])
+ self.assertEqual(len(cm.output), 2)
+
+ def test_logging_debug(self):
+ cmd = MyCommand()
+ with self.assertLogs() as cm:
+ self._run_with_argv(cmd, [
+ "mycommand",
+ "--debug",
+ "loggingsubcommand",
+ ])
+ self.assertEqual(len(cm.output), 3)
+
if __name__ == '__main__':
unittest.main()