Permalink
Browse files

Log JSON error responses from Solitude

  • Loading branch information...
1 parent 01f6f88 commit 6e42a6e25d4fe416cfeeae2dc5a1e9f24f17a911 @kumar303 kumar303 committed Dec 31, 2012
Showing with 47 additions and 8 deletions.
  1. +24 −7 webpay/base/middleware.py
  2. +22 −1 webpay/base/tests/test_middleware.py
  3. +1 −0 webpay/settings/base.py
@@ -1,14 +1,37 @@
import json
-import pprint
import sys
import traceback
+import commonware.log
from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.utils.translation.trans_real import parse_accept_lang_header
import tower
+log = commonware.log.getLogger('w.middleware')
+
+
+class LogJSONerror:
+ """
+ If the exception has JSON content, log the JSON message.
+ This is intended to catch and log Solitude error messages
+ such as form errors for 400 errors.
+ """
+ def process_exception(self, request, exception):
+ etype = type(exception)
+ if hasattr(etype, '__name__'):
+ etype = etype.__name__
+ if hasattr(exception, 'content'):
+ try:
+ log.error('%s: %s: JSON: %s'
+ % (etype, exception,
+ json.loads(exception.content)))
+ except ValueError:
+ log.error('%s: %s: %s... (not JSON content)'
+ % (etype, exception,
+ str(exception.content)[0:50]))
+
class LogExceptionsMiddleware:
"""
@@ -18,12 +41,6 @@ class LogExceptionsMiddleware:
would not otherwise show the Django debug page.
"""
def process_exception(self, request, exception):
- if hasattr(exception, 'content'):
- try:
- # Solitude JSON error.
- pprint.pprint(json.loads(exception.content))
- except Exception, exc:
- print 'Could not load exception as JSON: %s' % exc
traceback.print_exception(*sys.exc_info())
@@ -1,3 +1,5 @@
+import json
+
from django import http
from django.conf import settings
from django.test import TestCase
@@ -6,7 +8,7 @@
import fudge
from nose.tools import eq_
-from webpay.base.middleware import LocaleMiddleware
+from webpay.base.middleware import LocaleMiddleware, LogJSONerror
class TestLocaleMiddleware(TestCase):
@@ -68,3 +70,22 @@ def test_lang_non_existant(self):
def test_no_input(self):
eq_(self.process()[0], settings.LANGUAGE_CODE)
+
+
+class ExcWithContent(Exception):
+
+ def __init__(self, msg, content):
+ Exception.__init__(self, msg)
+ self.content = content
+
+
+class TestLogJSONerror(TestCase):
+
+ def test_json(self):
+ err = LogJSONerror()
+ exc = ExcWithContent('msg', json.dumps({'foo': 'bar'}))
+ err.process_exception(None, exc)
+
+ def test_not_json(self):
+ err = LogJSONerror()
+ err.process_exception(None, ExcWithContent('msg', '}]not valid JSON'))
@@ -139,6 +139,7 @@
'commonware.middleware.FrameOptionsHeader',
'mobility.middleware.DetectMobileMiddleware',
'mobility.middleware.XMobileMiddleware',
+ 'webpay.base.middleware.LogJSONerror',
)
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

0 comments on commit 6e42a6e

Please sign in to comment.