Wednesday, June 22, 2011

Django: Logging Quickstart in Django 1.3

Logging is always one of those things that seems like there is a lot of boilerplate code that I tend to always have to lookup oneline each time.  Though logging is very customizable, most of the time I need simply to only need log to a file or files.   Therefore, I'm writing this in hopes of compling a simple configuration that can be dropped into a project.  My understanding is still rudimentary so feel free to drop a comment.

A logging framework is built into Django 1.3 which makes it easier to integrate into a given project.  The logging framework contains three main components: formatters, handlers, and loggers.  Formatters determine how the output will be displayed when it is logged.  Handlers handle where output is logged, whether that be a file, the counsole, or an email.  Loggers are associated with handlers and are the objects that one interacts with when logging something.  As in the example below, more than one formatter, handler or logger can be defined in a project.

In settings.py:
import os

# choose a path that is your virtual environment root
VENV_ROOT = os.path.join('/','web','myvenv')

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file_userlogins': {                # define and name a handler
            'level': 'DEBUG',
            'class': 'logging.FileHandler', # set the logging class to log to a file
            'formatter': 'verbose',         # define the formatter to associate
            'filename': os.path.join(VENV_ROOT, 'log', 'userlogins.log') # log file
        },

        'file_usersaves': {                 # define and name a second handler
            'level': 'DEBUG',
            'class': 'logging.FileHandler', # set the logging class to log to a file
            'formatter': 'verbose',         # define the formatter to associate
            'filename': os.path.join(VENV_ROOT, 'log', 'usersaves.log')  # log file
        },
    },
    'loggers': {
        'logview.userlogins': {              # define a logger - give it a name
            'handlers': ['file_userlogins'], # specify what handler to associate
            'level': 'INFO',                 # specify the logging level
            'propagate': True,
        },     

        'logview.usersaves': {               # define another logger
            'handlers': ['file_usersaves'],  # associate a different handler
            'level': 'INFO',                 # specify the logging level
            'propagate': True,
        },        
    }       
}

In application code such as in views.py:
import logging   # import the required logging module
logger_logins = logging.getLogger('logview.userlogins')  # logger from settings.py
logger_logins.info('Log info')
logger_logins.debug('Log Debug information %s' % ("can pass in variables"))

# we can log to a different file using the other logger
logger_saves = logging.getLogger('logview.usersaves')
logger_saves.error('log an error')

Tuesday, June 7, 2011

Django: Executing manage.py from Anywhere

One nice convenience would be to have a way to call manage.py from anywhere within a virtual environment.  For example, if I want to execute 'manage.py shell', it would be nice to be able to execute that from anywhere rather than having to change directory to where manage.py lives.

We can already run management commands from anywhere using django-admin by utilizing the --settings flag, but doing this requires a lot of typing. And wrapping the django-admin in a shell script seems inelegant somehow.

Instead, I wrote a small python script based off of manage.py.  This can be placed in the ./bin directory in the virtualenv.  The DjangoManageSettings object is meant to be customized on a per project basis, and I intend to make it so it can be passed in from a file configuration somewhere.

Anyway, thought I would share.  I'm curious to see other approaches to this.

# ---------- ${VIRTUAL_ENV}/bin/django_manage.py -------------------------
#!/usr/bin/env python

import os, sys
from django.core.management import execute_manager


class DjangoManageSettings(object):

    def __init__(self):
        self.VENV_ROOT = os.getenv("VIRTUAL_ENV")
        # The name of the module that settings.py resides in
        self.PROJECT_NAME="myproject"
        # The path to the directory where the Django project lives. 
        # I made it relative to the virtualenv root. 
        self.PROJECT_PARENT_PATH = os.path.join(self.VENV_ROOT, "app")
        # The name of the django settings model in the project
        self.SETTINGS_MODULE_NAME='settings'


dm_settings = DjangoManageSettings()

if not dm_settings.VENV_ROOT:
    print("A virtual environment must be activated before using this script.")
    exit(1)


sys.path.insert(0, os.path.join(dm_settings.PROJECT_PARENT_PATH))
mod = __import__(dm_settings.PROJECT_NAME, globals(), locals(), 
                 [dm_settings.SETTINGS_MODULE_NAME])
settings = getattr(mod, dm_settings.SETTINGS_MODULE_NAME)

if __name__ == "__main__":
    execute_manager(settings)