Repository: witchard/grole

Issue:
Use logging library instead of print

Discussion:

Patch:
diff --git a/grole.py b/grole.py
index be7559d..d1443fd 100755
--- a/grole.py
+++ b/grole.py
@@ -15,6 +15,7 @@ import pathlib
 import html
 import sys
 import argparse
+import logging
 from collections import defaultdict
 
 __author__ = 'witchard'
@@ -310,6 +311,7 @@ class Grole:
         self._handlers = defaultdict(list)
         self.env = {'doc': []}
         self.env.update(env)
+        self._logger = logging.getLogger('grole')
 
     def route(self, path_regex, methods=['GET'], doc=True):
         """
@@ -338,7 +340,7 @@ class Grole:
         Parses requests, finds appropriate handlers and returns responses
         """
         peer = writer.get_extra_info('peername')
-        print('New connection from {}'.format(peer))
+        self._logger.debug('New connection from {}'.format(peer))
         try:
             # Loop handling requests
             while True:
@@ -361,7 +363,7 @@ class Grole:
                                 res = Response(data=res)
                         except:
                             # Error - log it and return 500
-                            traceback.print_exc()
+                            self._logger.error(traceback.format_exc())
                             res = Response(code=500, reason='Internal Server Error')
                         break
 
@@ -371,9 +373,9 @@ class Grole:
 
                 # Respond
                 await res._write(writer)
-                print('{}: {} -> {}'.format(peer, req.path,  res.code))
+                self._logger.info('{}: {} -> {}'.format(peer, req.path,  res.code))
         except EOFError:
-            print('Connection closed from {}'.format(peer))
+            self._logger.debug('Connection closed from {}'.format(peer))
 
     def run(self, host='localhost', port=1234):
         """
@@ -390,7 +392,7 @@ class Grole:
         server = loop.run_until_complete(coro)
 
         # Run the server
-        print('Serving on {}'.format(server.sockets[0].getsockname()))
+        self._logger.info('Serving on {}'.format(server.sockets[0].getsockname()))
         try:
             loop.run_forever()
         except KeyboardInterrupt:
@@ -414,6 +416,11 @@ def parse_args(args=sys.argv[1:]):
                                 default='.')
     parser.add_argument('-n', '--noindex', help='do not show directory indexes',
                                 default=False, action='store_true')
+    loglevel = parser.add_mutually_exclusive_group()
+    loglevel.add_argument('-v', '--verbose', help='verbose logging',
+                                default=False, action='store_true')
+    loglevel.add_argument('-q', '--quiet', help='quiet logging',
+                                default=False, action='store_true')
     return parser.parse_args(args)
 
 def main(args=sys.argv[1:]):
@@ -421,6 +428,12 @@ def main(args=sys.argv[1:]):
     Run Grole static file server
     """
     args = parse_args(args)
+    if args.verbose:
+        logging.basicConfig(level=logging.DEBUG)
+    elif args.quiet:
+        logging.basicConfig(level=logging.ERROR)
+    else:
+        logging.basicConfig(level=logging.INFO)
     app = Grole()
     serve_static(app, '', args.directory, not args.noindex)
     app.run(args.address, args.port)


Test patch:
diff --git a/test/test_args.py b/test/test_args.py
index 5c50383..97a2df6 100644
--- a/test/test_args.py
+++ b/test/test_args.py
@@ -10,11 +10,21 @@ class TestArgs(unittest.TestCase):
         self.assertEqual(args.port, 1234)
         self.assertEqual(args.directory, '.')
         self.assertEqual(args.noindex, False)
+        self.assertEqual(args.verbose, False)
+        self.assertEqual(args.quiet, False)
 
     def test_override(self):
-        args = grole.parse_args(['-a', 'foo', '-p', '27', '-d', 'bar', '-n'])
+        args = grole.parse_args(['-a', 'foo', '-p', '27', '-d', 'bar', '-n', '-v'])
         self.assertEqual(args.address, 'foo')
         self.assertEqual(args.port, 27)
         self.assertEqual(args.directory, 'bar')
         self.assertEqual(args.noindex, True)
+        self.assertEqual(args.verbose, True)
+        self.assertEqual(args.quiet, False)
 
+    def test_error(self):
+        try:
+            grole.parse_args(['-q', '-v'])
+        except SystemExit:
+            return
+        self.fail('Did not error on mutually exclusive args')