Pretty Print Django POST Data in Python Logger

Due to customer requirements, I have a webpage with several forms, and dynamic formsets that are built on the client side using jquery formset. Kind of reminds me of the Simpsons episode where Homer designs a car. But here at ROI Technologies LLC, we are not girly men. We laugh in the face of complexity. And every once in a while complexity bites us in the ass.

Obviously, the best solution is to write extensive tests. Unless of course you include costs in your calculation of your “best” metric. An alternative to automatic testing is using the Python logger to gather the info you will need to quickly fix a bug if one is encountered. That’s what this post is about.

Back to my Homer page, as you can imagine, the POST data is extensive. To output it in a readable format in the logs, use json. Like this

try:
    is_valid = my_form.is_valid()
except:
    # Grab the data to fix the bug
    logger.exception('Got exception while validating form:')
    logger.debug('Here is the post data:\n %s', json.dumps(request.POST, indent=4, sort_keys=True))
    raise #  back to crashing

That first logger line in the exception handler, prints that message along with the traceback! The second logger line uses json to pretty print the Django POST data. Happy debugging.

Advertisements

2 thoughts on “Pretty Print Django POST Data in Python Logger

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s