Add proper logging to git-pull-hook
authorJan Dittberner <jandd@cacert.org>
Sat, 14 Apr 2018 19:26:05 +0000 (21:26 +0200)
committerJan Dittberner <jandd@cacert.org>
Sat, 14 Apr 2018 19:26:05 +0000 (21:26 +0200)
sitemodules/profiles/files/puppet_server/git-pull-hook
sitemodules/profiles/templates/puppet_server/git-pull-hook.ini.epp

index 32fd1c4..ed34047 100755 (executable)
@@ -10,10 +10,12 @@ Configuration is read from /etc/git-pull-hook.ini, ~/.git-pull-hook.ini and
 a git-pull-hook.ini in the working directory in that order.
 """
 
+import logging
+import logging.config
+import os
 from configparser import ConfigParser
 from http import HTTPStatus
 from http.server import HTTPServer, BaseHTTPRequestHandler
-import os
 from subprocess import Popen, PIPE
 
 ENV_FOR_GIT = {
@@ -23,9 +25,11 @@ ENV_FOR_GIT = {
 TOKENS = []
 GIT_DIRECTORY = ""
 
+LOGGER = None
+
 
 def read_ini():
-    global ENV_FOR_GIT, TOKENS, GIT_DIRECTORY
+    global ENV_FOR_GIT, TOKENS, GIT_DIRECTORY, LOGGER
     config = ConfigParser()
     config.read(['/etc/git-pull-hook.ini',
                  os.path.expanduser('~/.git-pull-hook.ini'),
@@ -35,6 +39,30 @@ def read_ini():
               config['git-pull-hook']['tokens'].split(',')]
     GIT_DIRECTORY = config['git-pull-hook']['git_directory']
 
+    logging.config.dictConfig({
+        'version': 1,
+        'formatters': {
+            'full': {
+                'format': '%(asctime)s %(levelname)-8s %(message)s',
+                'datefmt': '%Y-%m-%d %H:%M:%S',
+            }
+        },
+        'handlers': {
+            'file': {
+                'class': 'logging.FileHandler',
+                'filename': config.get('git-pull-hook', 'logfile'),
+                'formatter': 'full',
+            },
+        },
+        'loggers': {
+            'git-pull-hook': {
+                'handlers': ['file'],
+                'level': 'INFO',
+            }
+        }
+    })
+    LOGGER = logging.getLogger('git-pull-hook')
+
 
 class GitHookRequestHandler(BaseHTTPRequestHandler):
     """
@@ -42,6 +70,11 @@ class GitHookRequestHandler(BaseHTTPRequestHandler):
     with a known authentication token in an "Authentication" HTTP header.
     """
 
+    def __init__(self, request, client_address, server):
+        global LOGGER
+        self.log = LOGGER
+        super().__init__(request, client_address, server)
+
     def _send_data(self, message):
         self.send_header("Content-Type", "text/plain; charset=utf8")
         self.end_headers()
@@ -75,14 +108,20 @@ class GitHookRequestHandler(BaseHTTPRequestHandler):
             if self.headers['Authentication'] in [token for token in TOKENS]:
                 self._handle_pull()
             else:
-                self.send_response(HTTPStatus.UNAUTHORIZED)
-                self._send_data('You have to send a valid token in the "Authentication" header.')
+                self.send_error(HTTPStatus.UNAUTHORIZED,
+                                'You have to send a valid token in the "Authentication" header.')
         elif self.path == '/health':
             self.send_response(HTTPStatus.OK)
             self._send_data("I'm healthy!")
         else:
-            self.send_error(HTTPStatus.BAD_REQUEST)
-            self._send_data("You requested something I do not understand.")
+            self.send_error(HTTPStatus.BAD_REQUEST,
+                            "You requested something I do not understand.")
+
+    def log_error(self, format, *args):
+        self.log.error("%s - %s" % (self.address_string(), format), *args)
+
+    def log_message(self, format, *args):
+        self.log.info("%s - %s" % (self.address_string(), format), *args)
 
 
 def run(server_class=HTTPServer, handler_class=GitHookRequestHandler):
index 8d292b2..2876c16 100644 (file)
@@ -6,3 +6,4 @@
 ssh_passphrase=<%= $ssh_passphrase %>
 tokens=<%= $tokens.join(',') %>
 git_directory=<%= $git_directory %>
+logfile=/var/log/git-pull-hook.log