NinjaCipher:-*-:ro60

Handy Django Logger

Here is a handy little logger I wrote for Django. Feel free to use it if you want and to give me your thoughts on improvements. It was my first stab so be gentle. ;)

Big thx to… http://www.linuxjournal.com/article/5821 for exception formatting code…

netflippers.py

from django.conf import settings
import logging
import sys
import traceback

class NFLogger():

    """
        The only requirement for this logger is that you have LOG_FILE
        set in your settings.py
    """
    def __init__(self):
        logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename=settings.LOG_FILE)

    """
        Static method that will call any of our members based on a string name
        for example: NFLogger.message(sys.exc_info(),"exception")
    """
    @staticmethod
    def message(message,methodname='debug'):
        logger = NFLogger()
        if hasattr(logger, methodname):
            _member = getattr(logger, methodname)
            _member(message)
        else:
            logger.debug(message)

    def info(self,message):
        logging.info(message)

    def error(self,message):
        logging.error(message)

    def warn(self,message):
        logging.warn(message)

    def critical(self,message):
        logging.critical(message)

    def debug(self,message):
        logging.debug(message)

    """
        This will output formatted info about the current exception.
        Just pass sys.exc_info() from inside your except block
    """
    def exception(self,sys_exc_info):
         cla, exc, trbk = sys_exc_info
         excName = cla.__name__
         try:
             excArgs = exc.__dict__["args"]
         except KeyError:
             excArgs = “”
         excTb = traceback.format_tb(trbk)
         logging.error(”nException Name: %snException Arguments: %snException Traceback: %sn”,excName, excArgs, excTb)

Just stick this in your Django app and set the path to your desired log file in your settings.py and you should be good to go.

In settings.py

LOG_FILE = '/tmp/pervade.log'

In your code

from pervade.netflippers import NFLogger
NFLogger.message("hi there")

or

NFLogger.message("hi there","info")

Or in an except block:


import sys

try:
    somecode.thaterrorsout
except:
    NFLogger.message(sys.exc_info(),"exception")
Del.icio.us Digg BlinkList Furl Ma.gnolia Reddit Spurl

One Response to “Handy Django Logger”

  1. Ninjacipher » Blog Archive » Django Pagination Wrapper Says:

    [...] NinjaCipher:-*-:ro60 « Handy Django Logger [...]

Leave a Reply

You must be logged in to post a comment.