I work at Tangent Labs, a digital agency, writing applications in python and django. I spend most of my free time hacking. I run commandlinefu.com and am the author of the e-commerce framework django-oscar amongst other things. I used to be a mathematician; I have a PhD in Mathematics from the University of Nottingham and an associated interest in cryptic crosswords, chess and playing devil's advocate. David is a DZone MVB and is not an employee of DZone and has posted 27 posts at DZone. You can read more from them at their website. View Full User Profile

Console Logging to STDOUT in Django

02.13.2012
| 4404 views |
  • submit to reddit

Problem

By default in Python (and Django), the documented console handler emits to STDERR, but you want it to use STDOUT instead. This is often desired for management commands that run as cronjobs.

 

Solution

For Python 2.6, use the following LOGGING config in your settings to specify a different output stream:

import sys
LOGGING = {
    'handlers': {
        'console':{
            'level':'INFO',
            'class':'logging.StreamHandler',
            'strm': sys.stdout
        },
        ...
    }
}


For Python 2.7+, the keyword argument to the constructor of logging.StreamHandler is stream rather than strm. Ensure you use the right version.

Discussion

Django's logging docs detail the following logging configuration for a console handler:

LOGGING = {
    ...
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    ...
}


...however, the default output stream for logging.StreamHandler is STDERR. The extra keyword argument in the solution alter this behaviour to use STDOUT.

Logging to STDERR means that any output from cron jobs is emailed to root. A more desirable behaviour is for only genuine errors to trigger emails, while normal output can be logged to file. Hence, a sensible cronjob file would look something like:

SHELL=/bin/bash
MAILTO=alerts.someproject@yourcompany.co.uk

*/10 * * * * app source /venv/bin/activate && /app/manage.py do_something > /dev/null


Source: http://codeinthehole.com/writing/console-logging-to-stdout-in-django/

Published at DZone with permission of David Winterbottom, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: