Commits

Lee McFadden committed 5fe3d24

Added response logging

Comments (0)

Files changed (2)

src/lumberjack/middleware.py

 from couchdbkit import Server
 from schema import Log
-from datetime import datetime
+from time import time
 
 class LumberjackMiddleware(object):
     """Use this middleware to log HTTP Requests to a CouchDB
     instance.
     """
-    def __init__(self, app, host='http://127.0.0.1:5984',
+    def __init__(self, app, app_label="default", host='http://127.0.0.1:5984',
                  db="lumberjack"):
         self.app = app
+        self.app_label = app_label
         self.host = host
         self.db = db
 
     def __call__(self, environ, start_response):
         # Build the server instance.  New instance per request.
+        log_start = time()
         server = Server(self.host)
         db = server.get_or_create_db(self.db)
         Log.set_db(db)
 
         log = Log()
-        log.log_start = datetime.utcnow()
+        log.app_label = self.app_label
+        log.log_start = log_start
 
         environ['lumberjack.log'] = log
 
-        retval = self.app(environ, start_response)
-
-        from pprint import pformat
-        raise Exception(type(retval))
-
         for k, v in environ.iteritems():
             if not "." in k:
                 log_key = k.lower()
                 setattr(log, log_key, str(v))
         log.reconstruct_url(environ)
 
-        log.log_end = datetime.utcnow()
+        sr_callback = self._sr_callback(start_response, log)
+        log.app_start = time()
+
+        retval = self.app(environ, sr_callback)
+
+        log.app_end = time()
+        log.app_delta = log.app_end - log.app_start
+
         log.save()
         return retval
+
+    def _sr_callback(self, start_response, log):
+        def callback(status, response_headers, exc_info=None):
+            log.status = status
+            log.status_int = int(status.split()[0])
+            log.response_headers = [list(i) for i in response_headers]
+            if exc_info:
+                log.exc_info = list(exc_info)
+            start_response(status, response_headers, exc_info)
+        return callback
+

src/lumberjack/schema.py

     server_protocol = StringProperty()
     url = StringProperty()
 
+    status = StringProperty()
+    status_int = IntegerProperty()
+    exc_info = ListProperty()
+    response_headers = ListProperty()
+
+    log_start = FloatProperty()
+    app_start = FloatProperty()
+    app_end = FloatProperty()
+    app_delta = FloatProperty()
+    app_label = StringProperty()
+
     def reconstruct_url(self, environ):
         url = "%s://" % environ['wsgi.url_scheme']